repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
LianjiaTech/ProgressLayout
sample/src/main/java/com/lianjiatech/infrastructure/example/SmartTextView.java
864
package com.lianjiatech.infrastructure.example; import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; /** * Created by Joker on 2016/1/3. */ public class SmartTextView extends TextView { public SmartTextView(Context context) { this(context, null); } public SmartTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SmartTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (!this.isInEditMode()) { SmartTextView.this.init(context); } } private void init(Context context) { Typeface typeface = Typeface.createFromAsset(context.getAssets(), "Lobster-Regular.ttf"); this.setTypeface(typeface); } }
apache-2.0
health-and-care-developer-network/health-and-care-developer-network
library/hazelcast/2.5/hazelcast-2.5-source/hazelcast/src/main/java/com/hazelcast/security/UsernamePasswordCredentials.java
2226
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.security; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * Simple implementation of {@link Credentials} using * username and password as security attributes. */ public class UsernamePasswordCredentials extends AbstractCredentials { private static final long serialVersionUID = -1508314631354255039L; private byte[] password; public UsernamePasswordCredentials() { super(); } public UsernamePasswordCredentials(String username, String password) { super(username); this.password = password.getBytes(); } public String getUsername() { return getPrincipal(); } public byte[] getRawPassword() { return password; } public String getPassword() { return password==null? "": new String(password); } public void setUsername(String username) { setPrincipal(username); } public void setPassword(String password) { this.password = password.getBytes(); } public void writeDataInternal(DataOutput out) throws IOException { out.writeInt(password != null ? password.length : 0); if (password != null) { out.write(password); } } public void readDataInternal(DataInput in) throws IOException { int s = in.readInt(); if (s > 0) { password = new byte[s]; in.readFully(password); } } @Override public String toString() { return "UsernamePasswordCredentials [username=" + getUsername() + "]"; } }
apache-2.0
JAVA201708/Homework
201709/20170928/Team2/SunGuiYong/works/work01/Ioob.java
3192
import java.io.InputStreamReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.BufferedReader; import java.io.FileReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.io.IOException; import java.io.FileNotFoundException; import java.util.List; import java.util.ArrayList; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; /** * @version 20170928 * @author sunguiyong * */ @SuppressWarnings("unchecked") public class Ioob { private static final Logger LOGGER = LogManager.getLogger(Ioob.class); public static void main(String[] args) throws Exception { List list = new ArrayList(readTxt()); System.out.println(list); } public static List readTxt() { BufferedReader br = null; List list = new ArrayList(); try { FileInputStream in = new FileInputStream("D:\\myTest\\subject.txt"); br = new BufferedReader(new InputStreamReader(in, "utf-8")); String str = null; while ((str = br.readLine()) != null) { String title = str; String[] options = new String[4]; for (int i = 0; i < options.length; i++) { options[i] = br.readLine(); } String answer = br.readLine(); br.readLine(); Subject subject = new Subject(title, options, answer); list.add(subject); } return list; } catch (FileNotFoundException e) { LOGGER.catching(e); return null; } catch (IOException e) { LOGGER.catching(e); return null; } finally { try { if (br != null) { br.close(); } } catch (IOException e) { LOGGER.catching(e); } } } public static Object readObject() throws Exception { ObjectInputStream objIn = new ObjectInputStream(new FileInputStream("D:\\myTest\\subject")); return objIn.readObject(); } public static void writeObject(Object obj) throws IOException { ObjectOutputStream objOut = new ObjectOutputStream(new FileOutputStream("D:\\myTest\\subject")); objOut.writeObject(obj); objOut.close(); } } class Subject implements Serializable { private String title; private String[] options; private String answer; public Subject(String title, String[] options, String answer) { this.title = title; this.options = options; this.answer = answer; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String[] getOptions() { return options; } public void setOptions(String[] options) { this.options = options; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(this.title).append("\n"); for (String element : options) { sb.append(element).append("\n"); } sb.append(this.answer).append("\n"); sb.append("\n"); return sb.toString(); } }
apache-2.0
like5188/Common
common/src/main/java/com/like/common/base/presenter/BasePresenter.java
757
package com.like.common.base.presenter; import android.content.Context; import android.support.annotation.NonNull; import com.like.common.base.entity.Host; import com.like.rxbus.RxBus; /** * Presenter的基类。持有Host和Context的引用。包含RxBus注册和取消注册。 */ public class BasePresenter { protected Host host; protected Context mContext; public BasePresenter(@NonNull Host host) { this.host = host; mContext = host.getActivity(); RxBus.register(this); } public Host getHost() { return host; } /** * 取消注册过的所有的事件,建议放在Activity的onDestroy()方法中。 */ public void unregister() { RxBus.unregister(this); } }
apache-2.0
huanshiwushuang/GraduationDesign_APP
src/com/guohao/fragment/RecommendFragment.java
13868
package com.guohao.fragment; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.guohao.graduationdesign_app.MoreMovieActivity; import com.guohao.graduationdesign_app.MovieDetailActivity; import com.guohao.graduationdesign_app.R; import com.guohao.inter.HttpCallBackListenerString; import com.guohao.util.Data; import com.guohao.util.HttpUtil; import com.guohao.util.Util; import com.nostra13.universalimageloader.core.ImageLoader; import android.content.Context; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class RecommendFragment extends Fragment { private ListView listView; private View view; private TextView refreshPrompt; private final int Loading_Data_Success = 1; private final int Loading_Data_Fail = 0; private final String Recommend_M = "ÍÆ¼öµçÓ°"; private final String Hot_M = "ÈÈÃŵçÓ°"; private final String Newest_M = "×îеçÓ°"; private final String HighMark_M = "¸ß·ÖµçÓ°"; //ÿÐжàÉÙ²¿ µçÓ° private final int LINE_COUNT = 3; public static final int CLASS_COUNT = 15; //´æ´¢ËùÓÐ-ÿÐÐÊý¾Ý private List<String> list; private RecommendAdapter adapter; //Ë鯬01 ºÍ Ë鯬02 ͬʱÍê³É²ÅÄܹ»dismiss public static Boolean isComplete = false; //±êʶ·û---±íÃ÷ÍøÂçÇëÇóÊÇ·ñÍê³É£¨µ±Öظ´¶à´ÎË¢ÐÂʱºò£¬ÐèÒª±£Ö¤ÔÚ ÍøÂçÊý¾Ý ¼ÓÔØµ½ List Íê³ÉÒԺ󣬲ŽøÐÐÏ´ÎˢУ© private SwipeRefreshLayout refreshLayout; private NetworkInfo info; private Handler handler = new Handler() { private String want,error; private JSONArray array; private String startLine,endLine; @Override public void handleMessage(Message msg) { switch (msg.what) { case Loading_Data_Success: Object[] objects = (Object[]) msg.obj; want = (String) objects[0]; array = (JSONArray) objects[1]; startLine = (String) objects[2]; endLine = (String) objects[3]; next(); setDataInList(); break; case Loading_Data_Fail: Object[] objs = (Object[]) msg.obj; want = (String) objs[0]; error = (String) objs[1]; startLine = (String) objs[2]; endLine = (String) objs[3]; Util.showToast(getActivity(), error); next(); break; } if (want.equals(Data.HighMark)) { RecommendFragment.isComplete = true; if (AllFragment.isComplete) { Util.dismissProgressDialog(); } new Handler().postDelayed(new Runnable() { @Override public void run() { refreshLayout.setRefreshing(false); if (list.size() <= 0) { refreshPrompt.setVisibility(View.VISIBLE); } } }, 700); } } private void setDataInList() { switch (want) { case Data.Recommend: //ռλ×ӵģ¬ÓÃÓÚ hot highMark µÈµÄ±êÌâλÖᣠlist.clear(); list.add(Recommend_M); addDataToList(array); break; case Data.Hot: //ռλ×ӵģ¬ÓÃÓÚ hot highMark µÈµÄ±êÌâλÖᣠlist.add(Hot_M); addDataToList(array); break; case Data.Newest: //ռλ×ӵģ¬ÓÃÓÚ hot highMark µÈµÄ±êÌâλÖᣠlist.add(Newest_M); addDataToList(array); break; case Data.HighMark: //ռλ×ӵģ¬ÓÃÓÚ hot highMark µÈµÄ±êÌâλÖᣠlist.add(HighMark_M); addDataToList(array); break; default: break; } adapter.notifyDataSetChanged(); } private void addDataToList(JSONArray array) { StringBuilder builder = new StringBuilder(); int j = array.length()/LINE_COUNT; int k = array.length()%LINE_COUNT; //ÿÀà-ÓÐÕâô¶àÐУ¨±ÈÈçÈÈÃŵçÓ°£© int m = (k == 0 ? j : j+1); //ÿÀà-×îºóÒ»ÐÐÓжàÉÙ¸ö int p = (k == 0 ? LINE_COUNT : k); //ÿÅŵĸöÊý int o = LINE_COUNT; for (int i = 0; i < m; i++) { j = i*LINE_COUNT; o = (i == m-1 ? p : LINE_COUNT); builder.append("["); for (int n = j; n < j+o; n++) { try { builder.append(array.get(n).toString()); } catch (JSONException e) { e.printStackTrace(); } if (n != j+o-1) { builder.append(","); } } builder.append("]"); list.add(builder.toString()); builder.delete(0, builder.length()); } } private void next() { switch (want) { case Data.Recommend: getData(Data.Hot, startLine, endLine); break; case Data.Hot: getData(Data.Newest, startLine, endLine); break; case Data.Newest: getData(Data.HighMark, startLine, endLine); break; case Data.HighMark: break; } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //ÌØ±ð×¢Ò⣬²»ÄÜÖ¸¶¨µÚ¶þ¸ö²ÎÊý¡£ ÒòΪÕâ¸ö Fragment »á±»Ìí¼Óµ½ ViewPager ÀïÃæ¡£ view = inflater.inflate(R.layout.fragment_recommend, null); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); Util.showProgressDialog(getActivity(), "ÕýÔÚ¼ÓÔØÊý¾Ý..."); info = Util.getNetworkInfo(getActivity()); if (info != null && info.isAvailable()) { getData(Data.Recommend,"1",CLASS_COUNT+""); }else { Util.showToast(getActivity(), "ÎÞÍøÂç"); refreshPrompt.setVisibility(View.VISIBLE); Util.dismissProgressDialog(); } } private void initView() { list = new ArrayList<String>(); listView = (ListView) view.findViewById(R.id.id_listview_recommend); refreshPrompt = (TextView) view.findViewById(R.id.id_textview_refresh_prompt); refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.id_swiperefreshlayout_refresh); refreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light); adapter = new RecommendAdapter(); listView.setAdapter(adapter); refreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { refreshPrompt.setVisibility(View.GONE); info = Util.getNetworkInfo(getActivity()); if (info != null && info.isAvailable()) { getData(Data.Recommend,"1",CLASS_COUNT+""); }else { if (list.size() == 0) { refreshPrompt.setVisibility(View.VISIBLE); } Util.showToast(getActivity(), "ÎÞÍøÂç"); refreshLayout.setRefreshing(false); } } }); } private void getData(final String want, final String startLine, final String endLine) { if (info == null || !info.isAvailable() ) { refreshLayout.setRefreshing(false); Util.showToast(getActivity(), "ÎÞÍøÂç"); return; } HttpUtil.visitMovieInfoTable(want, startLine, endLine, "", "", new HttpCallBackListenerString() { public void onFinish(String response) { Message msg = handler.obtainMessage(); String code = null; String data = null; try { JSONObject object = new JSONObject(response); code = object.getString(Data.KEY_CODE); data = object.getString(Data.KEY_DATA); } catch (JSONException e) { e.printStackTrace(); } if (code.equals(Data.VALUE_OK)) { JSONArray array = null; try { array = new JSONArray(data); } catch (JSONException e) { e.printStackTrace(); } msg.what = Loading_Data_Success; msg.obj = new Object[]{want,array,startLine,endLine}; handler.sendMessage(msg); }else { msg.obj = new Object[]{want,data,startLine,endLine}; msg.what = Loading_Data_Fail; handler.sendMessage(msg); } } public void onError(String e) { Message msg = handler.obtainMessage(); msg.obj = new Object[]{want,e,startLine,endLine}; msg.what = Loading_Data_Fail; handler.sendMessage(msg); } }); } class RecommendAdapter extends BaseAdapter implements OnClickListener { Context mContext; LayoutInflater inflater; final int TYPE_1 = 0; final int TYPE_2 = 1; public RecommendAdapter() { mContext = getActivity(); inflater = LayoutInflater.from(mContext); } public int getCount() { return list.size(); } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { int i = position%(int)(Math.ceil((float)CLASS_COUNT/(float)LINE_COUNT)+1); if (i == TYPE_1) { return TYPE_1; }else { return TYPE_2; } } public Object getItem(int position) { return list.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolderTitle holderTitle = null; ViewHolderContent holderContent = null; int i = getItemViewType(position); String data = list.get(position); if (convertView == null) { switch (i) { case TYPE_1: convertView = inflater.inflate(R.layout.fragment_recommend_item_title, null); holderTitle = new ViewHolderTitle(); holderTitle.name = (TextView) convertView.findViewById(R.id.id_textview_name); holderTitle.more = (TextView) convertView.findViewById(R.id.id_textview_more); convertView.setTag(holderTitle); break; case TYPE_2: convertView = inflater.inflate(R.layout.fragment_recommend_item_content, null); holderContent = new ViewHolderContent(); holderContent.img01 = (ImageView) convertView.findViewById(R.id.id_imageview_img01); holderContent.text01 = (TextView) convertView.findViewById(R.id.id_textview_text01); holderContent.img02 = (ImageView) convertView.findViewById(R.id.id_imageview_img02); holderContent.text02 = (TextView) convertView.findViewById(R.id.id_textview_text02); holderContent.img03 = (ImageView) convertView.findViewById(R.id.id_imageview_img03); holderContent.text03 = (TextView) convertView.findViewById(R.id.id_textview_text03); convertView.setTag(holderContent); break; default: break; } }else { switch (i) { case TYPE_1: holderTitle = (ViewHolderTitle) convertView.getTag(); break; case TYPE_2: holderContent = (ViewHolderContent) convertView.getTag(); break; default: break; } } switch (i) { case TYPE_1: holderTitle.name.setText(data); holderTitle.more.setText("¸ü¶à>>"); holderTitle.more.setTag(R.id.Click_Position, position); holderTitle.more.setTag(R.id.Click_Type, i); holderTitle.more.setOnClickListener(this); break; case TYPE_2: try { JSONArray array = new JSONArray(data); //»ñȡͼƬÐеÄ--¸ù½Úµã LinearLayout layout = (LinearLayout) holderContent.img01.getParent().getParent(); for (int j = 0; j < LINE_COUNT; j++) { LinearLayout l = (LinearLayout) layout.getChildAt(j); l.setVisibility(View.INVISIBLE); } for (int j = 0; j < array.length(); j++) { JSONObject object = array.getJSONObject(j); LinearLayout l = (LinearLayout) layout.getChildAt(j); l.setTag(R.id.Click_Position, position); l.setTag(R.id.Click_Type, i); l.setVisibility(View.VISIBLE); l.setOnClickListener(this); ImageView image = (ImageView) l.getChildAt(0); TextView text = (TextView) l.getChildAt(1); setImage(image, object.getString("moviePicLink")); text.setText(object.getString("movieName")); } } catch (JSONException e) { e.printStackTrace(); } break; default: break; } return convertView; } @Override public void onClick(View v) { int position = (int) v.getTag(R.id.Click_Position); int type = (int) v.getTag(R.id.Click_Type); if (type == TYPE_1) { switch (list.get(position)) { case Recommend_M: MoreMovieActivity.actionStart(getActivity(), Data.Recommend); break; case Hot_M: MoreMovieActivity.actionStart(getActivity(), Data.Hot); break; case Newest_M: MoreMovieActivity.actionStart(getActivity(), Data.Newest); break; case HighMark_M: MoreMovieActivity.actionStart(getActivity(), Data.HighMark); break; default: break; } }else if (type == TYPE_2) { try { JSONArray array = new JSONArray(list.get(position)); JSONObject object = null; switch (v.getId()) { case R.id.id_linearlayout_movie00: object = (JSONObject) array.get(0); break; case R.id.id_linearlayout_movie01: object = (JSONObject) array.get(1); break; case R.id.id_linearlayout_movie02: object = (JSONObject) array.get(2); break; default: return; } MovieDetailActivity.actionStart(getActivity(), object.getString("movieInfoTableId"), object.getString("movieName"), object.getString("moviePicLink")); } catch (JSONException e) { e.printStackTrace(); } } } public void setImage(final ImageView image, String picLink) { info = Util.getNetworkInfo(getActivity()); if (info == null || !info.isAvailable()) { return; } int i = Util.getPreferences(getActivity()).getInt(Data.K_Pic_Loading, Data.V_Pic_Loading_Big); if (i == Data.V_Pic_Loading_Big) { picLink = Util.getBigImageAddress(picLink); } Util.setImageWH(getActivity(), image, LINE_COUNT); ImageLoader loader = ImageLoader.getInstance(); loader.displayImage(picLink, image); } } class ViewHolderTitle { TextView name; TextView more; } class ViewHolderContent { ImageView img01; TextView text01; ImageView img02; TextView text02; ImageView img03; TextView text03; } }
apache-2.0
jl1955/uPortal5
uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/dao/jpa/PortletDefinitionIdImpl.java
2255
/** * Licensed to Apereo under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright ownership. Apereo * 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 the * following location: * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>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.apereo.portal.portlet.dao.jpa; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.apereo.portal.portlet.om.AbstractObjectId; import org.apereo.portal.portlet.om.IPortletDefinitionId; /** * Identifies a portlet definition * */ class PortletDefinitionIdImpl extends AbstractObjectId implements IPortletDefinitionId { private static final long serialVersionUID = 1L; private static final LoadingCache<Long, IPortletDefinitionId> ID_CACHE = CacheBuilder.newBuilder() .maximumSize(1000) .softValues() .build( new CacheLoader<Long, IPortletDefinitionId>() { @Override public IPortletDefinitionId load(Long key) throws Exception { return new PortletDefinitionIdImpl(key); } }); public static IPortletDefinitionId create(long portletDefinitionId) { return ID_CACHE.getUnchecked(portletDefinitionId); } private final long longId; private PortletDefinitionIdImpl(Long portletDefinitionId) { super(portletDefinitionId.toString()); this.longId = portletDefinitionId; } @Override public long getLongId() { return this.longId; } }
apache-2.0
John-Chan/coc-admin
src/org/coc/tools/client/event/ClanUpdateCancelEvt.java
519
package org.coc.tools.client.event; import com.google.gwt.event.shared.GwtEvent; public class ClanUpdateCancelEvt extends GwtEvent<ClanUpdateCancelEvtHandler>{ public static Type<ClanUpdateCancelEvtHandler> TYPE = new Type<ClanUpdateCancelEvtHandler>(); @Override public com.google.gwt.event.shared.GwtEvent.Type<ClanUpdateCancelEvtHandler> getAssociatedType() { return TYPE; } @Override protected void dispatch(ClanUpdateCancelEvtHandler handler) { handler.onCancel(this); } }
apache-2.0
objectiser/overlord-commons
overlord-commons-uiheader/src/test/java/org/overlord/commons/ui/header/MockHttpServletResponse.java
7671
/* * Copyright 2013 JBoss 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 org.overlord.commons.ui.header; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.MultivaluedMap; import org.jboss.resteasy.mock.MockHttpResponse; /** * * @author eric.wittmann@redhat.com */ public class MockHttpServletResponse extends MockHttpResponse implements HttpServletResponse { /** * Constructor. */ public MockHttpServletResponse() { } /** * @see javax.servlet.ServletResponse#getCharacterEncoding() */ @Override public String getCharacterEncoding() { return "UTF-8"; //$NON-NLS-1$ } /** * @see javax.servlet.ServletResponse#getContentType() */ @Override public String getContentType() { return null; } /** * @see javax.servlet.ServletResponse#getWriter() */ @Override public PrintWriter getWriter() throws IOException { return null; } /** * @see javax.servlet.ServletResponse#setCharacterEncoding(java.lang.String) */ @Override public void setCharacterEncoding(String charset) { } /** * @see javax.servlet.ServletResponse#setContentLength(int) */ @Override public void setContentLength(int len) { setIntHeader("Content-Length", len); //$NON-NLS-1$ } /** * @see javax.servlet.ServletResponse#setContentType(java.lang.String) */ @Override public void setContentType(String type) { setHeader("Content-Type", type); //$NON-NLS-1$ } /** * @see javax.servlet.ServletResponse#setBufferSize(int) */ @Override public void setBufferSize(int size) { } /** * @see javax.servlet.ServletResponse#getBufferSize() */ @Override public int getBufferSize() { return 0; } /** * @see javax.servlet.ServletResponse#flushBuffer() */ @Override public void flushBuffer() throws IOException { } /** * @see javax.servlet.ServletResponse#resetBuffer() */ @Override public void resetBuffer() { } /** * @see javax.servlet.ServletResponse#setLocale(java.util.Locale) */ @Override public void setLocale(Locale loc) { } /** * @see javax.servlet.ServletResponse#getLocale() */ @Override public Locale getLocale() { return null; } /** * @see javax.servlet.http.HttpServletResponse#addCookie(javax.servlet.http.Cookie) */ @Override public void addCookie(Cookie cookie) { } /** * @see javax.servlet.http.HttpServletResponse#containsHeader(java.lang.String) */ @Override public boolean containsHeader(String name) { return false; } /** * @see javax.servlet.http.HttpServletResponse#encodeURL(java.lang.String) */ @Override public String encodeURL(String url) { return null; } /** * @see javax.servlet.http.HttpServletResponse#encodeRedirectURL(java.lang.String) */ @Override public String encodeRedirectURL(String url) { return null; } /** * @see javax.servlet.http.HttpServletResponse#encodeUrl(java.lang.String) */ @Override public String encodeUrl(String url) { return null; } /** * @see javax.servlet.http.HttpServletResponse#encodeRedirectUrl(java.lang.String) */ @Override public String encodeRedirectUrl(String url) { return null; } /** * @see javax.servlet.http.HttpServletResponse#sendRedirect(java.lang.String) */ @Override public void sendRedirect(String location) throws IOException { } /** * @see javax.servlet.http.HttpServletResponse#setDateHeader(java.lang.String, long) */ @Override public void setDateHeader(String name, long date) { setHeader(name, "<DATE VALUE>"); //$NON-NLS-1$ } /** * @see javax.servlet.http.HttpServletResponse#addDateHeader(java.lang.String, long) */ @Override public void addDateHeader(String name, long date) { } /** * @see javax.servlet.http.HttpServletResponse#setHeader(java.lang.String, java.lang.String) */ @Override public void setHeader(String name, String value) { super.getOutputHeaders().putSingle(name, value); } /** * @see javax.servlet.http.HttpServletResponse#addHeader(java.lang.String, java.lang.String) */ @Override public void addHeader(String name, String value) { } /** * @see javax.servlet.http.HttpServletResponse#setIntHeader(java.lang.String, int) */ @Override public void setIntHeader(String name, int value) { setHeader(name, String.valueOf(value)); } /** * @see javax.servlet.http.HttpServletResponse#addIntHeader(java.lang.String, int) */ @Override public void addIntHeader(String name, int value) { } /** * @see javax.servlet.http.HttpServletResponse#setStatus(int, java.lang.String) */ @Override public void setStatus(int sc, String sm) { } /** * @see org.jboss.resteasy.mock.MockHttpResponse#getOutputStream() */ @Override public ServletOutputStream getOutputStream() throws IOException { return new MockServletOutputStream((ByteArrayOutputStream) super.getOutputStream()); } /** * */ public String getOutputHeadersAsString() { StringBuilder builder = new StringBuilder(); MultivaluedMap<String,Object> headers = getOutputHeaders(); Set<String> headerNames = new TreeSet<String>(headers.keySet()); for (String headerName : headerNames) { builder.append(headerName); builder.append(": "); //$NON-NLS-1$ boolean first = true; for (Object headerValue : headers.get(headerName)) { String val = headerValue.toString(); if (first) { builder.append(val); first = false; } else { builder.append(", ").append(val); //$NON-NLS-1$ } } builder.append("\r\n"); //$NON-NLS-1$ } return builder.toString(); } /** */ public String getOutputAsString() { try { return this.baos.toString("UTF-8"); //$NON-NLS-1$ } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } @Override public String getHeader(String name) { return null; } @Override public Collection<String> getHeaders(String name) { return null; } @Override public Collection<String> getHeaderNames() { return null; } }
apache-2.0
tgbyte/usertype
usertype.core/src/main/java/org/jadira/usertype/dateandtime/joda/util/Formatter.java
1211
package org.jadira.usertype.dateandtime.joda.util; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; public class Formatter { private Formatter() { } public static final DateTimeFormatter LOCAL_TIME_FORMATTER = new DateTimeFormatterBuilder().appendHourOfDay(2).appendLiteral(':').appendMinuteOfHour(2).appendLiteral(':').appendSecondOfMinute(2) .appendOptional(new DateTimeFormatterBuilder().appendLiteral('.').appendFractionOfSecond(3, 9).toParser()).toFormatter(); public static final DateTimeFormatter LOCAL_TIME_NOSECONDS_FORMATTER = new DateTimeFormatterBuilder().appendHourOfDay(2).appendLiteral(':').appendMinuteOfHour(2).toFormatter(); public static final DateTimeFormatter LOCAL_DATETIME_PRINTER = new DateTimeFormatterBuilder().appendPattern("0001-01-01 HH:mm:ss'.'").appendFractionOfSecond(0, 9).toFormatter(); public static final DateTimeFormatter LOCAL_DATETIME_PARSER = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd HH:mm:ss'.'").appendFractionOfSecond(0, 9).toFormatter(); public static final DateTimeFormatter LOCAL_DATETIME_FORMATTER = LOCAL_DATETIME_PARSER; }
apache-2.0
vimaier/conqat
org.conqat.engine.code_clones/src/org/conqat/engine/code_clones/normalization/repetition/RepetitiveRegionMarkerBase.java
3703
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 The ConQAT 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 org.conqat.engine.code_clones.normalization.repetition; import org.conqat.engine.commons.ConQATParamDoc; import org.conqat.engine.core.core.AConQATAttribute; import org.conqat.engine.core.core.AConQATParameter; import org.conqat.engine.core.core.ConQATException; import org.conqat.engine.resource.regions.RegionMarkerBase; import org.conqat.engine.sourcecode.resource.ITokenElement; import org.conqat.engine.sourcecode.resource.ITokenResource; /** * Base class for processors that mark repetitive regions. * * @author $Author: hummelb $ * @version $Rev: 37519 $ * @ConQAT.Rating GREEN Hash: 2D66522251FBB2A3906D894184ACC5E4 */ public abstract class RepetitiveRegionMarkerBase extends RegionMarkerBase<ITokenResource, ITokenElement, RepetitiveRegionMarkerStrategyBase> { /** Common documentation */ protected static final String DOC = "Works only for languages for which a " + "TokenOracleFactory is available. Just as holds for other region " + "markers, region information can then be used to steer normalization. Regions " + "of repetitive code can e.g. be normalized more conservatively."; /** Repetition detection parameters */ protected RepetitionParameters repetitionParameters = null; /** ConQAT Parameter */ @AConQATParameter(name = "min", description = "Minimal size of repetition", minOccurrences = 1, maxOccurrences = 1) public void setMinLength( @AConQATAttribute(name = ConQATParamDoc.REPETITION_MIN_LENGTH_NAME, description = ConQATParamDoc.REPETITION_MIN_LENGTH_DESC) int minLength, @AConQATAttribute(name = ConQATParamDoc.REPETITION_MIN_INSTANCES_NAME, description = ConQATParamDoc.REPETITION_MIN_INSTANCES_DESC) int minMotifInstances, @AConQATAttribute(name = ConQATParamDoc.REPETITION_MIN_MOTIF_LENGTH_NAME, description = ConQATParamDoc.REPETITION_MIN_MOTIF_LENGTH_DESC) int minMotifLength, @AConQATAttribute(name = ConQATParamDoc.REPETITION_MAX_MOTIF_LENGTH_NAME, description = ConQATParamDoc.REPETITION_MAX_MOTIF_LENGTH_DESC) int maxMotifLength) throws ConQATException { repetitionParameters = new RepetitionParameters(minLength, minMotifLength, maxMotifLength, minMotifInstances); } /** {@inheritDoc} */ @Override protected void setStrategyParameters( RepetitiveRegionMarkerStrategyBase strategy) { strategy.setRepetitionParameters(repetitionParameters); } /** {@inheritDoc} */ @Override protected Class<ITokenElement> getElementClass() { return ITokenElement.class; } }
apache-2.0
googleapis/java-dataflow
proto-google-cloud-dataflow-v1beta3/src/main/java/com/google/dataflow/v1beta3/LaunchFlexTemplateParameterOrBuilder.java
9543
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/dataflow/v1beta3/templates.proto package com.google.dataflow.v1beta3; public interface LaunchFlexTemplateParameterOrBuilder extends // @@protoc_insertion_point(interface_extends:google.dataflow.v1beta3.LaunchFlexTemplateParameter) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. The job name to use for the created job. For update job request, * job name should be same as the existing running job. * </pre> * * <code>string job_name = 1;</code> * * @return The jobName. */ java.lang.String getJobName(); /** * * * <pre> * Required. The job name to use for the created job. For update job request, * job name should be same as the existing running job. * </pre> * * <code>string job_name = 1;</code> * * @return The bytes for jobName. */ com.google.protobuf.ByteString getJobNameBytes(); /** * * * <pre> * Spec about the container image to launch. * </pre> * * <code>.google.dataflow.v1beta3.ContainerSpec container_spec = 4;</code> * * @return Whether the containerSpec field is set. */ boolean hasContainerSpec(); /** * * * <pre> * Spec about the container image to launch. * </pre> * * <code>.google.dataflow.v1beta3.ContainerSpec container_spec = 4;</code> * * @return The containerSpec. */ com.google.dataflow.v1beta3.ContainerSpec getContainerSpec(); /** * * * <pre> * Spec about the container image to launch. * </pre> * * <code>.google.dataflow.v1beta3.ContainerSpec container_spec = 4;</code> */ com.google.dataflow.v1beta3.ContainerSpecOrBuilder getContainerSpecOrBuilder(); /** * * * <pre> * Cloud Storage path to a file with json serialized ContainerSpec as * content. * </pre> * * <code>string container_spec_gcs_path = 5;</code> * * @return Whether the containerSpecGcsPath field is set. */ boolean hasContainerSpecGcsPath(); /** * * * <pre> * Cloud Storage path to a file with json serialized ContainerSpec as * content. * </pre> * * <code>string container_spec_gcs_path = 5;</code> * * @return The containerSpecGcsPath. */ java.lang.String getContainerSpecGcsPath(); /** * * * <pre> * Cloud Storage path to a file with json serialized ContainerSpec as * content. * </pre> * * <code>string container_spec_gcs_path = 5;</code> * * @return The bytes for containerSpecGcsPath. */ com.google.protobuf.ByteString getContainerSpecGcsPathBytes(); /** * * * <pre> * The parameters for FlexTemplate. * Ex. {"num_workers":"5"} * </pre> * * <code>map&lt;string, string&gt; parameters = 2;</code> */ int getParametersCount(); /** * * * <pre> * The parameters for FlexTemplate. * Ex. {"num_workers":"5"} * </pre> * * <code>map&lt;string, string&gt; parameters = 2;</code> */ boolean containsParameters(java.lang.String key); /** Use {@link #getParametersMap()} instead. */ @java.lang.Deprecated java.util.Map<java.lang.String, java.lang.String> getParameters(); /** * * * <pre> * The parameters for FlexTemplate. * Ex. {"num_workers":"5"} * </pre> * * <code>map&lt;string, string&gt; parameters = 2;</code> */ java.util.Map<java.lang.String, java.lang.String> getParametersMap(); /** * * * <pre> * The parameters for FlexTemplate. * Ex. {"num_workers":"5"} * </pre> * * <code>map&lt;string, string&gt; parameters = 2;</code> */ java.lang.String getParametersOrDefault(java.lang.String key, java.lang.String defaultValue); /** * * * <pre> * The parameters for FlexTemplate. * Ex. {"num_workers":"5"} * </pre> * * <code>map&lt;string, string&gt; parameters = 2;</code> */ java.lang.String getParametersOrThrow(java.lang.String key); /** * * * <pre> * Launch options for this flex template job. This is a common set of options * across languages and templates. This should not be used to pass job * parameters. * </pre> * * <code>map&lt;string, string&gt; launch_options = 6;</code> */ int getLaunchOptionsCount(); /** * * * <pre> * Launch options for this flex template job. This is a common set of options * across languages and templates. This should not be used to pass job * parameters. * </pre> * * <code>map&lt;string, string&gt; launch_options = 6;</code> */ boolean containsLaunchOptions(java.lang.String key); /** Use {@link #getLaunchOptionsMap()} instead. */ @java.lang.Deprecated java.util.Map<java.lang.String, java.lang.String> getLaunchOptions(); /** * * * <pre> * Launch options for this flex template job. This is a common set of options * across languages and templates. This should not be used to pass job * parameters. * </pre> * * <code>map&lt;string, string&gt; launch_options = 6;</code> */ java.util.Map<java.lang.String, java.lang.String> getLaunchOptionsMap(); /** * * * <pre> * Launch options for this flex template job. This is a common set of options * across languages and templates. This should not be used to pass job * parameters. * </pre> * * <code>map&lt;string, string&gt; launch_options = 6;</code> */ java.lang.String getLaunchOptionsOrDefault(java.lang.String key, java.lang.String defaultValue); /** * * * <pre> * Launch options for this flex template job. This is a common set of options * across languages and templates. This should not be used to pass job * parameters. * </pre> * * <code>map&lt;string, string&gt; launch_options = 6;</code> */ java.lang.String getLaunchOptionsOrThrow(java.lang.String key); /** * * * <pre> * The runtime environment for the FlexTemplate job * </pre> * * <code>.google.dataflow.v1beta3.FlexTemplateRuntimeEnvironment environment = 7;</code> * * @return Whether the environment field is set. */ boolean hasEnvironment(); /** * * * <pre> * The runtime environment for the FlexTemplate job * </pre> * * <code>.google.dataflow.v1beta3.FlexTemplateRuntimeEnvironment environment = 7;</code> * * @return The environment. */ com.google.dataflow.v1beta3.FlexTemplateRuntimeEnvironment getEnvironment(); /** * * * <pre> * The runtime environment for the FlexTemplate job * </pre> * * <code>.google.dataflow.v1beta3.FlexTemplateRuntimeEnvironment environment = 7;</code> */ com.google.dataflow.v1beta3.FlexTemplateRuntimeEnvironmentOrBuilder getEnvironmentOrBuilder(); /** * * * <pre> * Set this to true if you are sending a request to update a running * streaming job. When set, the job name should be the same as the * running job. * </pre> * * <code>bool update = 8;</code> * * @return The update. */ boolean getUpdate(); /** * * * <pre> * Use this to pass transform_name_mappings for streaming update jobs. * Ex:{"oldTransformName":"newTransformName",...}' * </pre> * * <code>map&lt;string, string&gt; transform_name_mappings = 9;</code> */ int getTransformNameMappingsCount(); /** * * * <pre> * Use this to pass transform_name_mappings for streaming update jobs. * Ex:{"oldTransformName":"newTransformName",...}' * </pre> * * <code>map&lt;string, string&gt; transform_name_mappings = 9;</code> */ boolean containsTransformNameMappings(java.lang.String key); /** Use {@link #getTransformNameMappingsMap()} instead. */ @java.lang.Deprecated java.util.Map<java.lang.String, java.lang.String> getTransformNameMappings(); /** * * * <pre> * Use this to pass transform_name_mappings for streaming update jobs. * Ex:{"oldTransformName":"newTransformName",...}' * </pre> * * <code>map&lt;string, string&gt; transform_name_mappings = 9;</code> */ java.util.Map<java.lang.String, java.lang.String> getTransformNameMappingsMap(); /** * * * <pre> * Use this to pass transform_name_mappings for streaming update jobs. * Ex:{"oldTransformName":"newTransformName",...}' * </pre> * * <code>map&lt;string, string&gt; transform_name_mappings = 9;</code> */ java.lang.String getTransformNameMappingsOrDefault( java.lang.String key, java.lang.String defaultValue); /** * * * <pre> * Use this to pass transform_name_mappings for streaming update jobs. * Ex:{"oldTransformName":"newTransformName",...}' * </pre> * * <code>map&lt;string, string&gt; transform_name_mappings = 9;</code> */ java.lang.String getTransformNameMappingsOrThrow(java.lang.String key); public com.google.dataflow.v1beta3.LaunchFlexTemplateParameter.TemplateCase getTemplateCase(); }
apache-2.0
noties/Markwon
markwon-editor/src/main/java/io/noties/markwon/editor/EditHandler.java
1305
package io.noties.markwon.editor; import android.text.Editable; import androidx.annotation.NonNull; import io.noties.markwon.Markwon; import io.noties.markwon.editor.handler.EmphasisEditHandler; import io.noties.markwon.editor.handler.StrongEmphasisEditHandler; /** * @see EmphasisEditHandler * @see StrongEmphasisEditHandler * @since 4.2.0 */ public interface EditHandler<T> { void init(@NonNull Markwon markwon); void configurePersistedSpans(@NonNull PersistedSpans.Builder builder); // span is present only in off-screen rendered markdown, it must be processed and // a NEW one must be added to editable (via edit-persist-spans) // // NB, editable.setSpan must obtain span from `spans` and must be configured beforehand // multiple spans are OK as long as they are configured /** * @param persistedSpans * @param editable * @param input * @param span * @param spanStart * @param spanTextLength * @see MarkwonEditorUtils */ void handleMarkdownSpan( @NonNull PersistedSpans persistedSpans, @NonNull Editable editable, @NonNull String input, @NonNull T span, int spanStart, int spanTextLength); @NonNull Class<T> markdownSpanType(); }
apache-2.0
ceylon/ceylon
compiler-java/test/src/org/eclipse/ceylon/compiler/java/test/interop/InteropTests.java
40169
/* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.eclipse.ceylon.compiler.java.test.interop; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.io.File; import java.io.IOException; import java.lang.ProcessBuilder.Redirect; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.eclipse.ceylon.common.ModuleSpec; import org.eclipse.ceylon.common.Versions; import org.eclipse.ceylon.common.config.Repositories; import org.eclipse.ceylon.compiler.java.test.CompilerError; import org.eclipse.ceylon.compiler.java.test.CompilerTests; import org.eclipse.ceylon.compiler.java.test.ErrorCollector; import org.eclipse.ceylon.model.cmr.JDKUtils; import org.eclipse.ceylon.model.cmr.JDKUtils.JDK; import org.junit.Assume; import org.junit.Ignore; import org.junit.Test; public class InteropTests extends CompilerTests { @Override protected ModuleWithArtifact getDestModuleWithArtifact(String main) { return new ModuleWithArtifact("org.eclipse.ceylon.compiler.java.test.interop", "1"); } @Test public void testIopArrays(){ compile("TypesJava.java"); compareWithJavaSource("Arrays"); } @Test public void testIopArraysNoOpt(){ compile("TypesJava.java"); compareWithJavaSourceNoOpt("Arrays"); } @Test public void testIopConstructors(){ compareWithJavaSource("Constructors"); } @Test public void testIopImport(){ compareWithJavaSource("Import"); } @Test public void testIopMethods(){ compile("TypesJava.java", "JavaWithOverloadedMembers.java", "JavaWithOverloadedMembersSubClass.java"); compareWithJavaSource("Methods"); } @Test public void testIopAmbiguousOverloading(){ compile("TypesJava.java", "JavaWithOverloadedMembers.java"); assertErrors("AmbiguousOverloading", new CompilerError(25, "illegal argument types in invocation of overloaded method or class: there must be exactly one overloaded declaration of 'ambiguousOverload' which accepts the given argument types 'String, String'"), new CompilerError(26, "illegal argument types in invocation of overloaded method or class: there must be exactly one overloaded declaration of 'ambiguousOverload2' which accepts the given argument types 'Integer, Integer'") ); } @Test public void testIopVariadicOverloadedMethods(){ compile("JavaWithOverloadedMembers.java"); compareWithJavaSource("VariadicOverloadedMethods"); } @Test public void testIopVariadicArrays(){ compile("TypesJava.java"); compareWithJavaSource("VariadicArraysMethods"); } @Test public void testIopVariadicImplementations(){ compile("TypesJava.java"); compareWithJavaSource("VariadicImplementations"); } @Test public void testIopImplementOverloadedConstructors(){ compile("JavaWithOverloadedMembers.java"); compareWithJavaSource("ImplementOverloadedConstructors"); } @Test public void testIopImplementOverloadedMethods(){ compile("JavaWithOverloadedMembers.java", "JavaWithOverloadedMembersSubClass.java"); compareWithJavaSource("ImplementOverloadedMethods"); } @Test public void testIopImplementSingleOverloadedMethods(){ compile("JavaWithOverloadedMembers.java"); compareWithJavaSource("ImplementSingleOverloadedMethods"); } @Test public void testIopDeclareOverloadedMethods(){ assertErrors("DeclareOverloadedMethodsErrors", new CompilerError(22, "duplicate declaration: the name 'method' is not unique in this scope (overloaded function must be declared with the 'overloaded' annotation in 'java.lang')"), new CompilerError(23, "duplicate declaration: the name 'method' is not unique in this scope (overloaded function must be declared with the 'overloaded' annotation in 'java.lang')")); compareWithJavaSource("DeclareOverloadedMethods"); } @Test public void testIopFields(){ compile("JavaFields.java"); compareWithJavaSource("Fields"); } @Test public void testIopSpecialFields(){ compile("JavaFields.java"); compareWithJavaSource("SpecialFields"); } @Test public void testIopGetString(){ compile("JavaGetString.java"); compareWithJavaSource("GetString"); } @Test public void testIopOverloadedSpecialFields(){ compile("JavaOverloadedSpecialFields.java"); compareWithJavaSource("OverloadedSpecialFields"); } @Test public void testIopAttributes(){ compile("JavaBean.java"); compareWithJavaSource("Attributes"); } @Test public void testIopSatisfies(){ compile("JavaInterface.java"); compareWithJavaSource("Satisfies"); } @Test public void testIopOptionality(){ compile("JavaOptionalInterface.java"); compareWithJavaSource("Optionality"); } @Test public void testIopStaticMembers(){ compile("JavaWithStaticMembers.java", "JavaWithStaticMembersSubClass.java"); compareWithJavaSource("StaticMembers"); } @Test public void testIopStaticRefs(){ compile("JavaWithStaticMembers.java", "JavaWithStaticMembersSubClass.java"); compareWithJavaSource("StaticRefs"); } @Test public void testIopTypes(){ compile("TypesJava.java"); compareWithJavaSource("Types"); } @Test public void testIopEnums(){ compile("JavaEnum.java"); compareWithJavaSource("Enums"); } @Test public void testIopEnumSwitch(){ compile("JavaEnum.java"); compareWithJavaSource("EnumSwitch"); } @Test public void testIopNesting(){ compile("JavaNesting.java"); compareWithJavaSource("Nesting"); } @Test public void testIopVariance(){ compile("JavaVariance.java"); compareWithJavaSource("Variance"); } // depends on #612 @Ignore("M6: depends on https://github.com/ceylon/ceylon-compiler/issues/612") @Test public void testIopVariance2_fail(){ compile("JavaVariance.java"); compareWithJavaSource("Variance2"); } @Test public void testIopCaseMismatch(){ compile("javaCaseMismatch.java"); compareWithJavaSource("CaseMismatch"); } @Test public void testIopCaseMismatch2(){ compile("javaCaseMismatch.java"); compareWithJavaSource("CaseMismatch2"); } @Test public void testIopCeylonKeywords(){ compile("satisfies.java"); compareWithJavaSource("CeylonKeywords"); } @Test public void testIopCheckedExceptions(){ compile("JavaCheckedExceptions.java"); compareWithJavaSource("CheckedExceptions"); } @Test public void testIopExceptionsAndThrowable(){ compile("JavaExceptionsAndThrowable.java"); compareWithJavaSource("ExceptionsAndThrowable"); } @Test public void testIopJavaExceptionMessage(){ compile("JavaExceptionMessage.java"); compareWithJavaSource("JavaExceptionMessage"); } @Test public void testIopJavaExceptionMessage2(){ compileAndRun("org.eclipse.ceylon.compiler.java.test.interop.javaExceptionMessage2", "JavaExceptionsAndThrowable.java", "JavaExceptionMessage2.ceylon"); } @Test public void testIopJavaExceptionArrays(){ compileAndRun("org.eclipse.ceylon.compiler.java.test.interop.javaExceptionArrays", "JavaExceptionArrays.ceylon", "JavaExceptionsAndThrowable.java"); } @Test public void testIopRefinesProtectedAccessMethod(){ compile("access/JavaAccessModifiers.java"); compareWithJavaSource("access/RefinesProtectedAccessMethod"); } @Test public void testMixedCompilationIndependent(){ compile("mixed/independent/Java.java", "mixed/independent/Ceylon.ceylon"); } @Test public void testMixedCompilationCeylonNeedsJava(){ compile("mixed/ceylon_needs_java/Java.java", "mixed/ceylon_needs_java/Ceylon.ceylon"); } @Ignore("M5: #470") @Test public void testMixedCompilationJavaNeedsCeylon(){ compile("mixed/java_needs_ceylon/Java.java", "mixed/java_needs_ceylon/Ceylon.ceylon"); } @Ignore("M5: #470") @Test public void testMixedCompilationInterdependent(){ compile("mixed/interdependent/Java.java", "mixed/interdependent/Ceylon.ceylon"); } @Test public void testUsesJDKTypes(){ compile("JDKTypes.ceylon"); } @Test public void testIopCallsProtectedAccessMethod(){ compile("access/JavaAccessModifiers.java"); compareWithJavaSource("access/CallsProtectedAccessMethod"); } @Test public void testIopRefinesAndCallsProtectedAccessMethod(){ compile("access/JavaAccessModifiers.java"); compareWithJavaSource("access/RefinesAndCallsProtectedAccessMethod"); } @Test public void testIopRefinesDefaultAccessMethod(){ compile("access/JavaAccessModifiers.java"); compile("access/RefinesDefaultAccessMethod.ceylon"); } @Test public void testIopRefinesDefaultAccessMethodWithShared(){ compile("access/JavaAccessModifiers.java"); assertErrors("access/RefinesDefaultAccessMethodWithShared", new CompilerError(22, "non-actual member collides with an inherited member: 'defaultAccessMethod' in 'RefinesDefaultAccessMethodWithShared' refines 'defaultAccessMethod' in 'JavaAccessModifiers' but is not annotated 'actual'")); } @Test public void testIopRefinesDefaultAccessMethodWithActual(){ compile("access/JavaAccessModifiers.java"); assertErrors("access/RefinesDefaultAccessMethodWithActual", new CompilerError(22, "actual declaration must be shared: 'defaultAccessMethod'")); } @Test public void testIopRefinesDefaultAccessMethodWithSharedActual(){ compile("access/JavaAccessModifiers.java"); compareWithJavaSource("access/RefinesDefaultAccessMethodWithSharedActual"); } @Test public void testIopCallsDefaultAccessMethod(){ compile("access/JavaAccessModifiers.java"); compareWithJavaSource("access/CallsDefaultAccessMethod"); } @Test public void testIopExtendsDefaultAccessClass(){ compile("access/JavaAccessModifiers.java"); compile("access/JavaDefaultAccessClass3.java"); compareWithJavaSource("access/ExtendsDefaultAccessClass"); } @Test public void testIopExtendsDefaultAccessClassWithOverloading(){ compile("access/JavaDefaultAccessClass4.java"); assertErrors("access/ExtendsDefaultAccessClassWithOverloading", new CompilerError(21, "illegal argument types in invocation of overloaded method or class: there must be exactly one overloaded declaration of 'JavaDefaultAccessClass4' which accepts the given argument types ''") ); } @Test public void testIopExtendsDefaultAccessClassInAnotherPkg(){ compile("access/JavaAccessModifiers.java"); compile("access/JavaDefaultAccessClass3.java"); assertErrors("ExtendsDefaultAccessClassInAnotherPkg", new CompilerError(21, "imported declaration is not visible: 'JavaDefaultAccessClass' is not shared"), new CompilerError(22, "imported declaration is not visible: 'JavaDefaultAccessClass2' is not shared"), new CompilerError(27, "type is not visible: 'JavaDefaultAccessClass'"), new CompilerError(29, "type is not visible: 'JavaDefaultAccessClass2'"), new CompilerError(31, "constructor is not visible: 'JavaDefaultAccessClass3' is package private") ); } @Test public void testIopCallsDefaultAccessClass(){ compile("access/JavaAccessModifiers.java"); compile("access/JavaDefaultAccessClass3.java"); compareWithJavaSource("access/CallsDefaultAccessClass"); } @Test public void testIopCallsDefaultAccessClassWithOverloading(){ compile("access/JavaDefaultAccessClass4.java"); assertErrors("access/CallsDefaultAccessClassWithOverloading", new CompilerError(22, "illegal argument types in invocation of overloaded method or class: there must be exactly one overloaded declaration of 'JavaDefaultAccessClass4' which accepts the given argument types ''") ); } @Test public void testIopCallsDefaultAccessClassInAnotherPkg(){ compile("access/JavaAccessModifiers.java"); compile("access/JavaDefaultAccessClass3.java"); assertErrors("CallsDefaultAccessClassInAnotherPkg", new CompilerError(21, "imported declaration is not visible: 'JavaDefaultAccessClass' is not shared"), new CompilerError(22, "imported declaration is not visible: 'JavaDefaultAccessClass2' is not shared"), new CompilerError(28, "type is not visible: 'JavaDefaultAccessClass'"), new CompilerError(29, "type is not visible: 'JavaDefaultAccessClass2'"), new CompilerError(30, "type constructor is not visible: 'JavaDefaultAccessClass3'") ); } @Test public void testIopCallsDefaultAccessClassInAnotherPkgWithOverloading(){ compile("access/JavaDefaultAccessClass4.java"); assertErrors("CallsDefaultAccessClassInAnotherPkgWithOverloading", new CompilerError(26, "illegal argument types in invocation of overloaded method or class: there must be exactly one overloaded declaration of 'JavaDefaultAccessClass4' which accepts the given argument types ''"), new CompilerError(27, "type constructor is not visible: 'JavaDefaultAccessClass4'"), new CompilerError(28, "constructor is not visible: 'JavaDefaultAccessClass4' is protected") ); } @Test public void testIopCallsDefaultAccessMethodInAnotherPkg(){ compile("access/JavaAccessModifiers.java"); assertErrors("CallsDefaultAccessMethodInAnotherPkg", new CompilerError(25, "method or attribute is not visible: 'protectedAccessMethod' of type 'JavaAccessModifiers' is protected"), new CompilerError(27, "method or attribute is not visible: 'defaultAccessMethod' of type 'JavaAccessModifiers' is package private"), new CompilerError(36, "function or value is not visible: 'defaultAccessMethod' is package private")); } @Test public void testIopRefinesDefaultAccessMethodInAnotherPkg(){ compile("access/JavaAccessModifiers.java"); assertErrors("RefinesDefaultAccessMethodInAnotherPkg", new CompilerError(27, "refined declaration is not visible: 'defaultAccessMethod' in 'RefinesDefaultAccessMethodInAnotherPkg' refines 'defaultAccessMethod' in 'JavaAccessModifiers' which is package private")); } @Test public void testIopNamedInvocations(){ assertErrors("NamedInvocations", new CompilerError(30, "overloaded declarations may not be called using named arguments: 'createTempFile'"), new CompilerError(30, "ambiguous callable reference to overloaded method or class: 'createTempFile' is overloaded"), new CompilerError(30, "named invocations of Java methods not supported"), new CompilerError(32, "named invocations of Java methods not supported"), new CompilerError(35, "named invocations of Java methods not supported"), new CompilerError(35, "overloaded declarations may not be called using named arguments: 'createTempFile'"), new CompilerError(35, "ambiguous callable reference to overloaded method or class: 'createTempFile' is overloaded"), new CompilerError(37, "named invocations of Java methods not supported") ); } @Test public void testIopOverrideStaticMethods(){ compile("JavaWithStaticMembers.java"); assertErrors("OverrideStaticMethods", new CompilerError(26, "member refines a non-default, non-formal member: 'topMethod' in 'StaticMethodsOverriding' refines 'topMethod' in 'JavaWithStaticMembers' which is not annotated 'formal' or 'default'"), new CompilerError(28, "member refines a non-default, non-formal member: 'topField' in 'StaticMethodsOverriding' refines 'topField' in 'JavaWithStaticMembers' which is not annotated 'formal' or 'default'") ); } @Test public void testJavaxInject(){ compareWithJavaSource("JavaxInject"); } @Test public void testJavaxValidation(){ compareWithJavaSource("JavaxValidation"); } @Test public void testAnnotationInterop(){ Assume.assumeTrue(allowSdkTests()); compile("sdk/JavaAnnotation.java"); compareWithJavaSource("sdk/AnnotationInterop"); assertErrors("sdk/AnnotationInteropErrors", new CompilerError(2, "function or value is not defined: 'javaAnnotationNoTarget__TYPE' might be misspelled or is not imported (did you mean 'javaAnnotationTypeTarget__TYPE'?)"), new CompilerError(3, "function or value is not defined: 'javaAnnotationNoTarget__CONSTRUCTOR' might be misspelled or is not imported (did you mean 'javaAnnotationCtorTarget__CONSTRUCTOR'?)"), new CompilerError(6, "function or value is not defined: 'javaAnnotationNoTarget__FIELD' might be misspelled or is not imported (did you mean 'javaAnnotationFieldTarget__FIELD'?)"), new CompilerError(7, "function or value is not defined: 'javaAnnotationNoTarget__GETTER' might be misspelled or is not imported (did you mean 'javaAnnotationMethodTarget__GETTER'?)"), new CompilerError(8, "function or value is not defined: 'javaAnnotationNoTarget__SETTER' might be misspelled or is not imported (did you mean 'javaAnnotationMethodTarget__SETTER'?)"), new CompilerError(12, "function or value is not defined: 'javaAnnotationNoTarget__PARAMETER' might be misspelled or is not imported (did you mean 'javaAnnotationDefaultTarget__PARAMETER'?)"), new CompilerError(14, "function or value is not defined: 'javaAnnotationNoTarget__LOCAL_VARIABLE' might be misspelled or is not imported (did you mean 'javaAnnotationDefaultTarget__LOCAL_VARIABLE'?)"), new CompilerError(19, "function or value is not defined: 'javaAnnotationNoTarget__ANNOTATION_TYPE' might be misspelled or is not imported (did you mean 'javaAnnotationDefaultTarget__ANNOTATION_TYPE'?)"), new CompilerError(21, "illegal annotation argument: must be a literal value, metamodel reference, annotation instantiation, or parameter reference"), new CompilerError(21, "named argument must be assignable to parameter 'clas' of 'javaAnnotationClass2': 'Class<String>' is not assignable to 'ClassOrInterfaceDeclaration'") ); } @Test public void testAnnotationSequencedArgs(){ Assume.assumeTrue(allowSdkTests()); compile("sdk/JavaAnnotation.java"); compareWithJavaSource("sdk/AnnotationSequencedArgs"); } @Test public void testBannedAnnotation(){ assertErrors("BannedAnnotation", new CompilerError(13, "illegal Java annotation"), new CompilerError(14, "illegal Java annotation"), new CompilerError(16, "illegal Java annotation (use 'deprecated' in 'ceylon.language')"), new CompilerError(17, "illegal Java annotation (use 'actual' in 'ceylon.language')")); } @Test public void testAnnotationsConstrainedClassCtor() { Assume.assumeTrue(allowSdkTests()); compile("sdk/JavaAnnotation.java"); compareWithJavaSource("sdk/AnnotationsConstrainedClassCtor"); } @Ignore("Can't make it work on jdk8 and jdk9") @Test public void testAnnotationInteropQualifiedEnum(){ Assume.assumeFalse("Runs on <JDK9", JDKUtils.jdk.providesVersion(JDKUtils.JDK.JDK9.version)); compareWithJavaSource("AnnotationInteropQualifiedEnum"); } @Test public void testAnnotationBug6145() { compareWithJavaSource("AnnotationBug6145"); } @Test public void testRepeatableAnnotation() { Assume.assumeTrue("Runs on JDK8", JDKUtils.jdk == JDKUtils.JDK.JDK8 || JDKUtils.jdk == JDKUtils.JDK.JDK9); compile("JavaRepeatable.java"); compareWithJavaSource("RepeatableAnnotation"); } @Test public void testSealedInterop(){ compile("access/JavaSealed.java"); assertErrors("Sealed", new CompilerError(27, "constructor is not visible: 'JavaSealed' is package private"), new CompilerError(29, "class cannot be instantiated: 'Runtime' does not have a default constructor"), new CompilerError(30, "type constructor is not visible: 'JavaSealed'")); } @Test public void testIopBug1736(){ compile("JavaWithStaticMembers.java"); compareWithJavaSource("Bug1736"); } @Test public void testIopBug1806(){ compareWithJavaSource("Bug1806"); } @Test public void testIopBug1977(){ compareWithJavaSource("Bug1977"); } @Test public void testIopWidening(){ compile("Widening.ceylon"); run("org.eclipse.ceylon.compiler.java.test.interop.run"); } @Test public void testIopBug2019(){ compile("access/JavaBug2019.java"); compile("Bug2019.ceylon"); } @Test public void testIopBug2027(){ compile("Bug2027.ceylon"); } @Test public void testIopBug2042(){ compareWithJavaSource("Bug2042"); } @Test public void testIopBug2053(){ compile("Bug2053Varargs.java"); compareWithJavaSource("Bug2053"); } @Test public void testIopBug2199(){ compareWithJavaSource("Bug2199"); } @Test public void testIopBug2271(){ compareWithJavaSource("Bug2271"); } @Test public void testIopBug2310(){ compile("Bug2310Java.java"); compile("Bug2310.ceylon"); } @Test public void testIopBug2318(){ compile("Bug2318Java.java"); compile("Bug2318.ceylon"); } @Test public void testIopBug2327(){ compile("Bug2327Java.java"); compile("Bug2327.ceylon"); } @Test public void testIopJpaCtor(){ compile("JpaCtorWithoutNullary.java"); compile("JpaCtorWithNullary.java"); compile("JpaCtor.ceylon"); } @Test public void testIopBug2331(){ compile("Bug2331Java.java"); compile("Bug2331.ceylon"); } @Test public void testIopJavaSerialization() throws Throwable{ Assume.assumeTrue(allowSdkTests()); compile("sdk/JavaSerialization.ceylon", "sdk/javaSerializationRoundTrip_.java"); runInJBossModules("run", "org.eclipse.ceylon.compiler.java.test.interop.sdk", Arrays.asList(//"org.eclipse.ceylon.compiler.java.test.interop", "--run", "org.eclipse.ceylon.compiler.java.test.interop.sdk::javaSerializationRoundTrip")); } @Test public void testIopJavaSerializationEeMode() throws Throwable{ // Same as above with with --ee Assume.assumeTrue(allowSdkTests()); List<String> opts = new ArrayList<>(defaultOptions); opts.add("-ee"); compile(opts, "sdk/JavaSerialization.ceylon", "sdk/javaSerializationRoundTrip_.java"); runInJBossModules("run", "org.eclipse.ceylon.compiler.java.test.interop.sdk", Arrays.asList(//"org.eclipse.ceylon.compiler.java.test.interop", "--run", "org.eclipse.ceylon.compiler.java.test.interop.sdk::javaSerializationRoundTrip")); } @Test public void testIopSerializableAssignable() throws Throwable{ compile("SerializableAssignable.ceylon"); } @Test public void testIopBug2397() throws Throwable{ compareWithJavaSource("Bug2397"); } /** * Warning: this test requires a build with "ant -Djigsaw=true clean dist" and to run on Java 9+Jigsaw */ @Test public void testJava9Module() throws Throwable{ Assume.assumeTrue("Runs on JDK9", JDKUtils.jdk == JDKUtils.JDK.JDK9); assertErrors(new String[]{"java9/user/runError.ceylon", "java9/user/package.ceylon"}, Arrays.asList("-out", destDir, "-rep", "test/java9/modules"), null, new CompilerError(1, "imported package is not visible: package 'com.ceylon.java9.internal' is not shared by module 'com.ceylon.java9'")); ErrorCollector c = new ErrorCollector(); assertCompilesOk(c, getCompilerTask(Arrays.asList("-out", destDir, "-rep", "test/java9/modules"), c, "java9/user/run.ceylon", "java9/user/package.ceylon").call2()); // check that we do not have a module-info.class File archive = getModuleArchive("org.eclipse.ceylon.compiler.java.test.interop.java9.user", "1"); try(ZipFile zf = new ZipFile(archive)){ ZipEntry entry = zf.getEntry("module-info.class"); assertNull(entry); } c = new ErrorCollector(); assertCompilesOk(c, getCompilerTask(Arrays.asList("-out", destDir, "-rep", "test/java9/modules", "-module-info"), c, "java9/user/run.ceylon", "java9/user/package.ceylon").call2()); // check that we do have a module-info.class try(ZipFile zf = new ZipFile(archive)){ ZipEntry entry = zf.getEntry("module-info.class"); assertNotNull(entry); } run("org.eclipse.ceylon.compiler.java.test.interop.java9.user.run", new ModuleWithArtifact("org.eclipse.ceylon.compiler.java.test.interop.java9.user", "1"), new ModuleWithArtifact("com.ceylon.java9", "123", "test/java9/modules", "jar")); // FIXME: this only works with a distrib build with module descriptors // assertEquals(0, runInJava9(new String[]{destDir, "test/java9/modules", "../dist/dist/repo"}, // new ModuleSpec(null, "org.eclipse.ceylon.compiler.java.test.interop.java9.user", "1"), // Collections.<String>emptyList())); } @Test public void testIopJavaIterableInFor(){ compareWithJavaSource("JavaIterableInFor"); } @Test public void testIopJavaArrayInFor(){ compareWithJavaSource("JavaArrayInFor"); } @Test public void testIopJavaIterableInForComprehension(){ compareWithJavaSource("JavaIterableInForComprehension"); run("org.eclipse.ceylon.compiler.java.test.interop.javaIterableInForComprehension"); } @Test public void testIopJavaArrayInForComprehension(){ Assume.assumeTrue(allowSdkTests()); compile("sdk/JavaArrayInForComprehension_util.ceylon"); compareWithJavaSource("sdk/JavaArrayInForComprehension"); run("org.eclipse.ceylon.compiler.java.test.interop.sdk.javaArrayInForComprehension", new ModuleWithArtifact("org.eclipse.ceylon.compiler.java.test.interop.sdk", "1"), new ModuleWithArtifact("ceylon.interop.java", Versions.CEYLON_VERSION_NUMBER, Repositories.get().getUserRepoDir().getAbsolutePath(), "car")); } @Test public void testIopJavaIterableInSpreadArgument(){ //compareWithJavaSource("JavaIterableInSpreadArgument"); compile("JavaIterableInSpreadArgument.ceylon"); run("org.eclipse.ceylon.compiler.java.test.interop.javaIterableInSpreadArgument"); } @Test public void testIopJavaArrayInSpreadArgument(){ //compareWithJavaSource("JavaArrayInSpreadArgument"); compile("JavaArrayInSpreadArgument.ceylon"); run("org.eclipse.ceylon.compiler.java.test.interop.javaArrayInSpreadArgument"); } @Test public void testIopJavaIterableWithSpreadOperator(){ //compareWithJavaSource("JavaIterableWithSpreadOperator"); compile("JavaIterableWithSpreadOperator.ceylon"); run("org.eclipse.ceylon.compiler.java.test.interop.javaIterableWithSpreadOperator"); } @Test public void testIopJavaArrayWithSpreadOperator(){ //compareWithJavaSource("JavaArrayWithSpreadOperator"); compile("JavaArrayWithSpreadOperator.ceylon"); run("org.eclipse.ceylon.compiler.java.test.interop.javaArrayWithSpreadOperator"); } @Test public void testIopJavaAutoCloseableInTry(){ compareWithJavaSource("JavaAutoCloseableInTry"); } @Test public void testIopJavaIterableWithoutJavaBase() throws IOException { // compile our java class File classesOutputFolder = new File(destDir+"-jar-classes"); cleanCars(classesOutputFolder.getPath()); classesOutputFolder.mkdirs(); File jarOutputFolder = new File(destDir+"-jar"); cleanCars(jarOutputFolder.getPath()); jarOutputFolder.mkdirs(); compileJavaModule(jarOutputFolder, classesOutputFolder, "org.eclipse.ceylon.compiler.java.test.interop.bug4389.a", "1", moduleName.replace('.', '/')+"/bug4389/a/A.java"); ArrayList<String> opts = new ArrayList<String>(defaultOptions); opts.add("-rep"); opts.add(jarOutputFolder.getPath()); compareWithJavaSource(opts, "bug4389/b/b.src", "bug4389/b/b.ceylon"); // } @Test public void testIopJavaListIndex(){ compareWithJavaSource("JavaListIndex"); } @Test public void testIopJavaMapIndex(){ compareWithJavaSource("JavaMapIndex"); } @Test public void testIopJavaArrayIndex(){ compareWithJavaSource("JavaArrayIndex"); } @Test public void testIopJavaCollectionWithInOp(){ compareWithJavaSource("JavaCollectionWithInOp"); } @Test public void testIopJavaArrayTypeConstraint(){ compile("JavaArrayTypeConstraint.ceylon"); } @Test public void testIopBug6143(){ compareWithJavaSource("Bug6143"); } @Test public void testIopBug6156(){ compile("Bug6156Document.java"); compile("Bug6156.ceylon"); compile("Bug6156b.ceylon"); } @Test public void testIopBug6160(){ compile("Bug6160.ceylon"); } @Test public void testIopCallDefaultInterfaceMethod(){ Assume.assumeTrue("Runs on JDK >= 8", JDKUtils.jdk == JDKUtils.JDK.JDK8 || JDKUtils.jdk == JDKUtils.JDK.JDK9); compareWithJavaSource("CallDefaultInterfaceMethod"); } @Test public void testIopSatisfyInterfaceWithDefaultMethod(){ Assume.assumeTrue("Runs on JDK >= 8", JDKUtils.jdk == JDKUtils.JDK.JDK8 || JDKUtils.jdk == JDKUtils.JDK.JDK9); compareWithJavaSource("SatisfyInterfaceWithDefaultMethod"); } @Test public void testIopRefineDefaultInterfaceMethod(){ Assume.assumeTrue("Runs on JDK8", JDKUtils.jdk == JDKUtils.JDK.JDK8 || JDKUtils.jdk == JDKUtils.JDK.JDK9); compareWithJavaSource("RefineDefaultInterfaceMethod"); } @Test public void testBug6244(){ compile("Bug6244Java.java"); compile("Bug6244.ceylon"); } @Test public void testSdkBug571() throws Throwable{ Assume.assumeTrue(allowSdkTests()); compile("sdk/SdkBug571.ceylon"); runInJBossModules("run", "org.eclipse.ceylon.compiler.java.test.interop.sdk", Arrays.asList("--run=org.eclipse.ceylon.compiler.java.test.interop.sdk::sdkBug571_run")); } @Test public void testIopBug6099(){ compile("Bug6099Java.java"); compile("Bug6099.ceylon"); } @Test public void testIopBug6123(){ compile("Bug6123Java.java"); compile("Bug6123.ceylon"); } @Test public void testIopBug6289(){ compareWithJavaSource("Bug6289"); } @Test public void testIopInterdep(){ compile("InterdepJava.java", "Interdep.ceylon"); } @Test public void testIopNullAnnotations(){ compile("nullable/NullAnnotationsJava.java", "nullable/NullAnnotations.ceylon"); } @Test public void testIopRawImplementations(){ compile("RawJava.java", "Raw.ceylon"); } @Test public void testIopLambdas(){ Assume.assumeTrue("Runs on JDK8", JDKUtils.jdk == JDKUtils.JDK.JDK8 || JDKUtils.jdk == JDKUtils.JDK.JDK9); List<String> options = Arrays.asList("-source", "8", "-target", "8"); compile(options, "LambdasJava.java"); compareWithJavaSource(options, "Lambdas.src", "Lambdas.ceylon"); compileAndRun("org.eclipse.ceylon.compiler.java.test.interop.classModelCoercionTest", "LambdasRuntime.ceylon"); assertErrors("LambdasErrors", new CompilerError(12, "refined declaration is not a real method: 'm' in 'Sub3' refines 'm' in 'InterfaceWithCoercedMembers'")); } @Test @Ignore("Missing 1.3.2") public void testSerializableLambdas() { compile("SerializableLambdas.java", "SerializableLambdas.ceylon"); run("org.eclipse.ceylon.compiler.java.test.interop.serializableLambdas"); } @Test public void testIopStaticEnumSet(){ Assume.assumeTrue(allowSdkTests()); compile("sdk/StaticEnumSet.ceylon"); } @Test public void testIopBug6574() { compareWithJavaSource("Bug6574"); run("org.eclipse.ceylon.compiler.java.test.interop.bug6574"); } @Test public void testIopBug6587() { compareWithJavaSource("Bug6587"); } @Test public void testIopBug6588() { compareWithJavaSource("Bug6588"); } @Test public void testIopBug6589() { compareWithJavaSource("Bug6589"); } @Test public void testIopAnnotateJavaPackage() throws Exception { compile("packageannotations/AnnotateJavaPackage.ceylon", "packageannotations/package.ceylon"); synchronized(RUN_LOCK){ String main = "org.eclipse.ceylon.compiler.java.test.interop.packageannotations.AnnotateJavaPackage"; try (URLClassLoader classLoader = getClassLoader(main, new ModuleWithArtifact("org.eclipse.ceylon.compiler.java.test.interop.packageannotations", "1"), new ModuleWithArtifact("javax.xml.bind:jaxb-api", "2.2.12", // we can do this because it will be resolved by the module descriptor new File(System.getProperty("user.home")+"/.m2/repository/javax/xml/bind/jaxb-api/2.2.12/jaxb-api-2.2.12.jar")))) { java.lang.Class<?> c = java.lang.Class.forName("org.eclipse.ceylon.compiler.java.test.interop.packageannotations.IntegerAdaptor", false, classLoader); java.lang.Package p = c.getPackage(); java.lang.Class ac = java.lang.Class.forName("javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters", false, classLoader); assertNotNull(p.getAnnotation(ac)); } } } @Test public void testIopAnnotatedJavaPackageRecompile() throws Exception { ArrayList<String> a = new ArrayList<String>(); a.add(script()); a.add("compile"); a.add("--verbose=code"); a.add("--rep"); a.add(getOutPath()); a.add("--src"); a.add("test/src"); a.add("org.eclipse.ceylon.compiler.java.test.interop.packageannotations"); System.err.println(a); ProcessBuilder pb = new ProcessBuilder(a); pb.redirectError(Redirect.INHERIT); pb.redirectOutput(Redirect.INHERIT); // use the same JVM as the current one pb.environment().put("JAVA_HOME", System.getProperty("java.home")); if(JDKUtils.jdk.providesVersion(JDK.JDK9.version)){ pb.environment().put("JAVA_OPTS", "--add-exports java.xml/com.sun.org.apache.xerces.internal.jaxp=ALL-UNNAMED" +" --add-exports java.xml/com.sun.org.apache.xalan.internal.xsltc.trax=ALL-UNNAMED" +" --add-exports java.xml/com.sun.xml.internal.stream=ALL-UNNAMED"); } Process p = pb.start(); assertEquals(0, p.waitFor()); // Now run it again p = pb.start(); assertEquals(0, p.waitFor()); } @Test public void testBug6632() { compareWithJavaSource("Bug6632"); } @Test public void testBug6635() { Assume.assumeTrue("Runs on JDK8", JDKUtils.jdk == JDKUtils.JDK.JDK8 || JDKUtils.jdk == JDKUtils.JDK.JDK9); compileAndRun("org.eclipse.ceylon.compiler.java.test.interop.run6635", "Bug6635.ceylon"); } @Test public void testIopTransient() { compareWithJavaSource("Transient"); } @Test public void testIopVolatile() { compareWithJavaSource("Volatile"); } @Test public void testIopSynchronized() { compareWithJavaSource("Synchronized"); } @Test public void testIopNative() { compareWithJavaSource("Native"); } @Test public void testIopStrictfp() { compareWithJavaSource("Strictfp"); } @Test public void testIopArrayWith() { compareWithJavaSource("ArrayWith"); run("org.eclipse.ceylon.compiler.java.test.interop.arrayWith"); } @Test public void testIopArrayFrom() { //compareWithJavaSource("ArrayFrom"); compile("ArrayFrom.ceylon"); run("org.eclipse.ceylon.compiler.java.test.interop.arrayFrom"); } @Test public void testIopAssertionMessageDetail() { compile("IopAssertionMessageDetail.ceylon"); run("org.eclipse.ceylon.compiler.java.test.interop.assertionMessageDetail"); } @Test public void testIopBug6854() { compile("Bug6854.java"); compareWithJavaSource("Bug6854"); } @Test public void testClassLiteral() { compile("ClassLiteral.java"); compareWithJavaSource("ClassLiteral"); //compile("ClassLiteral.ceylon"); run("org.eclipse.ceylon.compiler.java.test.interop.classLiteral_run"); } @Test public void testIopBug6899() { compile("Bug6899.ceylon"); run("org.eclipse.ceylon.compiler.java.test.interop.bug6899"); } }
apache-2.0
leafclick/intellij-community
platform/testFramework/src/com/intellij/testFramework/LexerTestCase.java
6886
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework; import com.intellij.lang.TokenWrapper; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.highlighter.HighlighterIterator; import com.intellij.openapi.util.Trinity; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.testFramework.fixtures.IdeaTestExecutionPolicy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * @author peter */ public abstract class LexerTestCase extends UsefulTestCase { protected void doTest(String text) { doTest(text, null); } protected void doTest(String text, @Nullable String expected) { doTest(text, expected, createLexer()); } protected void doTest(String text, @Nullable String expected, @NotNull Lexer lexer) { String result = printTokens(text, 0, lexer); if (expected != null) { assertSameLines(expected, result); } else { assertSameLinesWithFile(getPathToTestDataFile(getExpectedFileExtension()), result); } } @NotNull protected String getPathToTestDataFile(String extension) { return IdeaTestExecutionPolicy.getHomePathWithPolicy() + "/" + getDirPath() + "/" + getTestName(true) + extension; } @NotNull protected String getExpectedFileExtension() { return ".txt"; } protected void checkZeroState(String text, TokenSet tokenTypes) { Lexer lexer = createLexer(); lexer.start(text); while (true) { IElementType type = lexer.getTokenType(); if (type == null) { break; } if (tokenTypes.contains(type) && lexer.getState() != 0) { fail("Non-zero lexer state on token \"" + lexer.getTokenText() + "\" (" + type + ") at " + lexer.getTokenStart()); } lexer.advance(); } } protected void checkCorrectRestart(String text) { Lexer mainLexer = createLexer(); String allTokens = printTokens(text, 0, mainLexer); Lexer auxLexer = createLexer(); auxLexer.start(text); while (true) { IElementType type = auxLexer.getTokenType(); if (type == null) { break; } if (auxLexer.getState() == 0) { int tokenStart = auxLexer.getTokenStart(); String subTokens = printTokens(text, tokenStart, mainLexer); if (!allTokens.endsWith(subTokens)) { assertEquals("Restarting impossible from offset " + tokenStart + "; lexer state should not return 0 at this point", allTokens, subTokens); } } auxLexer.advance(); } } protected String printTokens(String text, int start) { return printTokens(text, start, createLexer()); } protected void checkCorrectRestartOnEveryToken(@NotNull String text) { Lexer mainLexer = createLexer(); List<Trinity<IElementType, Integer, Integer>> allTokens = tokenize(text, 0, 0, mainLexer); Lexer auxLexer = createLexer(); auxLexer.start(text); int index = 0; while (true) { IElementType type = auxLexer.getTokenType(); if (type == null) { break; } List<Trinity<IElementType, Integer, Integer>> subTokens = tokenize(text, auxLexer.getTokenStart(), auxLexer.getState(), mainLexer); if (!allTokens.subList(index++, allTokens.size()).equals(subTokens)) { assertEquals("Restarting impossible from offset " + auxLexer.getTokenStart() + " - " + auxLexer.getTokenText() + "\n" + "All tokens <type, offset, lexer state>: " + allTokens + "\n", allTokens.subList(index - 1, allTokens.size()), subTokens); } auxLexer.advance(); } } @NotNull private static List<Trinity<IElementType, Integer, Integer>> tokenize(@NotNull String text, int start, int state, @NotNull Lexer lexer) { List<Trinity<IElementType, Integer, Integer>> allTokens = new ArrayList<>(); try { lexer.start(text, start, text.length(), state); } catch (Throwable t) { LOG.error("Restarting impossible from offset " + start, t); throw new RuntimeException(t); } while (lexer.getTokenType() != null) { allTokens.add(Trinity.create(lexer.getTokenType(), lexer.getTokenStart(), lexer.getState())); lexer.advance(); } return allTokens; } public static String printTokens(CharSequence text, int start, Lexer lexer) { lexer.start(text, start, text.length()); StringBuilder result = new StringBuilder(); IElementType tokenType; while ((tokenType = lexer.getTokenType()) != null) { result.append(printSingleToken(text, tokenType, lexer.getTokenStart(), lexer.getTokenEnd())); lexer.advance(); } return result.toString(); } @NotNull public static String printTokens(@NotNull HighlighterIterator iterator) { CharSequence text = iterator.getDocument().getCharsSequence(); StringBuilder result = new StringBuilder(); IElementType tokenType; while (!iterator.atEnd()) { tokenType = iterator.getTokenType(); result.append(printSingleToken(text, tokenType, iterator.getStart(), iterator.getEnd())); iterator.advance(); } return result.toString(); } public static String printSingleToken(CharSequence fileText, IElementType tokenType, int start, int end) { return tokenType + " ('" + getTokenText(tokenType, fileText, start, end) + "')\n"; } protected void doFileTest(String fileExt) { doTest(loadTestDataFile("." + fileExt)); } @NotNull protected String loadTestDataFile(String fileExt) { String fileName = getPathToTestDataFile(fileExt); String text = ""; try { String fileText = FileUtil.loadFile(new File(fileName)); text = StringUtil.convertLineSeparators(shouldTrim() ? fileText.trim() : fileText); } catch (IOException e) { fail("can't load file " + fileName + ": " + e.getMessage()); } return text; } protected boolean shouldTrim() { return true; } @NotNull private static String getTokenText(IElementType tokenType, CharSequence sequence, int start, int end) { return tokenType instanceof TokenWrapper ? ((TokenWrapper)tokenType).getValue() : StringUtil.replace(sequence.subSequence(start, end).toString(), "\n", "\\n"); } protected abstract Lexer createLexer(); protected abstract String getDirPath(); }
apache-2.0
seelmann/ldapcon2009-datanucleus
DataNucleus-Advanced-Wicket/src/main/java/com/example/CountryViewPage.java
3358
/********************************************************************** Copyright (c) 2009 Stefan Seelmann. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********************************************************************/ package com.example; import java.util.ArrayList; import java.util.List; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.PropertyModel; import com.example.dao.CountryDao; public class CountryViewPage extends WebPage { private final WebPage previousPage; private final Country country; public CountryViewPage( WebPage previousPage, Country country ) { this.previousPage = previousPage; this.country = new CountryDao().loadWithUnits( country.getName() ); add( new FeedbackPanel( "feedback" ) ); add( new ViewForm( "countryViewForm" ) ); } public final class ViewForm extends Form<User> { private static final long serialVersionUID = 1L; public ViewForm( final String componentName ) { super( componentName ); add( new Label( "name", new PropertyModel<Unit>( country, "name" ) ) ); List<Unit> units = new ArrayList<Unit>( country.getUnits() ); add( new ListView<Unit>( "units", units ) { private static final long serialVersionUID = 1L; @Override protected void populateItem( ListItem<Unit> item ) { Unit unit = item.getModelObject(); Link<Unit> unitViewLink = new Link<Unit>( "unitView", item.getModel() ) { private static final long serialVersionUID = 1L; public void onClick() { setResponsePage( new UnitViewPage( CountryViewPage.this, getModelObject() ) ); } }; item.add( unitViewLink ); unitViewLink.add( new Label( "unitName", unit.getName() ) ); } } ); Button backButton = new Button( "backButton" ) { private static final long serialVersionUID = 1L; public void onSubmit() { setResponsePage( previousPage ); } }; backButton.setDefaultFormProcessing( false ); add( backButton ); } } }
apache-2.0
Dempsy/dempsy-commons
dempsy-serialization.api/src/test/java/net/dempsy/serialization/MockClass.java
1782
package net.dempsy.serialization; /* * Copyright 2012 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. */ import java.io.Serializable; /** * Simple mock bean for TestDefaultSerializer, * only lives in it's own class to make serialization easier. */ @SuppressWarnings("serial") public class MockClass implements Serializable { private int i; private String s; public MockClass() { // Miranda constructor to make Serialization happy } public MockClass(int i, String s) { this.i = i; this.s = s; } public void setI(int i) { this.i = i; } public void setS(String s) { this.s = s; } public int getI() { return i; } public String getS() { return s; } public boolean equals(Object other) { if (other == null) return false; if (! (other instanceof MockClass)) return false; MockClass t = (MockClass)other; if (t.getI() != i) return false; if ((s != null && t.getS() == null) || (s == null && t.getS() != null) || (! s.equals(t.getS()))) return false; return true; } }
apache-2.0
ChrOertlin/MiPaSt
org.pathvisio.mipast/src/org/pathvisio/mipast/io/FileMerger.java
7842
//Copyright 2014 BiGCaT // //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.pathvisio.mipast.io; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.JOptionPane; import org.pathvisio.core.preferences.GlobalPreference; import org.pathvisio.core.preferences.PreferenceManager; import org.pathvisio.gexplugin.GexTxtImporter; import org.pathvisio.gexplugin.ImportInformation; import org.pathvisio.gexplugin.ImportInformation; import org.pathvisio.mipast.DataHolding; import org.pathvisio.mipast.MiPaStFileReader; /** * * The FilerMerger class combines two data expression files into one combined * file that can be further handled by PathVisio. * * @author ChrOertlin * */ public class FileMerger { MiPaStFileReader fr = new MiPaStFileReader(); boolean sharedHeader = false; File combinedFile; /** * Creates the combined file, if two files are given to the plugin, and * return a combinedFile which can be accessed for importinformation * * @return */ public File createCombinedFile(ImportInformation miRNA, ImportInformation gene) throws IOException { combinedFile = new File(miRNA.getTxtFile().getParentFile() + "/combinedTxt.txt"); File miRNAFile = new File("miRNA"); File geneFile = new File("gene"); List<String> miRNALines; List<String> geneLines; MiPaStFileReader fr = new MiPaStFileReader(); miRNAFile = miRNA.getTxtFile(); geneFile = gene.getTxtFile(); miRNALines = fr.fileReader(miRNAFile); geneLines = fr.fileReader(geneFile); BufferedWriter fbw = new BufferedWriter(new FileWriter(combinedFile)); getDataRows(miRNA, miRNALines, gene, geneLines, fbw); fbw.close(); return combinedFile; } /** * Creates the combined header of the two input files, if two headers are * the same only one of the headers is taken into the combined header. * */ public List<String> createCombinedHeader(ImportInformation miRNA, ImportInformation gene) { List<String> combinedHeader = new ArrayList<String>( miRNA.getColNames().length + gene.getColNames().length + 1); combinedHeader.add("identifier"); combinedHeader.add("system code"); for (int i = 0; i < miRNA.getColNames().length; i++) { if (!combinedHeader.contains(miRNA.getColNames()[i]) && i != miRNA.getIdColumn()) { combinedHeader.add(miRNA.getColNames()[i]); } } checkDuplicateHeaders(gene, combinedHeader); for (int i = 0; i < gene.getColNames().length; i++) { if (!combinedHeader.contains(gene.getColNames()[i]) && i != gene.getIdColumn()) { combinedHeader.add(gene.getColNames()[i]); } } combinedHeader.add("type"); for (int i = 0; i < combinedHeader.size(); i++) { if (combinedHeader.get(i).isEmpty()) { combinedHeader.remove(i); } } return combinedHeader; } /** * Retrieves data rows from the expression data files and writes them to the * combined file. If there are values that fall under a shared header they * will be written below the shared header. If there is no value for a * header then the column will be left blank. */ public void getDataRows(ImportInformation miRNA, List<String> miRNALines, ImportInformation gene, List<String> geneLines, BufferedWriter fbw) throws IOException { String[] miRNAValues = null; String[] geneValues = null; List<String> combinedHeader = new ArrayList<String>(); combinedHeader = createCombinedHeader(miRNA, gene); List<String> miRNAData = new ArrayList<String>(); List<String> geneData = new ArrayList<String>(); writeToFile(combinedHeader, fbw); for (int i = 1; i < miRNALines.size(); i++) { miRNAValues = miRNALines.get(i).split(miRNA.getDelimiter()); miRNAData = fillDataRows(miRNAValues, combinedHeader, miRNA, "miRNA"); writeToFile(miRNAData, fbw); } for (int j = 1; j < geneLines.size(); j++) { geneValues = geneLines.get(j).split(gene.getDelimiter()); geneData = fillDataRows(geneValues, combinedHeader, gene, "gene"); writeToFile(geneData, fbw); } } /** * Sorts the data rows to the right place along the combined header, so that * every value is written into the right column. * */ public List<String> fillDataRows(String[] dataArray, List<String> combinedHeader, ImportInformation info, String type) { List<String> data = new ArrayList<String>(combinedHeader.size()); for (int i = 0; i < combinedHeader.size(); i++) { data.add(""); } boolean systemCodeAdded; for (int k = 0; k < dataArray.length; k++) { systemCodeAdded = false; if (k == info.getIdColumn()) { data.add(0, dataArray[k]); } if (info.isSyscodeFixed() && !combinedHeader.contains(info.getColNames()[k]) && !systemCodeAdded) { data.add(1, info.getDataSource().getSystemCode()); systemCodeAdded = true; } if (!info.isSyscodeFixed() && !combinedHeader.contains(info.getColNames()[k]) && !systemCodeAdded) { data.add(1, dataArray[info.getSyscodeColumn()]); systemCodeAdded = true; } if (combinedHeader.contains(info.getColNames()[k]) && k != info.getIdColumn() && combinedHeader.get(k) != "type" && !combinedHeader.isEmpty() && type == "miRNA") { data.add(combinedHeader.indexOf(info.getColNames()[k]),dataArray[k]); } if(combinedHeader.contains(info.getColNames()[k]) && type =="gene" && combinedHeader.get(k) != "type" && k != info.getIdColumn()){ for(String s : combinedHeader){ if(info.getColNames()[k].equals(s)){ data.add(combinedHeader.indexOf(s), dataArray[k]); } } } if (k == dataArray.length - 1) { data.add(combinedHeader.indexOf("type"), type); } } if (type == "gene"&& !info.isSyscodeFixed()) { DataHolding.setGeneSysCode(dataArray[info .getSyscodeColumn()]); } if(type == "gene"&& info.isSyscodeFixed()){ DataHolding.setGeneSysCode(info.getDataSource().getSystemCode()); } if (type == "miRNA" && !info.isSyscodeFixed()){ DataHolding.setMiRNASysCode(dataArray[info .getSyscodeColumn()]); } if(type == "miRNA"&& info.isSyscodeFixed()){ DataHolding.setMiRNASysCode(info.getDataSource().getSystemCode()); } return data; } public void writeToFile(List<String> array, BufferedWriter fbw) throws IOException { for (int i = 0; i < array.size(); i++) { fbw.write(array.get(i) + "\t"); } fbw.newLine(); } /** * checkDuplicateHeaders look in both files and checks if there are headers * that exist in both files. If so, sharedHeader will be true. This check is * needed to report back to make sure that a later visualization will be * possible. If there are no shared columns it will not be possible to shows * interactions. * */ public void checkDuplicateHeaders(ImportInformation info, List<String> combinedHeader) { for (int i = 0; i < info.getColNames().length; i++) { if (combinedHeader.contains(info.getColNames()[i])) { sharedHeader = true; } } } /** * Setters and getters * */ public boolean getSharedHeader() { return sharedHeader; } public File getCombinedFile() { return combinedFile; } }
apache-2.0
CaoYouXin/serveV2
server/controller/src/controller/TestController.java
1350
package controller; import beans.BeanManager; import config.Configs; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.protocol.HttpContext; import rest.Controller; import rest.WithMatcher; import rest.JsonResponse; import rest.RestHelper; import service.ITestService; import util.loader.CustomClassLoader; import java.io.IOException; public class TestController extends WithMatcher implements Controller { static { } private ITestService service = BeanManager.getInstance().getService(ITestService.class); @Override public String name() { return "controller.TestController"; } @Override public String urlPattern() { return "/test"; } @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { CustomClassLoader classLoader = Configs.getConfigs(Configs.CLASSLOADER, CustomClassLoader.class); BeanManager.getInstance().setService( (Class<ITestService>) classLoader.loadClass("service.ITestService"), (Class<ITestService>) classLoader.loadClass("service.impl.TestService") ); RestHelper.responseJSON(response, JsonResponse.success(this.service.test())); } }
apache-2.0
sdnwiselab/onos
providers/openflow/device/src/main/java/org/onosproject/provider/of/device/impl/PortStatsCollector.java
3623
/* * 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.provider.of.device.impl; import org.onosproject.openflow.controller.OpenFlowSwitch; import org.onosproject.openflow.controller.RoleState; import org.projectfloodlight.openflow.protocol.OFPortStatsRequest; import org.projectfloodlight.openflow.types.OFPort; import org.slf4j.Logger; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicLong; import static com.google.common.base.Preconditions.checkNotNull; import static org.slf4j.LoggerFactory.getLogger; /** * Sends Port Stats Request and collect the port statistics with a time interval. */ public class PortStatsCollector { private final Logger log = getLogger(getClass()); private static final int SECONDS = 1000; private OpenFlowSwitch sw; private Timer timer; private TimerTask task; private int refreshInterval; private final AtomicLong xidAtomic = new AtomicLong(1); /** * Creates a port states collector object. * * @param timer timer to use for scheduling * @param sw switch to pull * @param interval interval for collecting port statistic */ PortStatsCollector(Timer timer, OpenFlowSwitch sw, int interval) { this.timer = timer; this.sw = checkNotNull(sw, "Null switch"); this.refreshInterval = interval; } private class InternalTimerTask extends TimerTask { @Override public void run() { sendPortStatistic(); } } /** * Starts the port statistic collector. */ public synchronized void start() { log.info("Starting Port Stats collection thread for {}", sw.getStringId()); task = new InternalTimerTask(); timer.scheduleAtFixedRate(task, 1 * SECONDS, refreshInterval * SECONDS); } /** * Stops the port statistic collector. */ public synchronized void stop() { log.info("Stopping Port Stats collection thread for {}", sw.getStringId()); task.cancel(); task = null; } /** * Adjusts poll interval of the port statistic collector and restart. * * @param pollInterval period of collecting port statistic */ public synchronized void adjustPollInterval(int pollInterval) { this.refreshInterval = pollInterval; task.cancel(); task = new InternalTimerTask(); timer.scheduleAtFixedRate(task, refreshInterval * SECONDS, refreshInterval * SECONDS); } /** * Sends port statistic request to switch. */ private void sendPortStatistic() { if (sw.getRole() != RoleState.MASTER) { return; } Long statsXid = xidAtomic.getAndIncrement(); OFPortStatsRequest statsRequest = sw.factory().buildPortStatsRequest() .setPortNo(OFPort.ANY) .setXid(statsXid) .build(); sw.sendMsg(statsRequest); } }
apache-2.0
thomazaudio/EstradaRealSeminovos
src/util/Estado.java
317
package util; public class Estado { private int id; private String estado; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } }
apache-2.0
icoretech/audiobox-jlib
src/main/java/fm/audiobox/core/models/Genre.java
1415
/* * Copyright 2009-2016 iCoreTech, 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 fm.audiobox.core.models; import com.google.api.client.util.Key; import java.util.List; /** * Container class for a collection of {@link MediaFile} grouped by album. * <p> * It includes media file sorted by the media files' artist, album and position attributes. */ public class Genre extends Model { @Key private String token; @Key private String genre; @Key private List<? extends MediaFile> media_files; /** * Gets genre. * * @return the genre */ public String getGenre() { return genre; } /** * Gets token. * * @return the token */ public String getToken() { return token; } /** * Gets media files. * * @return the media files */ public List<? extends MediaFile> getMediaFiles() { return media_files; } }
apache-2.0
Jpcorp/STRAM
STRAM/STRAM-1.0/STRAM-1.0-domain/src/main/java/com/yousoft/stram/domain/StatusVehicule.java
908
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.yousoft.stram.domain; import java.io.Serializable; import lombok.ToString; /** * * @author jguinart */ @ToString public class StatusVehicule implements Serializable { private static final long serialVersionUID = 1L; private int id; private String name; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } }
apache-2.0
jvz/spring-boot
spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java
8537
/* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.flyway; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.annotation.PostConstruct; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.data.jpa.EntityManagerFactoryDependsOnPostProcessor; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.jdbc.DatabaseDriver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.GenericConverter; import org.springframework.core.io.ResourceLoader; import org.springframework.jdbc.support.JdbcUtils; import org.springframework.jdbc.support.MetaDataAccessException; import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * {@link EnableAutoConfiguration Auto-configuration} for Flyway database migrations. * * @author Dave Syer * @author Phillip Webb * @author Vedran Pavic * @author Stephane Nicoll * @author Jacques-Etienne Beaudet * @since 1.1.0 */ @Configuration @ConditionalOnClass(Flyway.class) @ConditionalOnBean(DataSource.class) @ConditionalOnProperty(prefix = "flyway", name = "enabled", matchIfMissing = true) @AutoConfigureAfter({ DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) public class FlywayAutoConfiguration { @Bean @ConfigurationPropertiesBinding public StringOrNumberToMigrationVersionConverter stringOrNumberMigrationVersionConverter() { return new StringOrNumberToMigrationVersionConverter(); } @Configuration @ConditionalOnMissingBean(Flyway.class) @EnableConfigurationProperties(FlywayProperties.class) public static class FlywayConfiguration { private final FlywayProperties properties; private final ResourceLoader resourceLoader; private final DataSource dataSource; private final DataSource flywayDataSource; private final FlywayMigrationStrategy migrationStrategy; public FlywayConfiguration(FlywayProperties properties, ResourceLoader resourceLoader, ObjectProvider<DataSource> dataSource, @FlywayDataSource ObjectProvider<DataSource> flywayDataSource, ObjectProvider<FlywayMigrationStrategy> migrationStrategy) { this.properties = properties; this.resourceLoader = resourceLoader; this.dataSource = dataSource.getIfUnique(); this.flywayDataSource = flywayDataSource.getIfAvailable(); this.migrationStrategy = migrationStrategy.getIfAvailable(); } @PostConstruct public void checkLocationExists() { if (this.properties.isCheckLocation()) { Assert.state(!this.properties.getLocations().isEmpty(), "Migration script locations not configured"); boolean exists = hasAtLeastOneLocation(); Assert.state(exists, "Cannot find migrations location in: " + this.properties .getLocations() + " (please add migrations or check your Flyway configuration)"); } } private boolean hasAtLeastOneLocation() { for (String location : this.properties.getLocations()) { if (this.resourceLoader.getResource(location).exists()) { return true; } } return false; } @Bean @ConfigurationProperties(prefix = "flyway") public Flyway flyway() { Flyway flyway = new SpringBootFlyway(); if (this.properties.isCreateDataSource()) { flyway.setDataSource(this.properties.getUrl(), this.properties.getUser(), this.properties.getPassword(), this.properties.getInitSqls().toArray(new String[0])); } else if (this.flywayDataSource != null) { flyway.setDataSource(this.flywayDataSource); } else { flyway.setDataSource(this.dataSource); } flyway.setLocations(this.properties.getLocations().toArray(new String[0])); return flyway; } @Bean @ConditionalOnMissingBean public FlywayMigrationInitializer flywayInitializer(Flyway flyway) { return new FlywayMigrationInitializer(flyway, this.migrationStrategy); } /** * Additional configuration to ensure that {@link EntityManagerFactory} beans * depend-on the {@code flywayInitializer} bean. */ @Configuration @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) protected static class FlywayInitializerJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { public FlywayInitializerJpaDependencyConfiguration() { super("flywayInitializer"); } } } /** * Additional configuration to ensure that {@link EntityManagerFactory} beans * depend-on the {@code flyway} bean. */ @Configuration @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) protected static class FlywayJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { public FlywayJpaDependencyConfiguration() { super("flyway"); } } private static class SpringBootFlyway extends Flyway { private static final String VENDOR_PLACEHOLDER = "{vendor}"; @Override public void setLocations(String... locations) { if (usesVendorLocation(locations)) { try { String url = (String) JdbcUtils .extractDatabaseMetaData(getDataSource(), "getURL"); DatabaseDriver vendor = DatabaseDriver.fromJdbcUrl(url); if (vendor != DatabaseDriver.UNKNOWN) { for (int i = 0; i < locations.length; i++) { locations[i] = locations[i].replace(VENDOR_PLACEHOLDER, vendor.getId()); } } } catch (MetaDataAccessException ex) { throw new IllegalStateException(ex); } } super.setLocations(locations); } private boolean usesVendorLocation(String... locations) { for (String location : locations) { if (location.contains(VENDOR_PLACEHOLDER)) { return true; } } return false; } } /** * Convert a String or Number to a {@link MigrationVersion}. */ private static class StringOrNumberToMigrationVersionConverter implements GenericConverter { private static final Set<ConvertiblePair> CONVERTIBLE_TYPES; static { Set<ConvertiblePair> types = new HashSet<ConvertiblePair>(2); types.add(new ConvertiblePair(String.class, MigrationVersion.class)); types.add(new ConvertiblePair(Number.class, MigrationVersion.class)); CONVERTIBLE_TYPES = Collections.unmodifiableSet(types); } @Override public Set<ConvertiblePair> getConvertibleTypes() { return CONVERTIBLE_TYPES; } @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { String value = ObjectUtils.nullSafeToString(source); return MigrationVersion.fromVersion(value); } } }
apache-2.0
da1z/intellij-community
platform/util/src/com/intellij/util/containers/ContainerUtil.java
85575
// Copyright 2000-2017 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.util.containers; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.*; import com.intellij.util.*; import gnu.trove.*; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Array; import java.util.*; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; @SuppressWarnings({"UtilityClassWithoutPrivateConstructor", "MethodOverridesStaticMethodOfSuperclass"}) public class ContainerUtil extends ContainerUtilRt { private static final int INSERTION_SORT_THRESHOLD = 10; @NotNull @Contract(pure=true) public static <T> T[] ar(@NotNull T... elements) { return elements; } @NotNull @Contract(pure=true) public static <K, V> HashMap<K, V> newHashMap() { return ContainerUtilRt.newHashMap(); } @NotNull @Contract(pure=true) public static <K, V> HashMap<K, V> newHashMap(@NotNull Map<? extends K, ? extends V> map) { return ContainerUtilRt.newHashMap(map); } @NotNull @Contract(pure=true) public static <K, V> Map<K, V> newHashMap(@NotNull Pair<K, ? extends V> first, @NotNull Pair<K, ? extends V>... entries) { return ContainerUtilRt.newHashMap(first, entries); } @NotNull @Contract(pure=true) public static <K, V> Map<K, V> newHashMap(@NotNull List<K> keys, @NotNull List<V> values) { return ContainerUtilRt.newHashMap(keys, values); } @NotNull @Contract(pure=true) public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() { return ContainerUtilRt.newTreeMap(); } @NotNull @Contract(pure=true) public static <K extends Comparable, V> TreeMap<K, V> newTreeMap(@NotNull Map<K, V> map) { return ContainerUtilRt.newTreeMap(map); } @NotNull @Contract(pure=true) public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() { return ContainerUtilRt.newLinkedHashMap(); } @NotNull @Contract(pure=true) public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(int capacity) { return ContainerUtilRt.newLinkedHashMap(capacity); } @NotNull @Contract(pure=true) public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(@NotNull Map<K, V> map) { return ContainerUtilRt.newLinkedHashMap(map); } @NotNull @Contract(pure=true) public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(@NotNull Pair<K, ? extends V> first, @NotNull Pair<K, ? extends V>... entries) { return ContainerUtilRt.newLinkedHashMap(first, entries); } @NotNull @Contract(pure=true) public static <K, V> THashMap<K, V> newTroveMap() { return new THashMap<K, V>(); } @NotNull @Contract(pure=true) public static <K, V> THashMap<K, V> newTroveMap(@NotNull TObjectHashingStrategy<K> strategy) { return new THashMap<K, V>(strategy); } @NotNull @Contract(pure=true) public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(@NotNull Class<K> keyType) { return new EnumMap<K, V>(keyType); } @SuppressWarnings("unchecked") @NotNull @Contract(pure=true) public static <T> TObjectHashingStrategy<T> canonicalStrategy() { return TObjectHashingStrategy.CANONICAL; } @SuppressWarnings("unchecked") @NotNull @Contract(pure=true) public static <T> TObjectHashingStrategy<T> identityStrategy() { return TObjectHashingStrategy.IDENTITY; } @NotNull @Contract(pure=true) public static <K, V> IdentityHashMap<K, V> newIdentityHashMap() { return new IdentityHashMap<K, V>(); } @NotNull @Contract(pure=true) public static <T> LinkedList<T> newLinkedList() { return ContainerUtilRt.newLinkedList(); } @NotNull @Contract(pure=true) public static <T> LinkedList<T> newLinkedList(@NotNull T... elements) { return ContainerUtilRt.newLinkedList(elements); } @NotNull @Contract(pure=true) public static <T> LinkedList<T> newLinkedList(@NotNull Iterable<? extends T> elements) { return ContainerUtilRt.newLinkedList(elements); } @NotNull @Contract(pure=true) public static <T> ArrayList<T> newArrayList() { return ContainerUtilRt.newArrayList(); } @NotNull @Contract(pure=true) public static <E> ArrayList<E> newArrayList(@NotNull E... array) { return ContainerUtilRt.newArrayList(array); } @NotNull @Contract(pure=true) public static <E> ArrayList<E> newArrayList(@NotNull Iterable<? extends E> iterable) { return ContainerUtilRt.newArrayList(iterable); } @NotNull @Contract(pure=true) public static <T> ArrayList<T> newArrayListWithCapacity(int size) { return ContainerUtilRt.newArrayListWithCapacity(size); } @NotNull @Contract(pure=true) public static <T> List<T> newArrayList(@NotNull final T[] elements, final int start, final int end) { if (start < 0 || start > end || end > elements.length) { throw new IllegalArgumentException("start:" + start + " end:" + end + " length:" + elements.length); } return new AbstractList<T>() { private final int size = end - start; @Override public T get(final int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException("index:" + index + " size:" + size); return elements[start + index]; } @Override public int size() { return size; } }; } @NotNull @Contract(pure = true) public static <T> List<T> newUnmodifiableList(List<? extends T> originalList) { int size = originalList.size(); if (size == 0) { return emptyList(); } else if (size == 1) { return Collections.singletonList(originalList.get(0)); } else { return Collections.unmodifiableList(newArrayList(originalList)); } } @NotNull @Contract(pure=true) public static <T> List<T> newSmartList() { return new SmartList<T>(); } @NotNull @Contract(pure=true) public static <T> List<T> newSmartList(T element) { return new SmartList<T>(element); } @NotNull @Contract(pure=true) public static <T> List<T> newSmartList(@NotNull T... elements) { return new SmartList<T>(elements); } @NotNull @Contract(pure=true) public static <T> HashSet<T> newHashSet() { return ContainerUtilRt.newHashSet(); } @NotNull @Contract(pure=true) public static <T> HashSet<T> newHashSet(int initialCapacity) { return ContainerUtilRt.newHashSet(initialCapacity); } @NotNull @Contract(pure=true) public static <T> HashSet<T> newHashSet(@NotNull T... elements) { return ContainerUtilRt.newHashSet(elements); } @NotNull @Contract(pure=true) public static <T> HashSet<T> newHashSet(@NotNull Iterable<? extends T> iterable) { return ContainerUtilRt.newHashSet(iterable); } @NotNull public static <T> HashSet<T> newHashSet(@NotNull Iterator<? extends T> iterator) { return ContainerUtilRt.newHashSet(iterator); } @NotNull @Contract(pure=true) public static <T> Set<T> newHashOrEmptySet(@Nullable Iterable<? extends T> iterable) { boolean empty = iterable == null || iterable instanceof Collection && ((Collection)iterable).isEmpty(); return empty ? Collections.<T>emptySet() : ContainerUtilRt.newHashSet(iterable); } @NotNull @Contract(pure=true) public static <T> LinkedHashSet<T> newLinkedHashSet() { return ContainerUtilRt.newLinkedHashSet(); } @NotNull @Contract(pure=true) public static <T> LinkedHashSet<T> newLinkedHashSet(@NotNull Iterable<? extends T> elements) { return ContainerUtilRt.newLinkedHashSet(elements); } @NotNull @Contract(pure=true) public static <T> LinkedHashSet<T> newLinkedHashSet(@NotNull T... elements) { return ContainerUtilRt.newLinkedHashSet(elements); } @NotNull @Contract(pure=true) public static <T> THashSet<T> newTroveSet() { return new THashSet<T>(); } @NotNull @Contract(pure=true) public static <T> THashSet<T> newTroveSet(@NotNull TObjectHashingStrategy<T> strategy) { return new THashSet<T>(strategy); } @NotNull @Contract(pure=true) public static <T> THashSet<T> newTroveSet(@NotNull T... elements) { return newTroveSet(Arrays.asList(elements)); } @NotNull @Contract(pure=true) public static <T> THashSet<T> newTroveSet(@NotNull TObjectHashingStrategy<T> strategy, @NotNull T... elements) { return new THashSet<T>(Arrays.asList(elements), strategy); } @NotNull @Contract(pure=true) public static <T> THashSet<T> newTroveSet(@NotNull TObjectHashingStrategy<T> strategy, @NotNull Collection<T> elements) { return new THashSet<T>(elements, strategy); } @NotNull @Contract(pure=true) public static <T> THashSet<T> newTroveSet(@NotNull Collection<T> elements) { return new THashSet<T>(elements); } @NotNull @Contract(pure=true) public static <K> THashSet<K> newIdentityTroveSet() { return new THashSet<K>(ContainerUtil.<K>identityStrategy()); } @NotNull @Contract(pure=true) public static <K> THashSet<K> newIdentityTroveSet(int initialCapacity) { return new THashSet<K>(initialCapacity, ContainerUtil.<K>identityStrategy()); } @NotNull @Contract(pure=true) public static <K> THashSet<K> newIdentityTroveSet(@NotNull Collection<K> collection) { return new THashSet<K>(collection, ContainerUtil.<K>identityStrategy()); } @NotNull @Contract(pure=true) public static <K,V> THashMap<K,V> newIdentityTroveMap() { return new THashMap<K,V>(ContainerUtil.<K>identityStrategy()); } @NotNull @Contract(pure=true) public static <T> TreeSet<T> newTreeSet() { return ContainerUtilRt.newTreeSet(); } @NotNull @Contract(pure=true) public static <T> TreeSet<T> newTreeSet(@NotNull Iterable<? extends T> elements) { return ContainerUtilRt.newTreeSet(elements); } @NotNull @Contract(pure=true) public static <T> TreeSet<T> newTreeSet(@NotNull T... elements) { return ContainerUtilRt.newTreeSet(elements); } @NotNull @Contract(pure=true) public static <T> TreeSet<T> newTreeSet(@Nullable Comparator<? super T> comparator) { return ContainerUtilRt.newTreeSet(comparator); } @NotNull @Contract(pure=true) public static <T> Set<T> newConcurrentSet() { return Collections.newSetFromMap(ContainerUtil.<T, Boolean>newConcurrentMap()); } @NotNull @Contract(pure=true) public static <K, V> ConcurrentMap<K, V> newConcurrentMap() { return new ConcurrentHashMap<K, V>(); } @Contract(pure=true) public static <K, V> ConcurrentMap<K,V> newConcurrentMap(int initialCapacity) { return new ConcurrentHashMap<K, V>(initialCapacity); } @Contract(pure=true) public static <K, V> ConcurrentMap<K,V> newConcurrentMap(int initialCapacity, float loadFactor, int concurrencyLevel) { return new ConcurrentHashMap<K, V>(initialCapacity, loadFactor, concurrencyLevel); } @NotNull @Contract(pure=true) public static <E> List<E> reverse(@NotNull final List<E> elements) { if (elements.isEmpty()) { return ContainerUtilRt.emptyList(); } return new AbstractList<E>() { @Override public E get(int index) { return elements.get(elements.size() - 1 - index); } @Override public int size() { return elements.size(); } }; } @NotNull @Contract(pure=true) public static <K, V> Map<K, V> union(@NotNull Map<? extends K, ? extends V> map, @NotNull Map<? extends K, ? extends V> map2) { Map<K, V> result = new THashMap<K, V>(map.size() + map2.size()); result.putAll(map); result.putAll(map2); return result; } @NotNull @Contract(pure=true) public static <T> Set<T> union(@NotNull Set<T> set, @NotNull Set<T> set2) { return union((Collection<T>)set, set2); } @NotNull @Contract(pure=true) public static <T> Set<T> union(@NotNull Collection<T> set, @NotNull Collection<T> set2) { Set<T> result = new THashSet<T>(set.size() + set2.size()); result.addAll(set); result.addAll(set2); return result; } @NotNull @Contract(pure=true) public static <E> Set<E> immutableSet(@NotNull E... elements) { switch (elements.length) { case 0: return Collections.emptySet(); case 1: return Collections.singleton(elements[0]); default: return Collections.unmodifiableSet(new THashSet<E>(Arrays.asList(elements))); } } @NotNull @Contract(pure=true) public static <E> ImmutableList<E> immutableList(@NotNull E ... array) { return new ImmutableListBackedByArray<E>(array); } @NotNull @Contract(pure=true) public static <E> ImmutableList<E> immutableSingletonList(final E element) { return ImmutableList.singleton(element); } @NotNull @Contract(pure=true) public static <E> ImmutableList<E> immutableList(@NotNull List<E> list) { return new ImmutableListBackedByList<E>(list); } @NotNull @Contract(pure=true) public static <K, V> ImmutableMapBuilder<K, V> immutableMapBuilder() { return new ImmutableMapBuilder<K, V>(); } @NotNull public static <K, V> MultiMap<K, V> groupBy(@NotNull Iterable<V> collection, @NotNull NullableFunction<V, K> grouper) { MultiMap<K, V> result = MultiMap.createLinked(); for (V data : collection) { K key = grouper.fun(data); if (key == null) { continue; } result.putValue(key, data); } if (!result.isEmpty() && result.keySet().iterator().next() instanceof Comparable) { return new KeyOrderedMultiMap<K, V>(result); } return result; } @Contract(pure = true) public static <T> T getOrElse(@NotNull List<T> elements, int i, T defaultValue) { return elements.size() > i ? elements.get(i) : defaultValue; } public static class ImmutableMapBuilder<K, V> { private final Map<K, V> myMap = new THashMap<K, V>(); public ImmutableMapBuilder<K, V> put(K key, V value) { myMap.put(key, value); return this; } @Contract(pure=true) public Map<K, V> build() { return Collections.unmodifiableMap(myMap); } } private static class ImmutableListBackedByList<E> extends ImmutableList<E> { private final List<E> myStore; private ImmutableListBackedByList(@NotNull List<E> list) { myStore = list; } @Override public E get(int index) { return myStore.get(index); } @Override public int size() { return myStore.size(); } } private static class ImmutableListBackedByArray<E> extends ImmutableList<E> { private final E[] myStore; private ImmutableListBackedByArray(@NotNull E[] array) { myStore = array; } @Override public E get(int index) { return myStore[index]; } @Override public int size() { return myStore.length; } } @NotNull @Contract(pure=true) public static <K, V> Map<K, V> intersection(@NotNull Map<K, V> map1, @NotNull Map<K, V> map2) { final Map<K, V> res = newHashMap(); final Set<K> keys = newHashSet(); keys.addAll(map1.keySet()); keys.addAll(map2.keySet()); for (K k : keys) { V v1 = map1.get(k); V v2 = map2.get(k); if (v1 == v2 || v1 != null && v1.equals(v2)) { res.put(k, v1); } } return res; } @NotNull @Contract(pure=true) public static <K, V> Map<K,Couple<V>> diff(@NotNull Map<K, V> map1, @NotNull Map<K, V> map2) { final Map<K, Couple<V>> res = newHashMap(); final Set<K> keys = newHashSet(); keys.addAll(map1.keySet()); keys.addAll(map2.keySet()); for (K k : keys) { V v1 = map1.get(k); V v2 = map2.get(k); if (!(v1 == v2 || v1 != null && v1.equals(v2))) { res.put(k, Couple.of(v1, v2)); } } return res; } public static <T> void processSortedListsInOrder(@NotNull List<T> list1, @NotNull List<T> list2, @NotNull Comparator<? super T> comparator, boolean mergeEqualItems, @NotNull Consumer<T> processor) { int index1 = 0; int index2 = 0; while (index1 < list1.size() || index2 < list2.size()) { T e; if (index1 >= list1.size()) { e = list2.get(index2++); } else if (index2 >= list2.size()) { e = list1.get(index1++); } else { T element1 = list1.get(index1); T element2 = list2.get(index2); int c = comparator.compare(element1, element2); if (c <= 0) { e = element1; index1++; } else { e = element2; index2++; } if (c == 0 && !mergeEqualItems) { processor.consume(e); index2++; e = element2; } } processor.consume(e); } } @NotNull @Contract(pure=true) public static <T> List<T> mergeSortedLists(@NotNull List<T> list1, @NotNull List<T> list2, @NotNull Comparator<? super T> comparator, boolean mergeEqualItems) { final List<T> result = new ArrayList<T>(list1.size() + list2.size()); processSortedListsInOrder(list1, list2, comparator, mergeEqualItems, new Consumer<T>() { @Override public void consume(T t) { result.add(t); } }); return result; } @NotNull @Contract(pure=true) public static <T> List<T> subList(@NotNull List<T> list, int from) { return list.subList(from, list.size()); } public static <T> void addAll(@NotNull Collection<T> collection, @NotNull Iterable<? extends T> appendix) { addAll(collection, appendix.iterator()); } public static <T> void addAll(@NotNull Collection<T> collection, @NotNull Iterator<? extends T> iterator) { while (iterator.hasNext()) { T o = iterator.next(); collection.add(o); } } /** * Adds all not-null elements from the {@code elements}, ignoring nulls */ public static <T> void addAllNotNull(@NotNull Collection<T> collection, @NotNull Iterable<? extends T> elements) { addAllNotNull(collection, elements.iterator()); } /** * Adds all not-null elements from the {@code elements}, ignoring nulls */ public static <T> void addAllNotNull(@NotNull Collection<T> collection, @NotNull Iterator<? extends T> elements) { while (elements.hasNext()) { T o = elements.next(); if (o != null) { collection.add(o); } } } @NotNull public static <T> List<T> collect(@NotNull Iterator<T> iterator) { if (!iterator.hasNext()) return emptyList(); List<T> list = new ArrayList<T>(); addAll(list, iterator); return list; } @NotNull public static <T> Set<T> collectSet(@NotNull Iterator<T> iterator) { if (!iterator.hasNext()) return Collections.emptySet(); Set<T> hashSet = newHashSet(); addAll(hashSet, iterator); return hashSet; } @NotNull public static <K, V> Map<K, V> newMapFromKeys(@NotNull Iterator<K> keys, @NotNull Convertor<K, V> valueConvertor) { Map<K, V> map = newHashMap(); while (keys.hasNext()) { K key = keys.next(); map.put(key, valueConvertor.convert(key)); } return map; } @NotNull public static <K, V> Map<K, V> newMapFromValues(@NotNull Iterator<V> values, @NotNull Convertor<V, K> keyConvertor) { Map<K, V> map = newHashMap(); fillMapWithValues(map, values, keyConvertor); return map; } public static <K, V> void fillMapWithValues(@NotNull Map<K, V> map, @NotNull Iterator<V> values, @NotNull Convertor<V, K> keyConvertor) { while (values.hasNext()) { V value = values.next(); map.put(keyConvertor.convert(value), value); } } @NotNull public static <K, V> Map<K, Set<V>> classify(@NotNull Iterator<V> iterator, @NotNull Convertor<V, K> keyConvertor) { Map<K, Set<V>> hashMap = new LinkedHashMap<K, Set<V>>(); while (iterator.hasNext()) { V value = iterator.next(); final K key = keyConvertor.convert(value); Set<V> set = hashMap.get(key); if (set == null) { hashMap.put(key, set = new LinkedHashSet<V>()); // ordered set!! } set.add(value); } return hashMap; } @NotNull @Contract(pure=true) public static <T> Iterator<T> emptyIterator() { return EmptyIterator.getInstance(); } @NotNull @Contract(pure=true) public static <T> Iterable<T> emptyIterable() { return EmptyIterable.getInstance(); } @Nullable @Contract(pure=true) public static <T> T find(@NotNull T[] array, @NotNull Condition<? super T> condition) { for (T element : array) { if (condition.value(element)) return element; } return null; } public static <T> boolean process(@NotNull Iterable<? extends T> iterable, @NotNull Processor<T> processor) { for (final T t : iterable) { if (!processor.process(t)) { return false; } } return true; } public static <T> boolean process(@NotNull List<? extends T> list, @NotNull Processor<T> processor) { //noinspection ForLoopReplaceableByForEach for (int i = 0, size = list.size(); i < size; i++) { T t = list.get(i); if (!processor.process(t)) { return false; } } return true; } public static <T> boolean process(@NotNull T[] iterable, @NotNull Processor<? super T> processor) { for (final T t : iterable) { if (!processor.process(t)) { return false; } } return true; } public static <T> boolean process(@NotNull Iterator<T> iterator, @NotNull Processor<? super T> processor) { while (iterator.hasNext()) { if (!processor.process(iterator.next())) { return false; } } return true; } @Nullable @Contract(pure=true) public static <T, V extends T> V find(@NotNull Iterable<V> iterable, @NotNull Condition<T> condition) { return find(iterable.iterator(), condition); } @Nullable @Contract(pure=true) public static <T> T find(@NotNull Iterable<? extends T> iterable, @NotNull final T equalTo) { return find(iterable, new Condition<T>() { @Override public boolean value(final T object) { return equalTo == object || equalTo.equals(object); } }); } @Nullable @Contract(pure=true) public static <T> T find(@NotNull Iterator<? extends T> iterator, @NotNull final T equalTo) { return find(iterator, new Condition<T>() { @Override public boolean value(final T object) { return equalTo == object || equalTo.equals(object); } }); } @Nullable public static <T, V extends T> V find(@NotNull Iterator<V> iterator, @NotNull Condition<T> condition) { while (iterator.hasNext()) { V value = iterator.next(); if (condition.value(value)) return value; } return null; } @Nullable public static <T, V extends T> V findLast(@NotNull List<V> list, @NotNull Condition<T> condition) { int index = lastIndexOf(list, condition); if (index < 0) return null; return list.get(index); } @NotNull @Contract(pure=true) public static <T, K, V> Map<K, V> map2Map(@NotNull T[] collection, @NotNull Function<T, Pair<K, V>> mapper) { return map2Map(Arrays.asList(collection), mapper); } @NotNull @Contract(pure=true) public static <T, K, V> Map<K, V> map2Map(@NotNull Collection<? extends T> collection, @NotNull Function<T, Pair<K, V>> mapper) { final Map<K, V> set = new THashMap<K, V>(collection.size()); for (T t : collection) { Pair<K, V> pair = mapper.fun(t); set.put(pair.first, pair.second); } return set; } @NotNull @Contract(pure = true) public static <T, K, V> Map<K, V> map2MapNotNull(@NotNull T[] collection, @NotNull Function<T, Pair<K, V>> mapper) { return map2MapNotNull(Arrays.asList(collection), mapper); } @NotNull @Contract(pure = true) public static <T, K, V> Map<K, V> map2MapNotNull(@NotNull Collection<? extends T> collection, @NotNull Function<T, Pair<K, V>> mapper) { final Map<K, V> set = new THashMap<K, V>(collection.size()); for (T t : collection) { Pair<K, V> pair = mapper.fun(t); if (pair != null) { set.put(pair.first, pair.second); } } return set; } @NotNull @Contract(pure=true) public static <K, V> Map<K, V> map2Map(@NotNull Collection<Pair<K, V>> collection) { final Map<K, V> result = new THashMap<K, V>(collection.size()); for (Pair<K, V> pair : collection) { result.put(pair.first, pair.second); } return result; } @NotNull @Contract(pure=true) public static <T> Object[] map2Array(@NotNull T[] array, @NotNull Function<T, Object> mapper) { return map2Array(array, Object.class, mapper); } @NotNull @Contract(pure=true) public static <T> Object[] map2Array(@NotNull Collection<T> array, @NotNull Function<T, Object> mapper) { return map2Array(array, Object.class, mapper); } @NotNull @Contract(pure=true) public static <T, V> V[] map2Array(@NotNull T[] array, @NotNull Class<? super V> aClass, @NotNull Function<T, V> mapper) { return map2Array(Arrays.asList(array), aClass, mapper); } @NotNull @Contract(pure=true) public static <T, V> V[] map2Array(@NotNull Collection<? extends T> collection, @NotNull Class<? super V> aClass, @NotNull Function<T, V> mapper) { final List<V> list = map2List(collection, mapper); @SuppressWarnings("unchecked") V[] array = (V[])Array.newInstance(aClass, list.size()); return list.toArray(array); } @NotNull @Contract(pure=true) public static <T, V> V[] map2Array(@NotNull Collection<? extends T> collection, @NotNull V[] to, @NotNull Function<T, V> mapper) { return map2List(collection, mapper).toArray(to); } @NotNull @Contract(pure=true) public static <T> List<T> filter(@NotNull T[] collection, @NotNull Condition<? super T> condition) { return findAll(collection, condition); } @NotNull @Contract(pure=true) public static int[] filter(@NotNull int[] collection, @NotNull TIntProcedure condition) { TIntArrayList result = new TIntArrayList(); for (int t : collection) { if (condition.execute(t)) { result.add(t); } } return result.isEmpty() ? ArrayUtil.EMPTY_INT_ARRAY : result.toNativeArray(); } @NotNull @Contract(pure=true) public static <T> List<T> findAll(@NotNull T[] collection, @NotNull Condition<? super T> condition) { final List<T> result = new SmartList<T>(); for (T t : collection) { if (condition.value(t)) { result.add(t); } } return result; } @NotNull @Contract(pure=true) public static <T> List<T> filter(@NotNull Collection<? extends T> collection, @NotNull Condition<? super T> condition) { return findAll(collection, condition); } @NotNull @Contract(pure = true) public static <K, V> Map<K, V> filter(@NotNull Map<K, ? extends V> map, @NotNull Condition<? super K> keyFilter) { Map<K, V> result = newHashMap(); for (Map.Entry<K, ? extends V> entry : map.entrySet()) { if (keyFilter.value(entry.getKey())) { result.put(entry.getKey(), entry.getValue()); } } return result; } @NotNull @Contract(pure=true) public static <T> List<T> findAll(@NotNull Collection<? extends T> collection, @NotNull Condition<? super T> condition) { if (collection.isEmpty()) return emptyList(); final List<T> result = new SmartList<T>(); for (final T t : collection) { if (condition.value(t)) { result.add(t); } } return result; } @NotNull @Contract(pure=true) public static <T> List<T> skipNulls(@NotNull Collection<? extends T> collection) { return findAll(collection, Condition.NOT_NULL); } @NotNull @Contract(pure=true) public static <T, V> List<V> findAll(@NotNull T[] collection, @NotNull Class<V> instanceOf) { return findAll(Arrays.asList(collection), instanceOf); } @NotNull @Contract(pure=true) public static <T, V> V[] findAllAsArray(@NotNull T[] collection, @NotNull Class<V> instanceOf) { List<V> list = findAll(Arrays.asList(collection), instanceOf); @SuppressWarnings("unchecked") V[] array = (V[])Array.newInstance(instanceOf, list.size()); return list.toArray(array); } @NotNull @Contract(pure=true) public static <T, V> V[] findAllAsArray(@NotNull Collection<? extends T> collection, @NotNull Class<V> instanceOf) { List<V> list = findAll(collection, instanceOf); @SuppressWarnings("unchecked") V[] array = (V[])Array.newInstance(instanceOf, list.size()); return list.toArray(array); } @NotNull @Contract(pure=true) public static <T> T[] findAllAsArray(@NotNull T[] collection, @NotNull Condition<? super T> instanceOf) { List<T> list = findAll(collection, instanceOf); if (list.size() == collection.length) { return collection; } @SuppressWarnings("unchecked") T[] array = (T[])Array.newInstance(collection.getClass().getComponentType(), list.size()); return list.toArray(array); } @NotNull @Contract(pure=true) public static <T, V> List<V> findAll(@NotNull Collection<? extends T> collection, @NotNull Class<V> instanceOf) { final List<V> result = new SmartList<V>(); for (final T t : collection) { if (instanceOf.isInstance(t)) { @SuppressWarnings("unchecked") V v = (V)t; result.add(v); } } return result; } public static <T> void removeDuplicates(@NotNull Collection<T> collection) { Set<T> collected = newHashSet(); for (Iterator<T> iterator = collection.iterator(); iterator.hasNext();) { T t = iterator.next(); if (!collected.contains(t)) { collected.add(t); } else { iterator.remove(); } } } @NotNull @Contract(pure=true) public static Map<String, String> stringMap(@NotNull final String... keyValues) { final Map<String, String> result = newHashMap(); for (int i = 0; i < keyValues.length - 1; i+=2) { result.put(keyValues[i], keyValues[i+1]); } return result; } @NotNull @Contract(pure=true) public static <T> Iterator<T> iterate(@NotNull T[] array) { return array.length == 0 ? EmptyIterator.<T>getInstance() : Arrays.asList(array).iterator(); } @NotNull @Contract(pure=true) public static <T> Iterator<T> iterate(@NotNull final Enumeration<T> enumeration) { return new Iterator<T>() { @Override public boolean hasNext() { return enumeration.hasMoreElements(); } @Override public T next() { return enumeration.nextElement(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @NotNull @Contract(pure=true) public static <T> Iterable<T> iterate(@NotNull T[] arrays, @NotNull Condition<? super T> condition) { return iterate(Arrays.asList(arrays), condition); } @NotNull @Contract(pure=true) public static <T> Iterable<T> iterate(@NotNull final Collection<? extends T> collection, @NotNull final Condition<? super T> condition) { if (collection.isEmpty()) return emptyIterable(); return new Iterable<T>() { @NotNull @Override public Iterator<T> iterator() { return new Iterator<T>() { private final Iterator<? extends T> impl = collection.iterator(); private T next = findNext(); @Override public boolean hasNext() { return next != null; } @Override public T next() { T result = next; next = findNext(); return result; } @Nullable private T findNext() { while (impl.hasNext()) { T each = impl.next(); if (condition.value(each)) { return each; } } return null; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } @NotNull @Contract(pure=true) public static <T> Iterable<T> iterateBackward(@NotNull final List<? extends T> list) { return new Iterable<T>() { @NotNull @Override public Iterator<T> iterator() { return new Iterator<T>() { private final ListIterator<? extends T> it = list.listIterator(list.size()); @Override public boolean hasNext() { return it.hasPrevious(); } @Override public T next() { return it.previous(); } @Override public void remove() { it.remove(); } }; } }; } @NotNull @Contract(pure=true) public static <T, E> Iterable<Pair<T, E>> zip(@NotNull final Iterable<T> iterable1, @NotNull final Iterable<E> iterable2) { return new Iterable<Pair<T, E>>() { @NotNull @Override public Iterator<Pair<T, E>> iterator() { return new Iterator<Pair<T, E>>() { private final Iterator<T> i1 = iterable1.iterator(); private final Iterator<E> i2 = iterable2.iterator(); @Override public boolean hasNext() { return i1.hasNext() && i2.hasNext(); } @Override public Pair<T, E> next() { return Pair.create(i1.next(), i2.next()); } @Override public void remove() { i1.remove(); i2.remove(); } }; } }; } public static <E> void swapElements(@NotNull List<E> list, int index1, int index2) { E e1 = list.get(index1); E e2 = list.get(index2); list.set(index1, e2); list.set(index2, e1); } @NotNull public static <T> List<T> collect(@NotNull Iterator<?> iterator, @NotNull FilteringIterator.InstanceOf<T> instanceOf) { @SuppressWarnings("unchecked") List<T> list = collect(FilteringIterator.create((Iterator<T>)iterator, instanceOf)); return list; } public static <T> void addAll(@NotNull Collection<T> collection, @NotNull Enumeration<? extends T> enumeration) { while (enumeration.hasMoreElements()) { T element = enumeration.nextElement(); collection.add(element); } } @NotNull public static <T, A extends T, C extends Collection<T>> C addAll(@NotNull C collection, @NotNull A... elements) { //noinspection ManualArrayToCollectionCopy for (T element : elements) { collection.add(element); } return collection; } /** * Adds all not-null elements from the {@code elements}, ignoring nulls */ @NotNull public static <T, A extends T, C extends Collection<T>> C addAllNotNull(@NotNull C collection, @NotNull A... elements) { for (T element : elements) { if (element != null) { collection.add(element); } } return collection; } public static <T> boolean removeAll(@NotNull Collection<T> collection, @NotNull T... elements) { boolean modified = false; for (T element : elements) { modified |= collection.remove(element); } return modified; } // returns true if the collection was modified public static <T> boolean retainAll(@NotNull Collection<T> collection, @NotNull Condition<? super T> condition) { boolean modified = false; for (Iterator<T> iterator = collection.iterator(); iterator.hasNext(); ) { T next = iterator.next(); if (!condition.value(next)) { iterator.remove(); modified = true; } } return modified; } @Contract(pure=true) public static <T, U extends T> U findInstance(@NotNull Iterable<T> iterable, @NotNull Class<U> aClass) { return findInstance(iterable.iterator(), aClass); } public static <T, U extends T> U findInstance(@NotNull Iterator<T> iterator, @NotNull Class<U> aClass) { //noinspection unchecked return (U)find(iterator, FilteringIterator.instanceOf(aClass)); } @Nullable @Contract(pure=true) public static <T, U extends T> U findInstance(@NotNull T[] array, @NotNull Class<U> aClass) { return findInstance(Arrays.asList(array), aClass); } @NotNull @Contract(pure=true) public static <T, V> List<T> concat(@NotNull V[] array, @NotNull Function<V, Collection<? extends T>> fun) { return concat(Arrays.asList(array), fun); } /** * @return read-only list consisting of the elements from the collections stored in list added together */ @NotNull @Contract(pure=true) public static <T> List<T> concat(@NotNull Iterable<? extends Collection<T>> list) { List<T> result = new ArrayList<T>(); for (final Collection<T> ts : list) { result.addAll(ts); } return result.isEmpty() ? Collections.<T>emptyList() : result; } /** * @deprecated Use {@link #append(List, Object[])} or {@link #prepend(List, Object[])} instead * @param appendTail specify whether additional values should be appended in front or after the list * @return read-only list consisting of the elements from specified list with some additional values */ @Deprecated @NotNull @Contract(pure=true) public static <T> List<T> concat(boolean appendTail, @NotNull List<? extends T> list, @NotNull T... values) { return appendTail ? concat(list, list(values)) : concat(list(values), list); } @NotNull @Contract(pure=true) public static <T> List<T> append(@NotNull List<? extends T> list, @NotNull T... values) { return concat(list, list(values)); } /** * prepend values in front of the list * @return read-only list consisting of values and the elements from specified list */ @NotNull @Contract(pure=true) public static <T> List<T> prepend(@NotNull List<? extends T> list, @NotNull T... values) { return concat(list(values), list); } /** * @return read-only list consisting of the two lists added together */ @NotNull @Contract(pure=true) public static <T> List<T> concat(@NotNull final List<? extends T> list1, @NotNull final List<? extends T> list2) { if (list1.isEmpty() && list2.isEmpty()) { return Collections.emptyList(); } if (list1.isEmpty()) { //noinspection unchecked return (List<T>)list2; } if (list2.isEmpty()) { //noinspection unchecked return (List<T>)list1; } final int size1 = list1.size(); final int size = size1 + list2.size(); return new AbstractList<T>() { @Override public T get(int index) { if (index < size1) { return list1.get(index); } return list2.get(index - size1); } @Override public int size() { return size; } }; } @SuppressWarnings({"unchecked", "LambdaUnfriendlyMethodOverload"}) @NotNull @Contract(pure=true) public static <T> Iterable<T> concat(@NotNull final Iterable<? extends T>... iterables) { if (iterables.length == 0) return emptyIterable(); if (iterables.length == 1) return (Iterable<T>)iterables[0]; return new Iterable<T>() { @NotNull @Override public Iterator<T> iterator() { Iterator[] iterators = new Iterator[iterables.length]; for (int i = 0; i < iterables.length; i++) { Iterable<? extends T> iterable = iterables[i]; iterators[i] = iterable.iterator(); } return concatIterators(iterators); } }; } @NotNull @Contract(pure=true) public static <T> Iterator<T> concatIterators(@NotNull Iterator<T>... iterators) { return new SequenceIterator<T>(iterators); } @NotNull @Contract(pure=true) public static <T> Iterator<T> concatIterators(@NotNull Collection<Iterator<T>> iterators) { return new SequenceIterator<T>(iterators); } @NotNull @Contract(pure=true) public static <T> Iterable<T> concat(@NotNull final T[]... iterables) { return new Iterable<T>() { @NotNull @Override public Iterator<T> iterator() { Iterator[] iterators = new Iterator[iterables.length]; for (int i = 0; i < iterables.length; i++) { T[] iterable = iterables[i]; iterators[i] = iterate(iterable); } @SuppressWarnings("unchecked") Iterator<T> i = concatIterators(iterators); return i; } }; } /** * @return read-only list consisting of the lists added together */ @NotNull @Contract(pure=true) public static <T> List<T> concat(@NotNull final List<? extends T>... lists) { int size = 0; for (List<? extends T> each : lists) { size += each.size(); } if (size == 0) return emptyList(); final int finalSize = size; return new AbstractList<T>() { @Override public T get(final int index) { if (index >= 0 && index < finalSize) { int from = 0; for (List<? extends T> each : lists) { if (from <= index && index < from + each.size()) { return each.get(index - from); } from += each.size(); } if (from != finalSize) { throw new ConcurrentModificationException("The list has changed. Its size was " + finalSize + "; now it's " + from); } } throw new IndexOutOfBoundsException("index: " + index + "size: " + size()); } @Override public int size() { return finalSize; } }; } /** * @return read-only list consisting of the lists added together */ @NotNull @Contract(pure=true) public static <T> List<T> concat(@NotNull final List<List<? extends T>> lists) { @SuppressWarnings("unchecked") List<? extends T>[] array = lists.toArray(new List[lists.size()]); return concat(array); } /** * @return read-only list consisting of the lists (made by listGenerator) added together */ @NotNull @Contract(pure=true) public static <T, V> List<T> concat(@NotNull Iterable<? extends V> list, @NotNull Function<V, Collection<? extends T>> listGenerator) { List<T> result = new ArrayList<T>(); for (final V v : list) { result.addAll(listGenerator.fun(v)); } return result.isEmpty() ? ContainerUtil.<T>emptyList() : result; } @Contract(pure=true) public static <T> boolean intersects(@NotNull Collection<? extends T> collection1, @NotNull Collection<? extends T> collection2) { if (collection1.size() <= collection2.size()) { for (T t : collection1) { if (collection2.contains(t)) { return true; } } } else { for (T t : collection2) { if (collection1.contains(t)) { return true; } } } return false; } /** * @return read-only collection consisting of elements from both collections */ @NotNull @Contract(pure=true) public static <T> Collection<T> intersection(@NotNull Collection<? extends T> collection1, @NotNull Collection<? extends T> collection2) { List<T> result = new ArrayList<T>(); for (T t : collection1) { if (collection2.contains(t)) { result.add(t); } } return result.isEmpty() ? ContainerUtil.<T>emptyList() : result; } @NotNull @Contract(pure=true) public static <E extends Enum<E>> EnumSet<E> intersection(@NotNull EnumSet<E> collection1, @NotNull EnumSet<E> collection2) { EnumSet<E> result = EnumSet.copyOf(collection1); result.retainAll(collection2); return result; } @Nullable @Contract(pure=true) public static <T> T getFirstItem(@Nullable Collection<T> items) { return getFirstItem(items, null); } @Nullable @Contract(pure=true) public static <T> T getFirstItem(@Nullable List<T> items) { return items == null || items.isEmpty() ? null : items.get(0); } @Contract(pure=true) public static <T> T getFirstItem(@Nullable final Collection<T> items, @Nullable final T defaultResult) { return items == null || items.isEmpty() ? defaultResult : items.iterator().next(); } /** * The main difference from {@code subList} is that {@code getFirstItems} does not * throw any exceptions, even if maxItems is greater than size of the list * * @param items list * @param maxItems size of the result will be equal or less than {@code maxItems} * @param <T> type of list * @return new list with no more than {@code maxItems} first elements */ @NotNull @Contract(pure=true) public static <T> List<T> getFirstItems(@NotNull final List<T> items, int maxItems) { return items.subList(0, Math.min(maxItems, items.size())); } @Nullable @Contract(pure=true) public static <T> T iterateAndGetLastItem(@NotNull Iterable<T> items) { Iterator<T> itr = items.iterator(); T res = null; while (itr.hasNext()) { res = itr.next(); } return res; } @NotNull @Contract(pure=true) public static <T,U> Iterator<U> mapIterator(@NotNull final Iterator<T> iterator, @NotNull final Function<T,U> mapper) { return new Iterator<U>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public U next() { return mapper.fun(iterator.next()); } @Override public void remove() { iterator.remove(); } }; } /** * @return iterator with elements from the original {@param iterator} which are valid according to {@param filter} predicate. */ @NotNull @Contract(pure=true) public static <T> Iterator<T> filterIterator(@NotNull final Iterator<T> iterator, @NotNull final Condition<T> filter) { return new Iterator<T>() { T next; boolean hasNext; { findNext(); } @Override public boolean hasNext() { return hasNext; } private void findNext() { hasNext = false; while (iterator.hasNext()) { T t = iterator.next(); if (filter.value(t)) { next = t; hasNext = true; break; } } } @Override public T next() { T result; if (hasNext) { result = next; findNext(); } else { throw new NoSuchElementException(); } return result; } @Override public void remove() { iterator.remove(); } }; } @Nullable @Contract(pure=true) public static <T, L extends List<T>> T getLastItem(@Nullable L list, @Nullable T def) { return isEmpty(list) ? def : list.get(list.size() - 1); } @Nullable @Contract(pure=true) public static <T, L extends List<T>> T getLastItem(@Nullable L list) { return getLastItem(list, null); } /** * @return read-only collection consisting of elements from the 'from' collection which are absent from the 'what' collection */ @NotNull @Contract(pure=true) public static <T> Collection<T> subtract(@NotNull Collection<T> from, @NotNull Collection<T> what) { final Set<T> set = newHashSet(from); set.removeAll(what); return set.isEmpty() ? ContainerUtil.<T>emptyList() : set; } @NotNull @Contract(pure=true) public static <T> T[] toArray(@Nullable Collection<T> c, @NotNull ArrayFactory<T> factory) { return c != null ? c.toArray(factory.create(c.size())) : factory.create(0); } @NotNull @Contract(pure=true) public static <T> T[] toArray(@NotNull Collection<? extends T> c1, @NotNull Collection<? extends T> c2, @NotNull ArrayFactory<T> factory) { return ArrayUtil.mergeCollections(c1, c2, factory); } @NotNull @Contract(pure=true) public static <T> T[] mergeCollectionsToArray(@NotNull Collection<? extends T> c1, @NotNull Collection<? extends T> c2, @NotNull ArrayFactory<T> factory) { return ArrayUtil.mergeCollections(c1, c2, factory); } public static <T extends Comparable<T>> void sort(@NotNull List<T> list) { int size = list.size(); if (size < 2) return; if (size == 2) { T t0 = list.get(0); T t1 = list.get(1); if (t0.compareTo(t1) > 0) { list.set(0, t1); list.set(1, t0); } } else if (size < INSERTION_SORT_THRESHOLD) { for (int i = 0; i < size; i++) { for (int j = 0; j < i; j++) { T ti = list.get(i); T tj = list.get(j); if (ti.compareTo(tj) < 0) { list.set(i, tj); list.set(j, ti); } } } } else { Collections.sort(list); } } public static <T> void sort(@NotNull List<T> list, @NotNull Comparator<? super T> comparator) { int size = list.size(); if (size < 2) return; if (size == 2) { T t0 = list.get(0); T t1 = list.get(1); if (comparator.compare(t0, t1) > 0) { list.set(0, t1); list.set(1, t0); } } else if (size < INSERTION_SORT_THRESHOLD) { for (int i = 0; i < size; i++) { for (int j = 0; j < i; j++) { T ti = list.get(i); T tj = list.get(j); if (comparator.compare(ti, tj) < 0) { list.set(i, tj); list.set(j, ti); } } } } else { Collections.sort(list, comparator); } } public static <T extends Comparable<T>> void sort(@NotNull T[] a) { int size = a.length; if (size < 2) return; if (size == 2) { T t0 = a[0]; T t1 = a[1]; if (t0.compareTo(t1) > 0) { a[0] = t1; a[1] = t0; } } else if (size < INSERTION_SORT_THRESHOLD) { for (int i = 0; i < size; i++) { for (int j = 0; j < i; j++) { T ti = a[i]; T tj = a[j]; if (ti.compareTo(tj) < 0) { a[i] = tj; a[j] = ti; } } } } else { Arrays.sort(a); } } @NotNull @Contract(pure=true) public static <T> List<T> sorted(@NotNull Collection<T> list, @NotNull Comparator<? super T> comparator) { return sorted((Iterable<T>)list, comparator); } @NotNull @Contract(pure=true) public static <T> List<T> sorted(@NotNull Iterable<T> list, @NotNull Comparator<? super T> comparator) { List<T> sorted = newArrayList(list); sort(sorted, comparator); return sorted; } @NotNull @Contract(pure=true) public static <T extends Comparable<? super T>> List<T> sorted(@NotNull Collection<T> list) { return sorted(list, new Comparator<T>() { @Override public int compare(T o1, T o2) { return o1.compareTo(o2); } }); } public static <T> void sort(@NotNull T[] a, @NotNull Comparator<T> comparator) { int size = a.length; if (size < 2) return; if (size == 2) { T t0 = a[0]; T t1 = a[1]; if (comparator.compare(t0, t1) > 0) { a[0] = t1; a[1] = t0; } } else if (size < INSERTION_SORT_THRESHOLD) { for (int i = 0; i < size; i++) { for (int j = 0; j < i; j++) { T ti = a[i]; T tj = a[j]; if (comparator.compare(ti, tj) < 0) { a[i] = tj; a[j] = ti; } } } } else { Arrays.sort(a, comparator); } } /** * @return read-only list consisting of the elements from the iterable converted by mapping */ @NotNull @Contract(pure=true) public static <T,V> List<V> map(@NotNull Iterable<? extends T> iterable, @NotNull Function<T, V> mapping) { List<V> result = new ArrayList<V>(); for (T t : iterable) { result.add(mapping.fun(t)); } return result.isEmpty() ? ContainerUtil.<V>emptyList() : result; } /** * @return read-only list consisting of the elements from the iterable converted by mapping */ @NotNull @Contract(pure=true) public static <T,V> List<V> map(@NotNull Collection<? extends T> iterable, @NotNull Function<T, V> mapping) { return ContainerUtilRt.map2List(iterable, mapping); } /** * @return read-only list consisting of the elements from the array converted by mapping with nulls filtered out */ @NotNull @Contract(pure=true) public static <T, V> List<V> mapNotNull(@NotNull T[] array, @NotNull Function<T, V> mapping) { return mapNotNull(Arrays.asList(array), mapping); } /** * @return read-only list consisting of the elements from the array converted by mapping with nulls filtered out */ @NotNull @Contract(pure=true) public static <T, V> V[] mapNotNull(@NotNull T[] array, @NotNull Function<T, V> mapping, @NotNull V[] emptyArray) { List<V> result = new ArrayList<V>(array.length); for (T t : array) { V v = mapping.fun(t); if (v != null) { result.add(v); } } if (result.isEmpty()) { assert emptyArray.length == 0 : "You must pass an empty array"; return emptyArray; } return result.toArray(emptyArray); } /** * @return read-only list consisting of the elements from the iterable converted by mapping with nulls filtered out */ @NotNull @Contract(pure=true) public static <T, V> List<V> mapNotNull(@NotNull Iterable<? extends T> iterable, @NotNull Function<T, V> mapping) { List<V> result = new ArrayList<V>(); for (T t : iterable) { final V o = mapping.fun(t); if (o != null) { result.add(o); } } return result.isEmpty() ? ContainerUtil.<V>emptyList() : result; } /** * @return read-only list consisting of the elements from the array converted by mapping with nulls filtered out */ @NotNull @Contract(pure=true) public static <T, V> List<V> mapNotNull(@NotNull Collection<? extends T> iterable, @NotNull Function<T, V> mapping) { if (iterable.isEmpty()) { return emptyList(); } List<V> result = new ArrayList<V>(iterable.size()); for (T t : iterable) { final V o = mapping.fun(t); if (o != null) { result.add(o); } } return result.isEmpty() ? ContainerUtil.<V>emptyList() : result; } /** * @return read-only list consisting of the elements with nulls filtered out */ @NotNull @Contract(pure=true) public static <T> List<T> packNullables(@NotNull T... elements) { List<T> list = new ArrayList<T>(); for (T element : elements) { addIfNotNull(list, element); } return list.isEmpty() ? ContainerUtil.<T>emptyList() : list; } /** * @return read-only list consisting of the elements from the array converted by mapping */ @NotNull @Contract(pure=true) public static <T, V> List<V> map(@NotNull T[] array, @NotNull Function<T, V> mapping) { List<V> result = new ArrayList<V>(array.length); for (T t : array) { result.add(mapping.fun(t)); } return result.isEmpty() ? ContainerUtil.<V>emptyList() : result; } @NotNull @Contract(pure=true) public static <T, V> V[] map(@NotNull T[] arr, @NotNull Function<T, V> mapping, @NotNull V[] emptyArray) { if (arr.length==0) { assert emptyArray.length == 0 : "You must pass an empty array"; return emptyArray; } List<V> result = new ArrayList<V>(arr.length); for (T t : arr) { result.add(mapping.fun(t)); } return result.toArray(emptyArray); } @NotNull @Contract(pure=true) public static <T> Set<T> set(@NotNull T ... items) { return newHashSet(items); } public static <K, V> void putIfAbsent(final K key, @Nullable V value, @NotNull final Map<K, V> result) { if (!result.containsKey(key)) { result.put(key, value); } } public static <K, V> void putIfNotNull(final K key, @Nullable V value, @NotNull final Map<K, V> result) { if (value != null) { result.put(key, value); } } public static <K, V> void putIfNotNull(final K key, @Nullable Collection<? extends V> value, @NotNull final MultiMap<K, V> result) { if (value != null) { result.putValues(key, value); } } public static <K, V> void putIfNotNull(final K key, @Nullable V value, @NotNull final MultiMap<K, V> result) { if (value != null) { result.putValue(key, value); } } public static <T> void add(final T element, @NotNull final Collection<T> result, @NotNull final Disposable parentDisposable) { if (result.add(element)) { Disposer.register(parentDisposable, new Disposable() { @Override public void dispose() { result.remove(element); } }); } } @NotNull @Contract(pure=true) public static <T> List<T> createMaybeSingletonList(@Nullable T element) { return element == null ? ContainerUtil.<T>emptyList() : Collections.singletonList(element); } @NotNull @Contract(pure=true) public static <T> Set<T> createMaybeSingletonSet(@Nullable T element) { return element == null ? Collections.<T>emptySet() : Collections.singleton(element); } @NotNull public static <T, V> V getOrCreate(@NotNull Map<T, V> result, final T key, @NotNull V defaultValue) { V value = result.get(key); if (value == null) { result.put(key, value = defaultValue); } return value; } public static <T, V> V getOrCreate(@NotNull Map<T, V> result, final T key, @NotNull Factory<V> factory) { V value = result.get(key); if (value == null) { result.put(key, value = factory.create()); } return value; } @NotNull @Contract(pure=true) public static <T, V> V getOrElse(@NotNull Map<T, V> result, final T key, @NotNull V defValue) { V value = result.get(key); return value == null ? defValue : value; } @Contract(pure=true) public static <T> boolean and(@NotNull T[] iterable, @NotNull Condition<? super T> condition) { return and(Arrays.asList(iterable), condition); } @Contract(pure=true) public static <T> boolean and(@NotNull Iterable<T> iterable, @NotNull Condition<? super T> condition) { for (final T t : iterable) { if (!condition.value(t)) return false; } return true; } @Contract(pure=true) public static <T> boolean exists(@NotNull T[] iterable, @NotNull Condition<? super T> condition) { return or(Arrays.asList(iterable), condition); } @Contract(pure=true) public static <T> boolean exists(@NotNull Iterable<T> iterable, @NotNull Condition<? super T> condition) { return or(iterable, condition); } @Contract(pure=true) public static <T> boolean or(@NotNull T[] iterable, @NotNull Condition<? super T> condition) { return or(Arrays.asList(iterable), condition); } @Contract(pure=true) public static <T> boolean or(@NotNull Iterable<T> iterable, @NotNull Condition<? super T> condition) { for (final T t : iterable) { if (condition.value(t)) return true; } return false; } @Contract(pure=true) public static <T> int count(@NotNull Iterable<T> iterable, @NotNull Condition<? super T> condition) { int count = 0; for (final T t : iterable) { if (condition.value(t)) count++; } return count; } @NotNull @Contract(pure=true) public static <T> List<T> unfold(@Nullable T t, @NotNull NullableFunction<T, T> next) { if (t == null) return emptyList(); List<T> list = new ArrayList<T>(); while (t != null) { list.add(t); t = next.fun(t); } return list; } @NotNull @Contract(pure=true) public static <T> List<T> dropTail(@NotNull List<T> items) { return items.subList(0, items.size() - 1); } @NotNull @Contract(pure=true) public static <T> List<T> list(@NotNull T... items) { return Arrays.asList(items); } // Generalized Quick Sort. Does neither array.clone() nor list.toArray() public static <T> void quickSort(@NotNull List<T> list, @NotNull Comparator<? super T> comparator) { quickSort(list, comparator, 0, list.size()); } private static <T> void quickSort(@NotNull List<T> x, @NotNull Comparator<? super T> comparator, int off, int len) { // Insertion sort on smallest arrays if (len < 7) { for (int i = off; i < len + off; i++) { for (int j = i; j > off && comparator.compare(x.get(j), x.get(j - 1)) < 0; j--) { swapElements(x, j, j - 1); } } return; } // Choose a partition element, v int m = off + (len >> 1); // Small arrays, middle element if (len > 7) { int l = off; int n = off + len - 1; if (len > 40) { // Big arrays, pseudomedian of 9 int s = len / 8; l = med3(x, comparator, l, l + s, l + 2 * s); m = med3(x, comparator, m - s, m, m + s); n = med3(x, comparator, n - 2 * s, n - s, n); } m = med3(x, comparator, l, m, n); // Mid-size, med of 3 } T v = x.get(m); // Establish Invariant: v* (<v)* (>v)* v* int a = off; int b = a; int c = off + len - 1; int d = c; while (true) { while (b <= c && comparator.compare(x.get(b), v) <= 0) { if (comparator.compare(x.get(b), v) == 0) { swapElements(x, a++, b); } b++; } while (c >= b && comparator.compare(v, x.get(c)) <= 0) { if (comparator.compare(x.get(c), v) == 0) { swapElements(x, c, d--); } c--; } if (b > c) break; swapElements(x, b++, c--); } // Swap partition elements back to middle int n = off + len; int s = Math.min(a - off, b - a); vecswap(x, off, b - s, s); s = Math.min(d - c, n - d - 1); vecswap(x, b, n - s, s); // Recursively sort non-partition-elements if ((s = b - a) > 1) quickSort(x, comparator, off, s); if ((s = d - c) > 1) quickSort(x, comparator, n - s, s); } /* * Returns the index of the median of the three indexed longs. */ private static <T> int med3(@NotNull List<T> x, Comparator<? super T> comparator, int a, int b, int c) { return comparator.compare(x.get(a), x.get(b)) < 0 ? comparator.compare(x.get(b), x.get(c)) < 0 ? b : comparator.compare(x.get(a), x.get(c)) < 0 ? c : a : comparator.compare(x.get(c), x.get(b)) < 0 ? b : comparator.compare(x.get(c), x.get(a)) < 0 ? c : a; } /* * Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)]. */ private static <T> void vecswap(List<T> x, int a, int b, int n) { for (int i = 0; i < n; i++, a++, b++) { swapElements(x, a, b); } } /** * @return read-only set consisting of the only element o */ @NotNull @Contract(pure=true) public static <T> Set<T> singleton(final T o, @NotNull final TObjectHashingStrategy<T> strategy) { return strategy == TObjectHashingStrategy.CANONICAL ? new SingletonSet<T>(o) : SingletonSet.withCustomStrategy(o, strategy); } /** * @return read-only list consisting of the elements from all of the collections */ @NotNull @Contract(pure=true) public static <E> List<E> flatten(@NotNull Collection<E>[] collections) { return flatten(Arrays.asList(collections)); } /** * Processes the list, remove all duplicates and return the list with unique elements. * @param list must be sorted (according to the comparator), all elements must be not-null */ @NotNull public static <T> List<T> removeDuplicatesFromSorted(@NotNull List<T> list, @NotNull Comparator<? super T> comparator) { T prev = null; List<T> result = null; for (int i = 0; i < list.size(); i++) { T t = list.get(i); if (t == null) { throw new IllegalArgumentException("get(" + i + ") = null"); } int cmp = prev == null ? -1 : comparator.compare(prev, t); if (cmp < 0) { if (result != null) result.add(t); } else if (cmp == 0) { if (result == null) { result = new ArrayList<T>(list.size()); result.addAll(list.subList(0, i)); } } else { throw new IllegalArgumentException("List must be sorted but get(" + (i - 1) + ")=" + list.get(i - 1) + " > get(" + i + ")=" + t); } prev = t; } return result == null ? list : result; } /** * @return read-only list consisting of the elements from all of the collections */ @NotNull @Contract(pure=true) public static <E> List<E> flatten(@NotNull Iterable<? extends Collection<E>> collections) { List<E> result = new ArrayList<E>(); for (Collection<E> list : collections) { result.addAll(list); } return result.isEmpty() ? ContainerUtil.<E>emptyList() : result; } /** * @return read-only list consisting of the elements from all of the collections */ @NotNull @Contract(pure=true) public static <E> List<E> flattenIterables(@NotNull Iterable<? extends Iterable<E>> collections) { List<E> result = new ArrayList<E>(); for (Iterable<E> list : collections) { for (E e : list) { result.add(e); } } return result.isEmpty() ? ContainerUtil.<E>emptyList() : result; } @NotNull public static <K,V> V[] convert(@NotNull K[] from, @NotNull V[] to, @NotNull Function<K,V> fun) { if (to.length < from.length) { @SuppressWarnings("unchecked") V[] array = (V[])Array.newInstance(to.getClass().getComponentType(), from.length); to = array; } for (int i = 0; i < from.length; i++) { to[i] = fun.fun(from[i]); } return to; } @Contract(pure=true) public static <T> boolean containsIdentity(@NotNull Iterable<T> list, T element) { for (T t : list) { if (t == element) { return true; } } return false; } @Contract(pure=true) public static <T> int indexOfIdentity(@NotNull List<T> list, T element) { for (int i = 0, listSize = list.size(); i < listSize; i++) { if (list.get(i) == element) { return i; } } return -1; } @Contract(pure=true) public static <T> boolean equalsIdentity(@NotNull List<T> list1, @NotNull List<T> list2) { int listSize = list1.size(); if (list2.size() != listSize) { return false; } for (int i = 0; i < listSize; i++) { if (list1.get(i) != list2.get(i)) { return false; } } return true; } @Contract(pure=true) public static <T> int indexOf(@NotNull List<T> list, @NotNull Condition<? super T> condition) { for (int i = 0, listSize = list.size(); i < listSize; i++) { T t = list.get(i); if (condition.value(t)) { return i; } } return -1; } @Contract(pure=true) public static <T> int lastIndexOf(@NotNull List<T> list, @NotNull Condition<? super T> condition) { for (int i = list.size() - 1; i >= 0; i--) { T t = list.get(i); if (condition.value(t)) { return i; } } return -1; } @Nullable @Contract(pure = true) public static <T, U extends T> U findLastInstance(@NotNull List<T> list, @NotNull final Class<U> clazz) { int i = lastIndexOf(list, new Condition<T>() { @Override public boolean value(T t) { return clazz.isInstance(t); } }); //noinspection unchecked return i < 0 ? null : (U)list.get(i); } @Contract(pure = true) public static <T, U extends T> int lastIndexOfInstance(@NotNull List<T> list, @NotNull final Class<U> clazz) { return lastIndexOf(list, new Condition<T>() { @Override public boolean value(T t) { return clazz.isInstance(t); } }); } @Contract(pure=true) public static <T> int indexOf(@NotNull List<T> list, @NotNull final T object) { return indexOf(list, new Condition<T>() { @Override public boolean value(T t) { return t.equals(object); } }); } @NotNull @Contract(pure=true) public static <A,B> Map<B,A> reverseMap(@NotNull Map<A,B> map) { final Map<B,A> result = newHashMap(); for (Map.Entry<A, B> entry : map.entrySet()) { result.put(entry.getValue(), entry.getKey()); } return result; } @Contract("null -> null; !null -> !null") public static <T> List<T> trimToSize(@Nullable List<T> list) { if (list == null) return null; if (list.isEmpty()) return emptyList(); if (list instanceof ArrayList) { ((ArrayList)list).trimToSize(); } return list; } @NotNull @Contract(pure=true) public static <T> Stack<T> newStack() { return ContainerUtilRt.newStack(); } @NotNull @Contract(pure=true) public static <T> Stack<T> newStack(@NotNull Collection<T> initial) { return ContainerUtilRt.newStack(initial); } @NotNull @Contract(pure=true) public static <T> Stack<T> newStack(@NotNull T... initial) { return ContainerUtilRt.newStack(initial); } @NotNull @Contract(pure=true) public static <T> List<T> emptyList() { return ContainerUtilRt.emptyList(); } @NotNull @Contract(pure=true) public static <T> CopyOnWriteArrayList<T> createEmptyCOWList() { return ContainerUtilRt.createEmptyCOWList(); } /** * Creates List which is thread-safe to modify and iterate. * It differs from the java.util.concurrent.CopyOnWriteArrayList in the following: * - faster modification in the uncontended case * - less memory * - slower modification in highly contented case (which is the kind of situation you shouldn't use COWAL anyway) * * N.B. Avoid using {@code list.toArray(new T[list.size()])} on this list because it is inherently racey and * therefore can return array with null elements at the end. */ @NotNull @Contract(pure=true) public static <T> List<T> createLockFreeCopyOnWriteList() { return createConcurrentList(); } @NotNull @Contract(pure=true) public static <T> List<T> createLockFreeCopyOnWriteList(@NotNull Collection<? extends T> c) { return new LockFreeCopyOnWriteArrayList<T>(c); } @NotNull @Contract(pure=true) public static <V> ConcurrentIntObjectMap<V> createConcurrentIntObjectMap() { //noinspection deprecation return new ConcurrentIntObjectHashMap<V>(); } @NotNull @Contract(pure=true) public static <V> ConcurrentIntObjectMap<V> createConcurrentIntObjectMap(int initialCapacity, float loadFactor, int concurrencyLevel) { //noinspection deprecation return new ConcurrentIntObjectHashMap<V>(initialCapacity, loadFactor, concurrencyLevel); } @NotNull @Contract(pure=true) public static <V> ConcurrentIntObjectMap<V> createConcurrentIntObjectSoftValueMap() { //noinspection deprecation return new ConcurrentIntKeySoftValueHashMap<V>(); } @NotNull @Contract(pure=true) public static <V> ConcurrentLongObjectMap<V> createConcurrentLongObjectMap() { //noinspection deprecation return new ConcurrentLongObjectHashMap<V>(); } @NotNull @Contract(pure=true) public static <V> ConcurrentLongObjectMap<V> createConcurrentLongObjectMap(int initialCapacity) { //noinspection deprecation return new ConcurrentLongObjectHashMap<V>(initialCapacity); } @NotNull @Contract(pure=true) public static <K,V> ConcurrentMap<K,V> createConcurrentWeakValueMap() { //noinspection deprecation return new ConcurrentWeakValueHashMap<K, V>(); } @NotNull @Contract(pure=true) public static <V> ConcurrentIntObjectMap<V> createConcurrentIntObjectWeakValueMap() { //noinspection deprecation return new ConcurrentIntKeyWeakValueHashMap<V>(); } @NotNull @Contract(pure=true) public static <K,V> ConcurrentMap<K,V> createConcurrentWeakKeySoftValueMap(int initialCapacity, float loadFactor, int concurrencyLevel, @NotNull final TObjectHashingStrategy<K> hashingStrategy) { //noinspection deprecation return new ConcurrentWeakKeySoftValueHashMap<K, V>(initialCapacity, loadFactor, concurrencyLevel, hashingStrategy); } @NotNull @Contract(pure=true) public static <K,V> ConcurrentMap<K,V> createConcurrentSoftKeySoftValueMap(int initialCapacity, float loadFactor, int concurrencyLevel, @NotNull final TObjectHashingStrategy<K> hashingStrategy) { return new ConcurrentSoftKeySoftValueHashMap<K, V>(initialCapacity, loadFactor, concurrencyLevel, hashingStrategy); } @NotNull @Contract(pure=true) public static <K,V> ConcurrentMap<K,V> createConcurrentWeakKeySoftValueMap() { return createConcurrentWeakKeySoftValueMap(100, 0.75f, Runtime.getRuntime().availableProcessors(), ContainerUtil.<K>canonicalStrategy()); } @NotNull @Contract(pure=true) public static <K,V> ConcurrentMap<K,V> createConcurrentWeakKeyWeakValueMap() { return createConcurrentWeakKeyWeakValueMap(ContainerUtil.<K>canonicalStrategy()); } @NotNull @Contract(pure=true) public static <K,V> ConcurrentMap<K,V> createConcurrentWeakKeyWeakValueMap(@NotNull TObjectHashingStrategy<K> strategy) { //noinspection deprecation return new ConcurrentWeakKeyWeakValueHashMap<K, V>(100, 0.75f, Runtime.getRuntime().availableProcessors(), strategy); } @NotNull @Contract(pure = true) public static <K, V> ConcurrentMap<K,V> createConcurrentSoftValueMap() { //noinspection deprecation return new ConcurrentSoftValueHashMap<K, V>(); } @NotNull @Contract(pure=true) public static <K,V> ConcurrentMap<K,V> createConcurrentSoftMap() { //noinspection deprecation return new ConcurrentSoftHashMap<K, V>(); } @NotNull @Contract(pure=true) public static <K,V> ConcurrentMap<K,V> createConcurrentWeakMap() { //noinspection deprecation return new ConcurrentWeakHashMap<K, V>(); } @NotNull @Contract(pure=true) public static <K,V> ConcurrentMap<K,V> createConcurrentSoftMap(int initialCapacity, float loadFactor, int concurrencyLevel, @NotNull TObjectHashingStrategy<K> hashingStrategy) { //noinspection deprecation return new ConcurrentSoftHashMap<K, V>(initialCapacity, loadFactor, concurrencyLevel, hashingStrategy); } @NotNull @Contract(pure=true) public static <K,V> ConcurrentMap<K,V> createConcurrentWeakMap(int initialCapacity, float loadFactor, int concurrencyLevel, @NotNull TObjectHashingStrategy<K> hashingStrategy) { //noinspection deprecation return new ConcurrentWeakHashMap<K, V>(initialCapacity, loadFactor, concurrencyLevel, hashingStrategy); } @NotNull @Contract(pure=true) public static <K,V> ConcurrentMap<K,V> createConcurrentWeakMap(@NotNull TObjectHashingStrategy<K> hashingStrategy) { //noinspection deprecation return new ConcurrentWeakHashMap<K, V>(hashingStrategy); } /** * @see #createLockFreeCopyOnWriteList() */ @NotNull @Contract(pure=true) public static <T> ConcurrentList<T> createConcurrentList() { return new LockFreeCopyOnWriteArrayList<T>(); } @NotNull @Contract(pure=true) public static <T> ConcurrentList<T> createConcurrentList(@NotNull Collection <? extends T> collection) { return new LockFreeCopyOnWriteArrayList<T>(collection); } /** * @see #addIfNotNull(Collection, Object) instead */ @Deprecated public static <T> void addIfNotNull(@Nullable T element, @NotNull Collection<T> result) { addIfNotNull(result,element); } public static <T> void addIfNotNull(@NotNull Collection<T> result, @Nullable T element) { ContainerUtilRt.addIfNotNull(result, element); } @NotNull @Contract(pure=true) public static <T, V> List<V> map2List(@NotNull T[] array, @NotNull Function<T, V> mapper) { return ContainerUtilRt.map2List(array, mapper); } @NotNull @Contract(pure=true) public static <T, V> List<V> map2List(@NotNull Collection<? extends T> collection, @NotNull Function<T, V> mapper) { return ContainerUtilRt.map2List(collection, mapper); } @NotNull @Contract(pure=true) public static <K, V> List<Pair<K, V>> map2List(@NotNull Map<K, V> map) { return ContainerUtilRt.map2List(map); } @NotNull @Contract(pure=true) public static <T, V> Set<V> map2Set(@NotNull T[] collection, @NotNull Function<T, V> mapper) { return ContainerUtilRt.map2Set(collection, mapper); } @NotNull @Contract(pure=true) public static <T, V> Set<V> map2Set(@NotNull Collection<? extends T> collection, @NotNull Function<T, V> mapper) { return ContainerUtilRt.map2Set(collection, mapper); } @NotNull @Contract(pure=true) public static <T, V> Set<V> map2LinkedSet(@NotNull Collection<? extends T> collection, @NotNull Function<T, V> mapper) { if (collection.isEmpty()) return Collections.emptySet(); Set <V> set = new LinkedHashSet<V>(collection.size()); for (final T t : collection) { set.add(mapper.fun(t)); } return set; } @NotNull @Contract(pure=true) public static <T, V> Set<V> map2SetNotNull(@NotNull Collection<? extends T> collection, @NotNull Function<T, V> mapper) { if (collection.isEmpty()) return Collections.emptySet(); Set <V> set = new HashSet<V>(collection.size()); for (T t : collection) { V value = mapper.fun(t); if (value != null) { set.add(value); } } return set.isEmpty() ? Collections.<V>emptySet() : set; } @NotNull @Contract(pure=true) public static <T> T[] toArray(@NotNull List<T> collection, @NotNull T[] array) { return ContainerUtilRt.toArray(collection, array); } @NotNull @Contract(pure=true) public static <T> T[] toArray(@NotNull Collection<T> c, @NotNull T[] sample) { return ContainerUtilRt.toArray(c, sample); } @NotNull public static <T> T[] copyAndClear(@NotNull Collection<T> collection, @NotNull ArrayFactory<T> factory, boolean clear) { int size = collection.size(); T[] a = factory.create(size); if (size > 0) { a = collection.toArray(a); if (clear) collection.clear(); } return a; } @NotNull @Contract(pure=true) public static <T> Collection<T> toCollection(@NotNull Iterable<T> iterable) { return iterable instanceof Collection ? (Collection<T>)iterable : newArrayList(iterable); } @NotNull public static <T> List<T> toList(@NotNull Enumeration<T> enumeration) { if (!enumeration.hasMoreElements()) { return Collections.emptyList(); } List<T> result = new SmartList<T>(); while (enumeration.hasMoreElements()) { result.add(enumeration.nextElement()); } return result; } @Contract(value = "null -> true", pure = true) public static <T> boolean isEmpty(Collection<T> collection) { return collection == null || collection.isEmpty(); } @Contract(value = "null -> true", pure = true) public static boolean isEmpty(Map map) { return map == null || map.isEmpty(); } @NotNull @Contract(pure=true) public static <T> List<T> notNullize(@Nullable List<T> list) { return list == null ? ContainerUtilRt.<T>emptyList() : list; } @NotNull @Contract(pure=true) public static <T> Set<T> notNullize(@Nullable Set<T> set) { return set == null ? Collections.<T>emptySet() : set; } @NotNull @Contract(pure = true) public static <K, V> Map<K, V> notNullize(@Nullable Map<K, V> set) { return set == null ? Collections.<K, V>emptyMap() : set; } @Contract(pure = true) public static <T> boolean startsWith(@NotNull List<T> list, @NotNull List<T> prefix) { return list.size() >= prefix.size() && list.subList(0, prefix.size()).equals(prefix); } @Nullable @Contract(pure=true) public static <T, C extends Collection<T>> C nullize(@Nullable C collection) { return isEmpty(collection) ? null : collection; } @Contract(pure=true) public static <T extends Comparable<T>> int compareLexicographically(@NotNull List<T> o1, @NotNull List<T> o2) { for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { int result = Comparing.compare(o1.get(i), o2.get(i)); if (result != 0) { return result; } } return o1.size() < o2.size() ? -1 : o1.size() == o2.size() ? 0 : 1; } @Contract(pure=true) public static <T> int compareLexicographically(@NotNull List<T> o1, @NotNull List<T> o2, @NotNull Comparator<T> comparator) { for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { int result = comparator.compare(o1.get(i), o2.get(i)); if (result != 0) { return result; } } return o1.size() < o2.size() ? -1 : o1.size() == o2.size() ? 0 : 1; } /** * Returns a String representation of the given map, by listing all key-value pairs contained in the map. */ @NotNull @Contract(pure = true) public static String toString(@NotNull Map<?, ?> map) { StringBuilder sb = new StringBuilder("{"); for (Iterator<? extends Map.Entry<?, ?>> iterator = map.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<?, ?> entry = iterator.next(); sb.append(entry.getKey()).append('=').append(entry.getValue()); if (iterator.hasNext()) { sb.append(", "); } } sb.append('}'); return sb.toString(); } public static class KeyOrderedMultiMap<K, V> extends MultiMap<K, V> { public KeyOrderedMultiMap() { } public KeyOrderedMultiMap(@NotNull MultiMap<? extends K, ? extends V> toCopy) { super(toCopy); } @NotNull @Override protected Map<K, Collection<V>> createMap() { return new TreeMap<K, Collection<V>>(); } @NotNull @Override protected Map<K, Collection<V>> createMap(int initialCapacity, float loadFactor) { return new TreeMap<K, Collection<V>>(); } @NotNull public NavigableSet<K> navigableKeySet() { //noinspection unchecked return ((TreeMap)myMap).navigableKeySet(); } } @NotNull public static <K,V> Map<K,V> createWeakKeySoftValueMap() { return new WeakKeySoftValueHashMap<K, V>(); } @NotNull public static <K,V> Map<K,V> createWeakKeyWeakValueMap() { //noinspection deprecation return new WeakKeyWeakValueHashMap<K, V>(); } @NotNull public static <K,V> Map<K,V> createSoftKeySoftValueMap() { //noinspection deprecation return new SoftKeySoftValueHashMap<K, V>(); } /** * Hard keys soft values hash map. * Null keys are NOT allowed * Null values are allowed */ @NotNull public static <K,V> Map<K,V> createSoftValueMap() { //noinspection deprecation return new SoftValueHashMap<K, V>(); } /** * Hard keys weak values hash map. * Null keys are NOT allowed * Null values are allowed */ @NotNull public static <K,V> Map<K,V> createWeakValueMap() { //noinspection deprecation return new WeakValueHashMap<K, V>(); } /** * Soft keys hard values hash map. * Null keys are NOT allowed * Null values are allowed */ @NotNull public static <K,V> Map<K,V> createSoftMap() { //noinspection deprecation return new SoftHashMap<K, V>(); } @NotNull public static <K,V> Map<K,V> createSoftMap(@NotNull TObjectHashingStrategy<K> strategy) { //noinspection deprecation return new SoftHashMap<K, V>(strategy); } /** * Weak keys hard values hash map. * Null keys are NOT allowed * Null values are allowed */ @NotNull public static <K,V> Map<K,V> createWeakMap() { //noinspection deprecation return new WeakHashMap<K, V>(); } @NotNull public static <K,V> Map<K,V> createWeakMap(int initialCapacity) { //noinspection deprecation return new WeakHashMap<K, V>(initialCapacity); } @NotNull public static <K,V> Map<K,V> createWeakMap(int initialCapacity, float loadFactor, @NotNull TObjectHashingStrategy<K> strategy) { //noinspection deprecation return new WeakHashMap<K, V>(initialCapacity, loadFactor, strategy); } @NotNull public static <T> Set<T> createWeakSet() { return new WeakHashSet<T>(); } }
apache-2.0
1project1/Donate
app/src/main/java/app/project/donate/ngolocator/AlgorithmGIS.java
1999
package app.project.donate.ngolocator; /** * Created by ArupPc on 18-03-2017. */ public class AlgorithmGIS { public static PointFloating derivePos(PointFloating point, double range, double bearing) { double earthRad = 6371000;//m double latA = Math.toRadians(point.x); double lonA = Math.toRadians(point.y); double angularDistance = range / earthRad; double trueCourse = Math.toRadians(bearing); double lat = Math.asin( Math.sin(latA) * Math.cos(angularDistance) + Math.cos(latA) * Math.sin(angularDistance) * Math.cos(trueCourse)); double dlon = Math.atan2( Math.sin(trueCourse) * Math.sin(angularDistance) * Math.cos(latA), Math.cos(angularDistance) - Math.sin(latA) * Math.sin(lat)); double lon = ((lonA + dlon + Math.PI) % (Math.PI * 2)) - Math.PI; lat = Math.toDegrees(lat); lon = Math.toDegrees(lon); PointFloating newPoint = new PointFloating(lat, lon); return newPoint; } public static boolean pointIsInCircle(PointFloating pointForCheck, PointFloating center, double radius) { if (getDistanceBetweenTwoPoints(pointForCheck, center) <= radius) { return true; } return false; } public static double getDistanceBetweenTwoPoints(PointFloating p1, PointFloating p2) { double R = 6371000; // m double dLat = Math.toRadians(p2.x - p1.x); double dLon = Math.toRadians(p2.y - p1.y); double lat1 = Math.toRadians(p1.x); double lat2 = Math.toRadians(p2.x); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double d = R * c; return d; } }
apache-2.0
redoxide/ruste
de.redoxi.ruste.core/src/java/de/redoxi/ruste/core/model/ast/Function.java
3387
/* * Copyright 2013 Hayden Smith * * 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.redoxi.ruste.core.model.ast; import java.util.ArrayList; import java.util.List; /** * Representation of a function within a {@link Module} * * @see http://static.rust-lang.org/doc/master/rust.html#functions */ public class Function extends Item implements Identifiable, Scope, Visible, Generic { private String identifier; private List<GenericParam> genericParameters = new ArrayList<GenericParam>(); private List<NamedArg> args = new ArrayList<NamedArg>(); private String returnType; private int bodyStartLine, bodyStartPos, bodyEndLine, bodyEndPos; public Function(Module module) { super(module); } public String getReturnType() { return returnType; } public void setReturnType(String returnType) { this.returnType = returnType; } @Override public String toString() { StringBuilder label = new StringBuilder(); label.append(identifier); // TODO Generic parameters label.append('('); for (int i = 0; i < args.size(); ++i) { final NamedArg arg = args.get(i); label.append(arg.getIdentifier()); label.append(" : "); label.append(arg.getType()); if (i < args.size() - 1) { label.append(", "); } } label.append(')'); if (returnType != null) { label.append(" -> "); label.append(returnType); } return label.toString(); } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } @Override public boolean contains(String identifier) { // TODO Local variable declarations return getEnclosingScope() != null && getEnclosingScope().contains(identifier); } public int getBodyStartLine() { return bodyStartLine; } public void setBodyStartLine(int bodyStartLine) { this.bodyStartLine = bodyStartLine; } public int getBodyStartPos() { return bodyStartPos; } public void setBodyStartPos(int bodyStartPos) { this.bodyStartPos = bodyStartPos; } public int getBodyEndLine() { return bodyEndLine; } public void setBodyEndLine(int bodyEndLine) { this.bodyEndLine = bodyEndLine; } public int getBodyEndPos() { return bodyEndPos; } public void setBodyEndPos(int bodyEndPos) { this.bodyEndPos = bodyEndPos; } @Override public Identifiable get(String identifier) { // TODO Retrieve local variable declarations return getEnclosingScope().get(identifier); } @Override public Scope getEnclosingScope() { if (getItem() != null) { return getItem().getScope(); } return null; } public List<NamedArg> getArgs() { return args; } @Override public List<GenericParam> getGenericParameters() { return genericParameters; } }
apache-2.0
toddlipcon/helenus
src/java/com/facebook/infrastructure/utils/BloomCalculations.java
6715
/** * 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.facebook.infrastructure.utils; /** * The following calculations are taken from: * http://www.cs.wisc.edu/~cao/papers/summary-cache/node8.html * "Bloom Filters - the math" * * This class's static methods are meant to facilitate the use of the Bloom * Filter class by helping to choose correct values of 'bits per element' and * 'number of hash functions, k'. Author : Avinash Lakshman ( * alakshman@facebook.com) & Prashant Malik ( pmalik@facebook.com ) */ public class BloomCalculations { private static final int maxBits = 15; private static final int minBits = 2; private static final int minK = 1; private static final int maxK = 8; private static final int[] optKPerBits = new int[] { 1, // dummy K for 0 bits // per element 1, // dummy K for 1 bits per element 1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8 }; /** * In the following table, the row 'i' shows false positive rates if i bits * per element are used. Column 'j' shows false positive rates if j hash * functions are used. The first row is 'i=0', the first column is 'j=0'. Each * cell (i,j) the false positive rate determined by using i bits per element * and j hash functions. */ private static final double[][] probs = new double[][] { { 1.0 }, // dummy row representing 0 bits per element { 1.0, 1.0 }, // dummy row representing 1 bits per element { 1.0, 0.393, 0.400 }, { 1.0, 0.283, 0.237, 0.253 }, { 1.0, 0.221, 0.155, 0.147, 0.160 }, { 1.0, 0.181, 0.109, 0.092, 0.092, 0.101 }, { 1.0, 0.154, 0.0804, 0.0609, 0.0561, 0.0578, 0.0638 }, { 1.0, 0.133, 0.0618, 0.0423, 0.0359, 0.0347, 0.0364 }, { 1.0, 0.118, 0.0489, 0.0306, 0.024, 0.0217, 0.0216, 0.0229 }, { 1.0, 0.105, 0.0397, 0.0228, 0.0166, 0.0141, 0.0133, 0.0135, 0.0145 }, { 1.0, 0.0952, 0.0329, 0.0174, 0.0118, 0.00943, 0.00844, 0.00819, 0.00846 }, { 1.0, 0.0869, 0.0276, 0.0136, 0.00864, 0.0065, 0.00552, 0.00513, 0.00509 }, { 1.0, 0.08, 0.0236, 0.0108, 0.00646, 0.00459, 0.00371, 0.00329, 0.00314 }, { 1.0, 0.074, 0.0203, 0.00875, 0.00492, 0.00332, 0.00255, 0.00217, 0.00199 }, { 1.0, 0.0689, 0.0177, 0.00718, 0.00381, 0.00244, 0.00179, 0.00146, 0.00129 }, { 1.0, 0.0645, 0.0156, 0.00596, 0.003, 0.00183, 0.00128, 0.001, 0.000852 } }; // the // first // column // is // a // dummy // column // representing // K=0. public static double getFailureRate(int bitsPerElement) { int k = computeBestK(bitsPerElement); if (bitsPerElement >= probs.length) bitsPerElement = probs.length - 1; return probs[bitsPerElement][k]; } /** * Given the number of bits that can be used per element, return the optimal * number of hash functions in order to minimize the false positive rate. * * @param bitsPerElement * @return The number of hash functions that minimize the false positive rate. */ public static int computeBestK(int bitsPerElement) { if (bitsPerElement < 0) return optKPerBits[0]; if (bitsPerElement >= optKPerBits.length) return optKPerBits[optKPerBits.length - 1]; return optKPerBits[bitsPerElement]; } /** * A wrapper class that holds two key parameters for a Bloom Filter: the * number of hash functions used, and the number of bits per element used. */ public static class BloomSpecification { int K; // number of hash functions. int bitsPerElement; } /** * Given a maximum tolerable false positive probability, compute a Bloom * specification which will give less than the specified false positive rate, * but minimize the number of bits per element and the number of hash * functions used. Because bandwidth (and therefore total bitvector size) is * considered more expensive than computing power, preference is given to * minimizing bits per element rather than number of hash funtions. * * @param maxFalsePosProb * The maximum tolerable false positive rate. * @return A Bloom Specification which would result in a false positive rate * less than specified by the function call. */ public static BloomSpecification computeBitsAndK(double maxFalsePosProb) { BloomSpecification spec = new BloomSpecification(); spec.bitsPerElement = 2; spec.K = optKPerBits[spec.bitsPerElement]; // Handle the trivial cases: if (maxFalsePosProb >= probs[minBits][minK]) return spec; if (maxFalsePosProb < probs[maxBits][maxK]) { spec.bitsPerElement = maxBits; spec.K = maxK; return spec; } // First find the minimal required number of bits: while (probs[spec.bitsPerElement][spec.K] > maxFalsePosProb) { spec.bitsPerElement++; spec.K = optKPerBits[spec.bitsPerElement]; } // Now that the number of bits is sufficient, see if we can relax K // without losing too much precision. while (probs[spec.bitsPerElement][spec.K - 1] <= maxFalsePosProb) { spec.K--; } return spec; } }
apache-2.0
dongpf/hadoop-0.19.1
src/mapred/org/apache/hadoop/mapred/lib/LongSumReducer.java
1668
/** * 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.mapred.lib; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.io.LongWritable; /** A {@link Reducer} that sums long values. */ public class LongSumReducer<K> extends MapReduceBase implements Reducer<K, LongWritable, K, LongWritable> { public void reduce(K key, Iterator<LongWritable> values, OutputCollector<K, LongWritable> output, Reporter reporter) throws IOException { // sum all values for this key long sum = 0; while (values.hasNext()) { sum += values.next().get(); } // output sum output.collect(key, new LongWritable(sum)); } }
apache-2.0
elsam/drools-planner-old
drools-planner-benchmark/src/test/java/org/drools/planner/benchmark/core/ranking/WorstScoreSolverBenchmarkRankingComparatorTest.java
3237
/* * Copyright 2012 JBoss 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 org.drools.planner.benchmark.core.ranking; import java.util.ArrayList; import java.util.List; import org.drools.planner.benchmark.core.SingleBenchmark; import org.drools.planner.benchmark.core.SolverBenchmark; import org.junit.Test; import static org.junit.Assert.*; public class WorstScoreSolverBenchmarkRankingComparatorTest extends AbstractRankingComparatorTest { @Test public void normal() { WorstScoreSolverBenchmarkRankingComparator comparator = new WorstScoreSolverBenchmarkRankingComparator(); SolverBenchmark a = new SolverBenchmark(null); List<SingleBenchmark> aSingleBenchmarkList = new ArrayList<SingleBenchmark>(); addSingleBenchmark(aSingleBenchmarkList, -100, -30, -2001); addSingleBenchmark(aSingleBenchmarkList, -2001, -30, -2001); addSingleBenchmark(aSingleBenchmarkList, -30, -30, -2001); a.setSingleBenchmarkList(aSingleBenchmarkList); a.benchmarkingEnded(); SolverBenchmark b = new SolverBenchmark(null); List<SingleBenchmark> bSingleBenchmarkList = new ArrayList<SingleBenchmark>(); addSingleBenchmark(bSingleBenchmarkList, -900, -30, -2000); addSingleBenchmark(bSingleBenchmarkList, -2000, -30, -2000); addSingleBenchmark(bSingleBenchmarkList, -30, -30, -2000); b.setSingleBenchmarkList(bSingleBenchmarkList); b.benchmarkingEnded(); assertEquals(-1, comparator.compare(a, b)); assertEquals(1, comparator.compare(b, a)); } @Test public void worstIsEqual() { WorstScoreSolverBenchmarkRankingComparator comparator = new WorstScoreSolverBenchmarkRankingComparator(); SolverBenchmark a = new SolverBenchmark(null); List<SingleBenchmark> aSingleBenchmarkList = new ArrayList<SingleBenchmark>(); addSingleBenchmark(aSingleBenchmarkList, -101, -30, -2000); addSingleBenchmark(aSingleBenchmarkList, -2000, -30, -2000); addSingleBenchmark(aSingleBenchmarkList, -30, -30, -2000); a.setSingleBenchmarkList(aSingleBenchmarkList); a.benchmarkingEnded(); SolverBenchmark b = new SolverBenchmark(null); List<SingleBenchmark> bSingleBenchmarkList = new ArrayList<SingleBenchmark>(); addSingleBenchmark(bSingleBenchmarkList, -100, -40, -2000); addSingleBenchmark(bSingleBenchmarkList, -2000, -40, -2000); addSingleBenchmark(bSingleBenchmarkList, -40, -40, -2000); b.setSingleBenchmarkList(bSingleBenchmarkList); b.benchmarkingEnded(); assertEquals(-1, comparator.compare(a, b)); assertEquals(1, comparator.compare(b, a)); } }
apache-2.0
sbower/kuali-rice-1
core/framework/src/main/java/org/kuali/rice/core/framework/persistence/jpa/type/HibernateKualiEncryptDecryptUserType.java
3255
/* * Copyright 2007 The Kuali Foundation * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.core.framework.persistence.jpa.type; import org.hibernate.HibernateException; import org.hibernate.usertype.UserType; import org.kuali.rice.core.api.CoreApiServiceLocator; import java.security.GeneralSecurityException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; /** * Hibernate UserType to encrypt and decript data on its way to the database * * @author Kuali Rice Team (rice.collab@kuali.org) * */ public class HibernateKualiEncryptDecryptUserType extends HibernateImmutableValueUserType implements UserType { /** * Retrieves a value from the given ResultSet and decrypts it * * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, java.lang.String[], java.lang.Object) */ public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { String value = rs.getString(names[0]); String converted = null; if (value != null) { try { converted = CoreApiServiceLocator.getEncryptionService().decrypt(value); } catch (GeneralSecurityException gse) { throw new RuntimeException("Unable to decrypt value from db: " + gse.getMessage()); } if (converted == null) { converted = value; } } return converted; } /** * Encrypts the value if possible and then sets that on the PreparedStatement * * @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement, java.lang.Object, int) */ public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { String converted = null; if (value != null) { try { converted = CoreApiServiceLocator.getEncryptionService().encrypt(value); } catch (GeneralSecurityException gse) { throw new RuntimeException("Unable to encrypt value to db: " + gse.getMessage()); } } if (converted == null) { st.setNull(index, Types.VARCHAR); } else { st.setString(index, converted); } } /** * Returns String.class * * @see org.hibernate.usertype.UserType#returnedClass() */ public Class returnedClass() { return String.class; } /** * Returns an array with the SQL VARCHAR type as the single member * * @see org.hibernate.usertype.UserType#sqlTypes() */ public int[] sqlTypes() { return new int[] { Types.VARCHAR }; } }
apache-2.0
CycloneAxe/phphub-android
app/src/main/java/org/estgroup/phphub/common/adapter/NotificationItemView.java
3094
package org.estgroup.phphub.common.adapter; import android.content.Context; import android.net.Uri; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import com.ocpsoft.pretty.time.PrettyTime; import org.estgroup.phphub.R; import org.estgroup.phphub.api.entity.element.Notification; import org.estgroup.phphub.api.entity.element.Topic; import org.estgroup.phphub.api.entity.element.User; import org.estgroup.phphub.common.base.BaseAdapterItemView; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Locale; import butterknife.Bind; import static org.estgroup.phphub.common.qualifier.ClickType.CLICK_TYPE_TOPIC_CLICKED; import static org.estgroup.phphub.common.qualifier.ClickType.CLICK_TYPE_USER_CLICKED; public class NotificationItemView extends BaseAdapterItemView<Notification> { @Bind(R.id.sdv_avatar) SimpleDraweeView avatarView; @Bind(R.id.tv_msg_date) TextView msgDateView; @Bind(R.id.tv_msg_details) TextView msgDetailsView; @Bind(R.id.tv_msg_reply) TextView msgReplyView; @Bind(R.id.bga_rlyt_content) RelativeLayout topicContentView; public NotificationItemView(Context context) { super(context); } @Override public int getLayoutId() { return R.layout.message_item; } @Override public void bind(Notification notification) { String msgType = notification.getType(); User user = notification.getFromUser().getData(); Topic topic = notification.getTopic().getData(); String msgDate = user.getName(); avatarView.setImageURI(Uri.parse(user.getAvatar())); if (notification.getCreatedAt() != null) { Locale locale = getResources().getConfiguration().locale; PrettyTime prettyTime = new PrettyTime(locale); String dateStr = notification.getCreatedAt(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { String prettyTimeString = prettyTime.format(sdf.parse(dateStr)); msgDate += " • " + prettyTimeString; } catch (ParseException e) { e.printStackTrace(); } } msgDateView.setText(msgDate); msgDetailsView.setText(notification.getTypeMsg() + " : " + topic.getTitle()); if (msgType.equals("new_reply")) { msgReplyView.setText(notification.getBody()); msgReplyView.setVisibility(VISIBLE); } else { msgReplyView.setVisibility(GONE); } topicContentView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { notifyItemAction(CLICK_TYPE_TOPIC_CLICKED); } }); avatarView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { notifyItemAction(CLICK_TYPE_USER_CLICKED); } }); } }
apache-2.0
nezihyigitbasi/presto
presto-main/src/main/java/com/facebook/presto/operator/ExchangeClientConfig.java
4707
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator; import io.airlift.configuration.Config; import io.airlift.http.client.HttpClientConfig; import io.airlift.units.DataSize; import io.airlift.units.DataSize.Unit; import io.airlift.units.Duration; import io.airlift.units.MinDataSize; import io.airlift.units.MinDuration; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import java.util.concurrent.TimeUnit; public class ExchangeClientConfig { private DataSize maxBufferSize = new DataSize(32, Unit.MEGABYTE); private int concurrentRequestMultiplier = 3; private Duration minErrorDuration = new Duration(1, TimeUnit.MINUTES); private Duration maxErrorDuration = new Duration(5, TimeUnit.MINUTES); private DataSize maxResponseSize = new HttpClientConfig().getMaxContentLength(); private int clientThreads = 25; private int pageBufferClientMaxCallbackThreads = 25; private boolean acknowledgePages = true; private double responseSizeExponentialMovingAverageDecayingAlpha = 0.1; @NotNull public DataSize getMaxBufferSize() { return maxBufferSize; } @Config("exchange.max-buffer-size") public ExchangeClientConfig setMaxBufferSize(DataSize maxBufferSize) { this.maxBufferSize = maxBufferSize; return this; } @Min(1) public int getConcurrentRequestMultiplier() { return concurrentRequestMultiplier; } @Config("exchange.concurrent-request-multiplier") public ExchangeClientConfig setConcurrentRequestMultiplier(int concurrentRequestMultiplier) { this.concurrentRequestMultiplier = concurrentRequestMultiplier; return this; } @Deprecated public Duration getMinErrorDuration() { return maxErrorDuration; } @Deprecated @Config("exchange.min-error-duration") public ExchangeClientConfig setMinErrorDuration(Duration minErrorDuration) { return this; } @NotNull @MinDuration("1ms") public Duration getMaxErrorDuration() { return maxErrorDuration; } @Config("exchange.max-error-duration") public ExchangeClientConfig setMaxErrorDuration(Duration maxErrorDuration) { this.maxErrorDuration = maxErrorDuration; return this; } @NotNull @MinDataSize("1MB") public DataSize getMaxResponseSize() { return maxResponseSize; } @Config("exchange.max-response-size") public ExchangeClientConfig setMaxResponseSize(DataSize maxResponseSize) { this.maxResponseSize = maxResponseSize; return this; } @Min(1) public int getClientThreads() { return clientThreads; } @Config("exchange.client-threads") public ExchangeClientConfig setClientThreads(int clientThreads) { this.clientThreads = clientThreads; return this; } @Min(1) public int getPageBufferClientMaxCallbackThreads() { return pageBufferClientMaxCallbackThreads; } @Config("exchange.page-buffer-client.max-callback-threads") public ExchangeClientConfig setPageBufferClientMaxCallbackThreads(int pageBufferClientMaxCallbackThreads) { this.pageBufferClientMaxCallbackThreads = pageBufferClientMaxCallbackThreads; return this; } public boolean isAcknowledgePages() { return acknowledgePages; } @Config("exchange.acknowledge-pages") public ExchangeClientConfig setAcknowledgePages(boolean acknowledgePages) { this.acknowledgePages = acknowledgePages; return this; } @Config("exchange.response-size-exponential-moving-average-decaying-alpha") public ExchangeClientConfig setResponseSizeExponentialMovingAverageDecayingAlpha(double responseSizeExponentialMovingAverageDecayingAlpha) { this.responseSizeExponentialMovingAverageDecayingAlpha = responseSizeExponentialMovingAverageDecayingAlpha; return this; } public double getResponseSizeExponentialMovingAverageDecayingAlpha() { return responseSizeExponentialMovingAverageDecayingAlpha; } }
apache-2.0
xbreezes/Wordman
app/src/main/java/info/breezes/orm/utils/CursorUtils.java
2599
package info.breezes.orm.utils; import android.database.Cursor; import android.util.Log; import info.breezes.orm.OrmConfig; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by Qiao on 2014/5/27. */ public class CursorUtils { public static <T> T readCurrentEntity(Class<T> type, Cursor cursor,Map<String,Integer> columnIndex) { long st=System.currentTimeMillis(); try { T entity = type.newInstance(); Field fields[] = type.getFields(); for (Field field : fields) { String columnName = TableUtils.getColumnName(field); Class<?> fieldType = field.getType(); Object value = OrmConfig.getTranslator(fieldType).readColumnValue(cursor, columnIndex.get(columnName), field); if (value != null) { field.set(entity, value); } } Log.d("CursorUtils","readCurrentEntity cost:"+(System.currentTimeMillis()-st)); return entity; } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public static <T> List<T> readEntities(Class<T> type, Cursor cursor,Map<String,Integer> columnIndex) { ArrayList<T> arrayList = new ArrayList<T>(); while (cursor.moveToNext()) { arrayList.add(readCurrentEntity(type, cursor,columnIndex)); } return arrayList; } public static <T> T readCurrentEntity(Class<T> type, Cursor cursor) { long st=System.currentTimeMillis(); try { T entity = type.newInstance(); Field fields[] = type.getFields(); for (Field field : fields) { String columnName = TableUtils.getColumnName(field); Class<?> fieldType = field.getType(); Object value = OrmConfig.getTranslator(fieldType).readColumnValue(cursor, cursor.getColumnIndex(columnName), field); if (value != null) { field.set(entity, value); } } Log.d("CursorUtils","readCurrentEntity cost:"+(System.currentTimeMillis()-st)); return entity; } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
apache-2.0
a1vanov/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeDescriptorImpl.java
11516
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.query; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.cache.QueryIndexType; import org.apache.ignite.internal.util.tostring.GridToStringExclude; import org.apache.ignite.internal.util.tostring.GridToStringInclude; import org.apache.ignite.internal.util.typedef.internal.A; import org.apache.ignite.internal.util.typedef.internal.S; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * Descriptor of type. */ public class QueryTypeDescriptorImpl implements GridQueryTypeDescriptor { /** Cache name. */ private final String cacheName; /** */ private String name; /** */ private String tblName; /** Value field names and types with preserved order. */ @GridToStringInclude private final Map<String, Class<?>> fields = new LinkedHashMap<>(); /** */ @GridToStringExclude private final Map<String, GridQueryProperty> props = new HashMap<>(); /** Map with upper cased property names to help find properties based on SQL INSERT and MERGE queries. */ private final Map<String, GridQueryProperty> uppercaseProps = new HashMap<>(); /** Mutex for operations on indexes. */ private final Object idxMux = new Object(); /** */ @GridToStringInclude private final Map<String, QueryIndexDescriptorImpl> idxs = new HashMap<>(); /** Aliases. */ private Map<String, String> aliases; /** */ private QueryIndexDescriptorImpl fullTextIdx; /** */ private Class<?> keyCls; /** */ private Class<?> valCls; /** */ private String keyTypeName; /** */ private String valTypeName; /** */ private boolean valTextIdx; /** */ private int typeId; /** */ private String affKey; /** */ private String keyFieldName; /** */ private String valFieldName; /** Obsolete. */ private volatile boolean obsolete; /** * Constructor. * * @param cacheName Cache name. */ public QueryTypeDescriptorImpl(String cacheName) { this.cacheName = cacheName; } /** * @return Cache name. */ public String cacheName() { return cacheName; } /** {@inheritDoc} */ @Override public String name() { return name; } /** * Sets type name. * * @param name Name. */ public void name(String name) { this.name = name; } /** * Gets table name for type. * @return Table name. */ @Override public String tableName() { return tblName != null ? tblName : name; } /** * Sets table name for type. * * @param tblName Table name. */ public void tableName(String tblName) { this.tblName = tblName; } /** {@inheritDoc} */ @Override public Map<String, Class<?>> fields() { return fields; } /** {@inheritDoc} */ @Override public GridQueryProperty property(String name) { GridQueryProperty res = props.get(name); if (res == null) res = uppercaseProps.get(name.toUpperCase()); return res; } /** * @return Properties. */ public Map<String, GridQueryProperty> properties() { return props; } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public <T> T value(String field, Object key, Object val) throws IgniteCheckedException { assert field != null; GridQueryProperty prop = property(field); if (prop == null) throw new IgniteCheckedException("Failed to find field '" + field + "' in type '" + name + "'."); return (T)prop.value(key, val); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void setValue(String field, Object key, Object val, Object propVal) throws IgniteCheckedException { assert field != null; GridQueryProperty prop = property(field); if (prop == null) throw new IgniteCheckedException("Failed to find field '" + field + "' in type '" + name + "'."); prop.setValue(key, val, propVal); } /** {@inheritDoc} */ @Override public Map<String, GridQueryIndexDescriptor> indexes() { synchronized (idxMux) { return Collections.<String, GridQueryIndexDescriptor>unmodifiableMap(idxs); } } /** {@inheritDoc} */ @Override public int typeId() { return typeId; } /** * @param typeId Type ID. */ public void typeId(int typeId) { this.typeId = typeId; } /** * Get index by name. * * @param name Name. * @return Index. */ @Nullable public QueryIndexDescriptorImpl index(String name) { synchronized (idxMux) { return idxs.get(name); } } /** * @return Raw index descriptors. */ public Collection<QueryIndexDescriptorImpl> indexes0() { synchronized (idxMux) { return new ArrayList<>(idxs.values()); } } /** {@inheritDoc} */ @Override public GridQueryIndexDescriptor textIndex() { return fullTextIdx; } /** * Add index. * * @param idx Index. * @throws IgniteCheckedException If failed. */ public void addIndex(QueryIndexDescriptorImpl idx) throws IgniteCheckedException { synchronized (idxMux) { if (idxs.put(idx.name(), idx) != null) throw new IgniteCheckedException("Index with name '" + idx.name() + "' already exists."); } } /** * Drop index. * * @param idxName Index name. */ public void dropIndex(String idxName) { synchronized (idxMux) { idxs.remove(idxName); } } /** * Chedk if particular field exists. * * @param field Field. * @return {@code True} if exists. */ public boolean hasField(String field) { return props.containsKey(field) || QueryUtils.VAL_FIELD_NAME.equalsIgnoreCase(field); } /** * Adds field to text index. * * @param field Field name. * @throws IgniteCheckedException If failed. */ public void addFieldToTextIndex(String field) throws IgniteCheckedException { if (fullTextIdx == null) fullTextIdx = new QueryIndexDescriptorImpl(this, null, QueryIndexType.FULLTEXT, 0); fullTextIdx.addField(field, 0, false); } /** {@inheritDoc} */ @Override public Class<?> valueClass() { return valCls; } /** * Sets value class. * * @param valCls Value class. */ public void valueClass(Class<?> valCls) { A.notNull(valCls, "Value class must not be null"); this.valCls = valCls; } /** {@inheritDoc} */ @Override public Class<?> keyClass() { return keyCls; } /** * Set key class. * * @param keyCls Key class. */ public void keyClass(Class<?> keyCls) { this.keyCls = keyCls; } /** {@inheritDoc} */ @Override public String keyTypeName() { return keyTypeName; } /** * Set key type name. * * @param keyTypeName Key type name. */ public void keyTypeName(String keyTypeName) { this.keyTypeName = keyTypeName; } /** {@inheritDoc} */ @Override public String valueTypeName() { return valTypeName; } /** * Set value type name. * * @param valTypeName Value type name. */ public void valueTypeName(String valTypeName) { this.valTypeName = valTypeName; } /** * Adds property to the type descriptor. * * @param prop Property. * @param failOnDuplicate Fail on duplicate flag. * @throws IgniteCheckedException In case of error. */ public void addProperty(GridQueryProperty prop, boolean failOnDuplicate) throws IgniteCheckedException { String name = prop.name(); if (props.put(name, prop) != null && failOnDuplicate) throw new IgniteCheckedException("Property with name '" + name + "' already exists."); if (uppercaseProps.put(name.toUpperCase(), prop) != null && failOnDuplicate) throw new IgniteCheckedException("Property with upper cased name '" + name + "' already exists."); fields.put(name, prop.type()); } /** {@inheritDoc} */ @Override public boolean valueTextIndex() { return valTextIdx; } /** * Sets if this value should be text indexed. * * @param valTextIdx Flag value. */ public void valueTextIndex(boolean valTextIdx) { this.valTextIdx = valTextIdx; } /** {@inheritDoc} */ @Override public String affinityKey() { return affKey; } /** * @param affKey Affinity key field. */ public void affinityKey(String affKey) { this.affKey = affKey; } /** * @return Aliases. */ public Map<String, String> aliases() { return aliases != null ? aliases : Collections.<String, String>emptyMap(); } /** * @param aliases Aliases. */ public void aliases(Map<String, String> aliases) { this.aliases = aliases; } /** * @return {@code True} if obsolete. */ public boolean obsolete() { return obsolete; } /** * Mark index as obsolete. */ public void markObsolete() { obsolete = true; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(QueryTypeDescriptorImpl.class, this); } /** * Sets key field name. * @param keyFieldName Key field name. */ public void keyFieldName(String keyFieldName) { this.keyFieldName = keyFieldName; } /** {@inheritDoc} */ @Override public String keyFieldName() { return keyFieldName; } /** * Sets value field name. * @param valueFieldName value field name. */ public void valueFieldName(String valueFieldName) { this.valFieldName = valueFieldName; } /** {@inheritDoc} */ @Override public String valueFieldName() { return valFieldName; } /** {@inheritDoc} */ @Nullable @Override public String keyFieldAlias() { return keyFieldName != null ? aliases.get(keyFieldName) : null; } @Nullable @Override public String valueFieldAlias() { return valFieldName != null ? aliases.get(valFieldName) : null; } }
apache-2.0
eswdd/disco
disco-test/disco-normal-code-tests/src/test/java/uk/co/exemel/disco/tests/updatedcomponenttests/standardtesting/rpc/RPCGetNoParametersRequiredTest.java
4418
/* * Copyright 2013, The Sporting Exchange Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Originally from UpdatedComponentTests/StandardTesting/RPC/RPC_Get_NoParametersRequired.xls; package uk.co.exemel.disco.tests.updatedcomponenttests.standardtesting.rpc; import uk.co.exemel.testing.utils.disco.assertions.AssertionUtils; import uk.co.exemel.testing.utils.disco.beans.HttpCallBean; import uk.co.exemel.testing.utils.disco.beans.HttpResponseBean; import uk.co.exemel.testing.utils.disco.enums.DiscoMessageContentTypeEnum; import uk.co.exemel.testing.utils.disco.enums.DiscoMessageProtocolRequestTypeEnum; import uk.co.exemel.testing.utils.disco.enums.DiscoMessageProtocolResponseTypeEnum; import uk.co.exemel.testing.utils.disco.helpers.DiscoHelpers; import uk.co.exemel.testing.utils.disco.manager.AccessLogRequirement; import uk.co.exemel.testing.utils.disco.manager.DiscoManager; import uk.co.exemel.testing.utils.disco.manager.RequestLogRequirement; import org.testng.annotations.Test; import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; /** * Ensure that when a Batched JSON request is performed against a Disco operation that requires no parameters, the correct response is received. */ public class RPCGetNoParametersRequiredTest { @Test public void doTest() throws Exception { // Set up the Http Call Bean to make the request DiscoManager discoManager1 = DiscoManager.getInstance(); HttpCallBean callBean = discoManager1.getNewHttpCallBean("87.248.113.14"); DiscoManager discoManager = discoManager1; // Set the call bean to use JSON batching callBean.setJSONRPC(true); // Set the list of requests to make a batched call to Map[] mapArray2 = new Map[2]; mapArray2[0] = new HashMap(); mapArray2[0].put("method","testNoParams"); mapArray2[0].put("params","[]"); mapArray2[0].put("id","1"); mapArray2[1] = new HashMap(); mapArray2[1].put("method","testNoParams"); mapArray2[1].put("params","[]"); mapArray2[1].put("id","2"); callBean.setBatchedRequests(mapArray2); // Get current time for getting log entries later Timestamp timeStamp = new Timestamp(System.currentTimeMillis()); // Make JSON call to the operation requesting a JSON response discoManager.makeRestDiscoHTTPCall(callBean, DiscoMessageProtocolRequestTypeEnum.RESTJSON, DiscoMessageContentTypeEnum.JSON); // Get the response to the batched query (store the response for further comparison as order of batched responses cannot be relied on) HttpResponseBean response = callBean.getResponseObjectsByEnum(DiscoMessageProtocolResponseTypeEnum.RESTJSONJSON); // Convert the returned json object to a map for comparison DiscoHelpers discoHelpers4 = new DiscoHelpers(); Map<String, Object> map5 = discoHelpers4.convertBatchedResponseToMap(response); AssertionUtils.multiAssertEquals("{\"id\":1,\"result\":{\"status\":\"hello\",\"version\":\"1.0.0\"},\"jsonrpc\":\"2.0\"}", map5.get("response1")); AssertionUtils.multiAssertEquals("{\"id\":2,\"result\":{\"status\":\"hello\",\"version\":\"1.0.0\"},\"jsonrpc\":\"2.0\"}", map5.get("response2")); AssertionUtils.multiAssertEquals(200, map5.get("httpStatusCode")); AssertionUtils.multiAssertEquals("OK", map5.get("httpStatusText")); // Pause the test to allow the logs to be filled // generalHelpers.pauseTest(500L); // Check the log entries are as expected discoManager.verifyRequestLogEntriesAfterDate(timeStamp, new RequestLogRequirement("2.8", "testNoParams"),new RequestLogRequirement("2.8", "testNoParams") ); discoManager.verifyAccessLogEntriesAfterDate(timeStamp, new AccessLogRequirement("87.248.113.14", "/json-rpc", "Ok") ); } }
apache-2.0
arrayexpress/ae-interface
webapp/src/main/java/uk/ac/ebi/arrayexpress/servlets/GenomeSpaceUploadServlet.java
17683
package uk.ac.ebi.arrayexpress.servlets; /* * Copyright 2009-2014 European Molecular Biology 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. * */ import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.*; import org.apache.commons.lang.text.StrSubstitutor; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.arrayexpress.app.ApplicationServlet; import uk.ac.ebi.arrayexpress.components.Files; import uk.ac.ebi.arrayexpress.utils.StringTools; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GenomeSpaceUploadServlet extends ApplicationServlet { private static final long serialVersionUID = 4447436099042802322L; private transient final Logger logger = LoggerFactory.getLogger(getClass()); private final static String GS_DM_ROOT_URL = "https://dm.genomespace.org/datamanager/v1.0"; private final static String GS_HOME_DIRECTORY = "/personaldirectory"; private final static String GS_ROOT_DIRECTORY = "/file"; private final static String JSON_MIME_TYPE = "application/json"; private HttpClient httpClient; @Override public void init( ServletConfig config ) throws ServletException { super.init(config); httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); String proxyHost = System.getProperty("http.proxyHost"); String proxyPort = System.getProperty("http.proxyPort"); logger.info("Checking system properties for proxy configuration: [{}:{}]", proxyHost, proxyPort); if (null != proxyHost && null != proxyPort) { httpClient.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort)); } } @Override protected boolean canAcceptRequest( HttpServletRequest request, RequestType requestType ) { return (requestType == RequestType.GET || requestType == RequestType.POST); } @Override protected void doRequest( HttpServletRequest request, HttpServletResponse response, RequestType requestType ) throws ServletException, IOException { logRequest(logger, request, requestType); String action = request.getParameter("action"); if ("uploadFile".equals(action)) { doUploadFileAction(request, response); } else if ("checkDirectory".equals(action)) { doCheckCreateDirectoryAction(request, response, false); } else if ("createDirectory".equals(action)) { doCheckCreateDirectoryAction(request, response, true); } else { response.sendError( HttpServletResponse.SC_BAD_REQUEST , "Action [" + (null != action ? action : "<null>") + "] is not supported" ); } } private void doCheckCreateDirectoryAction( HttpServletRequest request, HttpServletResponse response, boolean shouldCreate ) throws IOException { String accession = request.getParameter("accession"); String gsToken = request.getParameter("token"); if (null == accession || null == gsToken) { response.sendError( HttpServletResponse.SC_BAD_REQUEST , "Expected parameters [accession] and [token] not found in the request" ); } else { DirectoryInfo dir = new DirectoryInfo(); Integer statusCode = getDirectoryInfo("/", dir, gsToken); if (HttpServletResponse.SC_OK != statusCode) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } String homePath = dir.getPath(); logger.debug("Located GenomeSpace user home directory path: [{}]", homePath); if (null == homePath) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (shouldCreate) { statusCode = getDirectoryInfo( homePath + "/ArrayExpress", dir, gsToken); if (HttpServletResponse.SC_NOT_FOUND == statusCode) { // let's attempt to create subdirectory "ArrayExpress" statusCode = createDirectory(homePath + "/ArrayExpress", dir, gsToken); if (HttpServletResponse.SC_OK != statusCode) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (HttpServletResponse.SC_OK != statusCode) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } String aePath = dir.getPath(); logger.debug("Located GenomeSpace AE directory path: [{}]", aePath); if (null == aePath) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } String opStatus = "exists"; statusCode = getDirectoryInfo( homePath + "/ArrayExpress/" + accession, dir, gsToken); if (HttpServletResponse.SC_NOT_FOUND == statusCode) { if (shouldCreate) { // let's attempt to create subdirectory "ArrayExpress" statusCode = createDirectory(homePath + "/ArrayExpress/" + accession, dir, gsToken); if (HttpServletResponse.SC_OK != statusCode) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } opStatus = "created"; } else { opStatus = "missing"; } } else if (HttpServletResponse.SC_OK != statusCode) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } String accessionPath = dir.getPath(); logger.debug("Located GenomeSpace target directory path for [{}]: [{}]", accession, accessionPath); response.setContentType(JSON_MIME_TYPE); try (PrintWriter out = response.getWriter()) { out.print("{\"target\":\"" + accessionPath + "\",\"status\":\"" + opStatus + "\"}"); } } } private void doUploadFileAction( HttpServletRequest request, HttpServletResponse response ) throws IOException { Files files = (Files) getComponent("Files"); String fileName = request.getParameter("filename"); String accession = request.getParameter("accession"); String targetLocation = request.getParameter("target"); String gsToken = request.getParameter("token"); if (null == fileName || null == accession || null == gsToken || null == targetLocation) { response.sendError( HttpServletResponse.SC_BAD_REQUEST , "Expected parameters [filename], [accession], [target], [token] not found in the request" ); } else { String fileLocation = files.getLocation(accession, null, fileName); File file = null != fileLocation ? new File(files.getRootFolder(), fileLocation) : null; if (null == file || !file.exists()) { logger.error("Requested file upload of [{}/{}] which is not found", accession, fileName); response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { UploadFileInfo fileInfo = new UploadFileInfo(file); Integer statusCode = getFileUploadURL(fileInfo, targetLocation, gsToken); if (HttpServletResponse.SC_OK != statusCode) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } statusCode = putFile(fileInfo); if (HttpServletResponse.SC_OK != statusCode) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } response.setContentType(JSON_MIME_TYPE); try (PrintWriter out = response.getWriter()) { out.print("{\"status\":\"copied\"}"); } logger.info("Successfully sent [{}] to [GenomeSpace:{}]", fileLocation, targetLocation); } } } private Integer getDirectoryInfo( String path, DirectoryInfo directoryInfo, String gsToken ) throws IOException { GetMethod get = new GetMethod( GS_DM_ROOT_URL + ("/".equals(path) ? GS_HOME_DIRECTORY : GS_ROOT_DIRECTORY + path) ); get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); get.setRequestHeader("Cookie","gs-token=" + gsToken); get.setRequestHeader("Accept", "application/json"); get.setRequestHeader("Content-Type", "application/json"); JSONParser jsonParser = new JSONParser(); Integer statusCode = null; try { statusCode = httpClient.executeMethod(get); if (HttpServletResponse.SC_OK == statusCode) { try (InputStream is = get.getResponseBodyAsStream()) { JSONObject dirInfo = (JSONObject) jsonParser.parse(new BufferedReader(new InputStreamReader(is))); directoryInfo.setInfo( (null != dirInfo && dirInfo.containsKey("directory")) ? (JSONObject)dirInfo.get("directory") : null ); } catch (ParseException x) { logger.error("Unable to parse JSON response:", x); } } else { logger.error("Unable to get directory info, status code [{}]", statusCode); } } catch ( HttpException x ) { logger.error("Caught an exception:", x); } finally { get.releaseConnection(); } return statusCode; } private Integer createDirectory( String path, DirectoryInfo directoryInfo, String gsToken ) throws IOException { PutMethod put = new PutMethod( GS_DM_ROOT_URL + GS_ROOT_DIRECTORY + path ); put.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); put.setRequestHeader("Cookie", "gs-token=" + gsToken); put.setRequestHeader("Accept", "application/json"); put.setRequestHeader("Content-Type", "application/json"); put.setRequestEntity(new StringRequestEntity("{\"isDirectory\":true}", JSON_MIME_TYPE, "US-ASCII")); JSONParser jsonParser = new JSONParser(); Integer statusCode = null; try { statusCode = httpClient.executeMethod(put); if (HttpServletResponse.SC_OK == statusCode) { try (InputStream is = put.getResponseBodyAsStream()) { directoryInfo.setInfo((JSONObject)jsonParser.parse(new BufferedReader(new InputStreamReader(is)))); } catch (ParseException x) { logger.error("Unable to parse JSON response:", x); } } else { logger.error("Unable create directory, status code [{}]", statusCode); } } catch ( HttpException x ) { logger.error("Caught an exception:", x); } finally { put.releaseConnection(); } return statusCode; } private Integer getFileUploadURL( UploadFileInfo fileInfo, String target, String gsToken ) throws IOException { GetMethod get = new GetMethod( GS_DM_ROOT_URL + "/uploadurl" + target.replaceAll("^/?(.+[^/])/?$", "/$1/") + fileInfo.getFile().getName() ); get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); get.setQueryString( new NameValuePair[]{ new NameValuePair("Content-Length", fileInfo.getContentLength()) , new NameValuePair("Content-Type", fileInfo.GetContentType()) , new NameValuePair("Content-MD5", fileInfo.getContentMD5()) } ); get.setRequestHeader("Cookie", "gs-token=" + gsToken); Integer statusCode = null; try { statusCode = httpClient.executeMethod(get); if (HttpServletResponse.SC_OK == statusCode) { fileInfo.setUploadURL(StringTools.streamToString(get.getResponseBodyAsStream(), "US-ASCII")); } else { logger.error("Unable to obtain upload URL, status code [{}]", statusCode); } } catch ( HttpException x ) { logger.error("Caught an exception:", x); } finally { get.releaseConnection(); } return statusCode; } private Integer putFile( UploadFileInfo fileInfo ) throws IOException { PutMethod put = new PutMethod(fileInfo.getUploadURL()); RequestEntity entity = new FileRequestEntity(fileInfo.getFile(), fileInfo.GetContentType()); put.setRequestEntity(entity); put.setRequestHeader("Content-MD5", fileInfo.getContentMD5()); Integer statusCode = null; try { statusCode = httpClient.executeMethod(put); } catch ( HttpException x ) { logger.error("Caught an exception:", x); } finally { put.releaseConnection(); } return statusCode; } private class DirectoryInfo { private JSONObject info = null; public void setInfo( JSONObject info ) { this.info = info; } public JSONObject getInfo() { return this.info; } public String getPath() { if (null != info && info.containsKey("path")) { return (String)info.get("path"); } return null; } } private class UploadFileInfo { private File file = null; private String md5 = null; private String uploadURL = null; public UploadFileInfo( File file ) { this.file = file; } public File getFile() { return this.file; } public String getContentLength() { if (null != getFile()) { return String.valueOf(getFile().length()); } return null; } public String getContentMD5() throws IOException { if (null != getFile() && null == this.md5) { String md5Command = getPreferences().getString("ae.files.get-md5-base64-encoded-command"); // put fileLocation in place of ${file} in command line Map<String, String> params = new HashMap<>(); params.put("arg.file", getFile().getPath()); StrSubstitutor sub = new StrSubstitutor(params); md5Command = sub.replace(md5Command); // execute command List<String> commandParams = new ArrayList<>(); commandParams.add("/bin/sh"); commandParams.add("-c"); commandParams.add(md5Command); logger.debug("Executing [{}]", md5Command); ProcessBuilder pb = new ProcessBuilder(commandParams); Process process = pb.start(); try (InputStream stdOut = process.getInputStream()) { this.md5 = StringTools.streamToString(stdOut, "US-ASCII").replaceAll("\\s", ""); if (0 != process.waitFor()) { this.md5 = null; } } catch (InterruptedException x) { logger.error("Process was interrupted: ", x); } } return this.md5; } public String GetContentType() { if (null != getFile()) { return getServletContext().getMimeType(getFile().getName()); } return null; } public String getUploadURL() { return this.uploadURL; } public void setUploadURL( String url ) { this.uploadURL = url; } } }
apache-2.0
engagepoint/camel
camel-core/src/main/java/org/apache/camel/util/EndpointHelper.java
17045
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.PatternSyntaxException; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.PollingConsumer; import org.apache.camel.Processor; import org.apache.camel.ResolveEndpointFailedException; import org.apache.camel.Route; import org.apache.camel.spi.BrowsableEndpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Some helper methods for working with {@link Endpoint} instances * * @version */ public final class EndpointHelper { private static final transient Logger LOG = LoggerFactory.getLogger(EndpointHelper.class); private static final AtomicLong ENDPOINT_COUNTER = new AtomicLong(0); private EndpointHelper() { //Utility Class } /** * Creates a {@link PollingConsumer} and polls all pending messages on the endpoint * and invokes the given {@link Processor} to process each {@link Exchange} and then closes * down the consumer and throws any exceptions thrown. */ public static void pollEndpoint(Endpoint endpoint, Processor processor, long timeout) throws Exception { PollingConsumer consumer = endpoint.createPollingConsumer(); try { consumer.start(); while (true) { Exchange exchange = consumer.receive(timeout); if (exchange == null) { break; } else { processor.process(exchange); } } } finally { try { consumer.stop(); } catch (Exception e) { LOG.warn("Failed to stop PollingConsumer: " + e, e); } } } /** * Creates a {@link PollingConsumer} and polls all pending messages on the * endpoint and invokes the given {@link Processor} to process each * {@link Exchange} and then closes down the consumer and throws any * exceptions thrown. */ public static void pollEndpoint(Endpoint endpoint, Processor processor) throws Exception { pollEndpoint(endpoint, processor, 1000L); } /** * Matches the endpoint with the given pattern. * <p/> * The endpoint will first resolve property placeholders using {@link CamelContext#resolvePropertyPlaceholders(String)}. * <p/> * The match rules are applied in this order: * <ul> * <li>exact match, returns true</li> * <li>wildcard match (pattern ends with a * and the uri starts with the pattern), returns true</li> * <li>regular expression match, returns true</li> * <li>otherwise returns false</li> * </ul> * * @param context the Camel context, if <tt>null</tt> then property placeholder resolution is skipped. * @param uri the endpoint uri * @param pattern a pattern to match * @return <tt>true</tt> if match, <tt>false</tt> otherwise. */ public static boolean matchEndpoint(CamelContext context, String uri, String pattern) { if (context != null) { try { uri = context.resolvePropertyPlaceholders(uri); } catch (Exception e) { throw new ResolveEndpointFailedException(uri, e); } } // normalize uri so we can do endpoint hits with minor mistakes and parameters is not in the same order try { uri = URISupport.normalizeUri(uri); } catch (Exception e) { throw new ResolveEndpointFailedException(uri, e); } // we need to test with and without scheme separators (//) if (uri.indexOf("://") != -1) { // try without :// also String scheme = ObjectHelper.before(uri, "://"); String path = ObjectHelper.after(uri, "://"); if (matchPattern(scheme + ":" + path, pattern)) { return true; } } else { // try with :// also String scheme = ObjectHelper.before(uri, ":"); String path = ObjectHelper.after(uri, ":"); if (matchPattern(scheme + "://" + path, pattern)) { return true; } } // and fallback to test with the uri as is return matchPattern(uri, pattern); } /** * Matches the endpoint with the given pattern. * @see #matchEndpoint(org.apache.camel.CamelContext, String, String) * * @deprecated use {@link #matchEndpoint(org.apache.camel.CamelContext, String, String)} instead. */ @Deprecated public static boolean matchEndpoint(String uri, String pattern) { return matchEndpoint(null, uri, pattern); } /** * Matches the name with the given pattern. * <p/> * The match rules are applied in this order: * <ul> * <li>exact match, returns true</li> * <li>wildcard match (pattern ends with a * and the name starts with the pattern), returns true</li> * <li>regular expression match, returns true</li> * <li>otherwise returns false</li> * </ul> * * @param name the name * @param pattern a pattern to match * @return <tt>true</tt> if match, <tt>false</tt> otherwise. */ public static boolean matchPattern(String name, String pattern) { if (name == null || pattern == null) { return false; } if (name.equals(pattern)) { // exact match return true; } if (matchWildcard(name, pattern)) { return true; } if (matchRegex(name, pattern)) { return true; } // no match return false; } /** * Matches the name with the given pattern. * <p/> * The match rules are applied in this order: * <ul> * <li>wildcard match (pattern ends with a * and the name starts with the pattern), returns true</li> * <li>otherwise returns false</li> * </ul> * * @param name the name * @param pattern a pattern to match * @return <tt>true</tt> if match, <tt>false</tt> otherwise. */ private static boolean matchWildcard(String name, String pattern) { // we have wildcard support in that hence you can match with: file* to match any file endpoints if (pattern.endsWith("*") && name.startsWith(pattern.substring(0, pattern.length() - 1))) { return true; } return false; } /** * Matches the name with the given pattern. * <p/> * The match rules are applied in this order: * <ul> * <li>regular expression match, returns true</li> * <li>otherwise returns false</li> * </ul> * * @param name the name * @param pattern a pattern to match * @return <tt>true</tt> if match, <tt>false</tt> otherwise. */ private static boolean matchRegex(String name, String pattern) { // match by regular expression try { if (name.matches(pattern)) { return true; } } catch (PatternSyntaxException e) { // ignore } return false; } /** * Sets the regular properties on the given bean * * @param context the camel context * @param bean the bean * @param parameters parameters * @throws Exception is thrown if setting property fails */ public static void setProperties(CamelContext context, Object bean, Map<String, Object> parameters) throws Exception { IntrospectionSupport.setProperties(context.getTypeConverter(), bean, parameters); } /** * Sets the reference properties on the given bean * <p/> * This is convention over configuration, setting all reference parameters (using {@link #isReferenceParameter(String)} * by looking it up in registry and setting it on the bean if possible. * * @param context the camel context * @param bean the bean * @param parameters parameters * @throws Exception is thrown if setting property fails */ @SuppressWarnings("unchecked") public static void setReferenceProperties(CamelContext context, Object bean, Map<String, Object> parameters) throws Exception { Iterator<Map.Entry<String, Object>> it = parameters.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); String name = entry.getKey(); Object v = entry.getValue(); String value = v != null ? v.toString() : null; if (value != null && isReferenceParameter(value)) { boolean hit = IntrospectionSupport.setProperty(context, context.getTypeConverter(), bean, name, null, value, true); if (hit) { // must remove as its a valid option and we could configure it it.remove(); } } } } /** * Is the given parameter a reference parameter (starting with a # char) * * @param parameter the parameter * @return <tt>true</tt> if its a reference parameter */ public static boolean isReferenceParameter(String parameter) { return parameter != null && parameter.trim().startsWith("#"); } /** * Resolves a reference parameter by making a lookup in the registry. * * @param <T> type of object to lookup. * @param context Camel context to use for lookup. * @param value reference parameter value. * @param type type of object to lookup. * @return lookup result. * @throws IllegalArgumentException if referenced object was not found in registry. */ public static <T> T resolveReferenceParameter(CamelContext context, String value, Class<T> type) { return resolveReferenceParameter(context, value, type, true); } /** * Resolves a reference parameter by making a lookup in the registry. * * @param <T> type of object to lookup. * @param context Camel context to use for lookup. * @param value reference parameter value. * @param type type of object to lookup. * @return lookup result (or <code>null</code> only if * <code>mandatory</code> is <code>false</code>). * @throws IllegalArgumentException if object was not found in registry and * <code>mandatory</code> is <code>true</code>. */ public static <T> T resolveReferenceParameter(CamelContext context, String value, Class<T> type, boolean mandatory) { String valueNoHash = value.replaceAll("#", ""); if (mandatory) { return CamelContextHelper.mandatoryLookup(context, valueNoHash, type); } else { return CamelContextHelper.lookup(context, valueNoHash, type); } } /** * Resolves a reference list parameter by making lookups in the registry. * The parameter value must be one of the following: * <ul> * <li>a comma-separated list of references to beans of type T</li> * <li>a single reference to a bean type T</li> * <li>a single reference to a bean of type java.util.List</li> * </ul> * * @param context Camel context to use for lookup. * @param value reference parameter value. * @param elementType result list element type. * @return list of lookup results. * @throws IllegalArgumentException if any referenced object was not found in registry. */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> List<T> resolveReferenceListParameter(CamelContext context, String value, Class<T> elementType) { if (value == null) { return Collections.emptyList(); } List<String> elements = Arrays.asList(value.split(",")); if (elements.size() == 1) { Object bean = resolveReferenceParameter(context, elements.get(0).trim(), Object.class); if (bean instanceof List) { // The bean is a list return (List) bean; } else { // The bean is a list element return Arrays.asList(elementType.cast(bean)); } } else { // more than one list element List<T> result = new ArrayList<T>(elements.size()); for (String element : elements) { result.add(resolveReferenceParameter(context, element.trim(), elementType)); } return result; } } /** * Gets the route id for the given endpoint in which there is a consumer listening. * * @param endpoint the endpoint * @return the route id, or <tt>null</tt> if none found */ public static String getRouteIdFromEndpoint(Endpoint endpoint) { if (endpoint == null || endpoint.getCamelContext() == null) { return null; } List<Route> routes = endpoint.getCamelContext().getRoutes(); for (Route route : routes) { if (route.getEndpoint().equals(endpoint) || route.getEndpoint().getEndpointKey().equals(endpoint.getEndpointKey())) { return route.getId(); } } return null; } /** * A helper method for Endpoint implementations to create new Ids for Endpoints which also implement * {@link org.apache.camel.spi.HasId} */ public static String createEndpointId() { return "endpoint" + ENDPOINT_COUNTER.incrementAndGet(); } /** * Lookup the id the given endpoint has been enlisted with in the {@link org.apache.camel.spi.Registry}. * * @param endpoint the endpoint * @return the endpoint id, or <tt>null</tt> if not found */ public static String lookupEndpointRegistryId(Endpoint endpoint) { if (endpoint == null || endpoint.getCamelContext() == null) { return null; } Map<String, Endpoint> map = endpoint.getCamelContext().getRegistry().lookupByType(Endpoint.class); for (Map.Entry<String, Endpoint> entry : map.entrySet()) { if (entry.getValue().equals(endpoint)) { return entry.getKey(); } } // not found return null; } /** * Browses the {@link BrowsableEndpoint} within the given range, and returns the messages as a XML payload. * * @param endpoint the browsable endpoint * @param fromIndex from range * @param toIndex to range * @param includeBody whether to include the message body in the XML payload * @return XML payload with the messages * @throws IllegalArgumentException if the from and to range is invalid * @see MessageHelper#dumpAsXml(org.apache.camel.Message) */ public static String browseRangeMessagesAsXml(BrowsableEndpoint endpoint, Integer fromIndex, Integer toIndex, Boolean includeBody) { if (fromIndex == null) { fromIndex = 0; } if (toIndex == null) { toIndex = Integer.MAX_VALUE; } if (fromIndex > toIndex) { throw new IllegalArgumentException("From index cannot be larger than to index, was: " + fromIndex + " > " + toIndex); } List<Exchange> exchanges = endpoint.getExchanges(); if (exchanges.size() == 0) { return null; } StringBuilder sb = new StringBuilder(); sb.append("<messages>"); for (int i = fromIndex; i < exchanges.size() && i <= toIndex; i++) { Exchange exchange = exchanges.get(i); Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn(); String xml = MessageHelper.dumpAsXml(msg, includeBody); sb.append("\n").append(xml); } sb.append("\n</messages>"); return sb.toString(); } }
apache-2.0
awsdocs/aws-doc-sdk-examples
java/example_code/redshift/CreateAndModifyClusterParameterGroup.java
6395
/** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is 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/ * * 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. */ // snippet-sourcedescription:[CreateAndModifyClusterParameterGroup demonstrates how to create and modify an Amazon Redshift parameter group.] // snippet-service:[redshift] // snippet-keyword:[Java] // snippet-sourcesyntax:[java] // snippet-keyword:[Amazon Redshift] // snippet-keyword:[Code Sample] // snippet-keyword:[CreateClusterParameterGroup] // snippet-keyword:[DescribeClusterParameterGroups] // snippet-keyword:[ModifyClusterParameterGroup] // snippet-sourcetype:[full-example] // snippet-sourcedate:[2019-02-01] // snippet-sourceauthor:[AWS] // snippet-start:[redshift.java.CreateAndModifyClusterParameterGroup.complete] package com.amazonaws.services.redshift; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.amazonaws.services.redshift.model.*; public class CreateAndModifyClusterParameterGroup { public static AmazonRedshift client; public static String clusterParameterGroupName = "parametergroup1"; public static String clusterIdentifier = "***provide a cluster identifier***"; public static String parameterGroupFamily = "redshift-1.0"; public static void main(String[] args) throws IOException { // Default client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} client = AmazonRedshiftClientBuilder.defaultClient(); try { createClusterParameterGroup(); modifyClusterParameterGroup(); associateParameterGroupWithCluster(); describeClusterParameterGroups(); } catch (Exception e) { System.err.println("Operation failed: " + e.getMessage()); } } private static void createClusterParameterGroup() { CreateClusterParameterGroupRequest request = new CreateClusterParameterGroupRequest() .withDescription("my cluster parameter group") .withParameterGroupName(clusterParameterGroupName) .withParameterGroupFamily(parameterGroupFamily); client.createClusterParameterGroup(request); System.out.println("Created cluster parameter group."); } private static void describeClusterParameterGroups() { DescribeClusterParameterGroupsResult result = client.describeClusterParameterGroups(); printResultClusterParameterGroups(result); } private static void modifyClusterParameterGroup() { List<Parameter> parameters = new ArrayList<Parameter>(); parameters.add(new Parameter() .withParameterName("extra_float_digits") .withParameterValue("2")); // Replace WLM configuration. The new configuration defines a queue (in addition to the default). parameters.add(new Parameter() .withParameterName("wlm_json_configuration") .withParameterValue("[{\"user_group\":[\"example_user_group1\"],\"query_group\":[\"example_query_group1\"],\"query_concurrency\":7},{\"query_concurrency\":5}]")); ModifyClusterParameterGroupRequest request = new ModifyClusterParameterGroupRequest() .withParameterGroupName(clusterParameterGroupName) .withParameters(parameters); client.modifyClusterParameterGroup(request); } private static void associateParameterGroupWithCluster() { ModifyClusterRequest request = new ModifyClusterRequest() .withClusterIdentifier(clusterIdentifier) .withClusterParameterGroupName(clusterParameterGroupName); Cluster result = client.modifyCluster(request); System.out.format("Parameter Group %s is used for Cluster %s\n", clusterParameterGroupName, result.getClusterParameterGroups().get(0).getParameterGroupName()); } private static void printResultClusterParameterGroups(DescribeClusterParameterGroupsResult result) { if (result == null) { System.out.println("\nDescribe cluster parameter groups result is null."); return; } System.out.println("\nPrinting parameter group results:\n"); for (ClusterParameterGroup group : result.getParameterGroups()) { System.out.format("\nDescription: %s\n", group.getDescription()); System.out.format("Group Family Name: %s\n", group.getParameterGroupFamily()); System.out.format("Group Name: %s\n", group.getParameterGroupName()); describeClusterParameters(group.getParameterGroupName()); } } private static void describeClusterParameters(String parameterGroupName) { DescribeClusterParametersRequest request = new DescribeClusterParametersRequest() .withParameterGroupName(parameterGroupName); DescribeClusterParametersResult result = client.describeClusterParameters(request); printResultClusterParameters(result, parameterGroupName); } private static void printResultClusterParameters(DescribeClusterParametersResult result, String parameterGroupName) { if (result == null) { System.out.println("\nCluster parameters is null."); return; } System.out.format("\nPrinting cluster parameters for \"%s\"\n", parameterGroupName); for (Parameter parameter : result.getParameters()) { System.out.println(" Name: " + parameter.getParameterName() + ", Value: " + parameter.getParameterValue()); System.out.println(" DataType: " + parameter.getDataType() + ", MinEngineVersion: " + parameter.getMinimumEngineVersion()); System.out.println(" AllowedValues: " + parameter.getAllowedValues() + ", Source: " + parameter.getSource()); System.out.println(" IsModifiable: " + parameter.getIsModifiable() + ", Description: " + parameter.getDescription()); } } } // snippet-end:[redshift.java.CreateAndModifyClusterParameterGroup.complete]
apache-2.0
HaStr/kieker
kieker-common/test-gen/kieker/test/common/junit/record/jvm/TestGeneratedClassLoadingRecord.java
9593
/*************************************************************************** * Copyright 2015 Kieker Project (http://kieker-monitoring.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ package kieker.test.common.junit.record.jvm; import java.nio.ByteBuffer; import org.junit.Assert; import org.junit.Test; import kieker.common.record.jvm.ClassLoadingRecord; import kieker.common.util.registry.IRegistry; import kieker.common.util.registry.Registry; import kieker.test.common.junit.AbstractGeneratedKiekerTest; import kieker.test.common.util.record.BookstoreOperationExecutionRecordFactory; /** * Creates {@link OperationExecutionRecord}s via the available constructors and * checks the values passed values via getters. * * @author Kieker Build * * @since 1.10 */ public class TestGeneratedClassLoadingRecord extends AbstractGeneratedKiekerTest { public TestGeneratedClassLoadingRecord() { // empty default constructor } /** * Tests {@link ClassLoadingRecord#TestClassLoadingRecord(String, String, long, long, long, String, int, int)}. */ @Test public void testToArray() { // NOPMD (assert missing) for (int i=0;i<ARRAY_LENGTH;i++) { // initialize ClassLoadingRecord record = new ClassLoadingRecord(LONG_VALUES.get(i % LONG_VALUES.size()), STRING_VALUES.get(i % STRING_VALUES.size()), STRING_VALUES.get(i % STRING_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()), INT_VALUES.get(i % INT_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size())); // check values Assert.assertEquals("ClassLoadingRecord.timestamp values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTimestamp()); Assert.assertEquals("ClassLoadingRecord.hostname values are not equal.", STRING_VALUES.get(i % STRING_VALUES.size()) == null?"":STRING_VALUES.get(i % STRING_VALUES.size()), record.getHostname()); Assert.assertEquals("ClassLoadingRecord.vmName values are not equal.", STRING_VALUES.get(i % STRING_VALUES.size()) == null?"":STRING_VALUES.get(i % STRING_VALUES.size()), record.getVmName()); Assert.assertEquals("ClassLoadingRecord.totalLoadedClassCount values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTotalLoadedClassCount()); Assert.assertEquals("ClassLoadingRecord.loadedClassCount values are not equal.", (int) INT_VALUES.get(i % INT_VALUES.size()), record.getLoadedClassCount()); Assert.assertEquals("ClassLoadingRecord.unloadedClassCount values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getUnloadedClassCount()); Object[] values = record.toArray(); Assert.assertNotNull("Record array serialization failed. No values array returned.", values); Assert.assertEquals("Record array size does not match expected number of properties 6.", 6, values.length); // check all object values exist Assert.assertNotNull("Array value [0] of type Long must be not null.", values[0]); Assert.assertNotNull("Array value [1] of type String must be not null.", values[1]); Assert.assertNotNull("Array value [2] of type String must be not null.", values[2]); Assert.assertNotNull("Array value [3] of type Long must be not null.", values[3]); Assert.assertNotNull("Array value [4] of type Integer must be not null.", values[4]); Assert.assertNotNull("Array value [5] of type Long must be not null.", values[5]); // check all types Assert.assertTrue("Type of array value [0] " + values[0].getClass().getCanonicalName() + " does not match the desired type Long", values[0] instanceof Long); Assert.assertTrue("Type of array value [1] " + values[1].getClass().getCanonicalName() + " does not match the desired type String", values[1] instanceof String); Assert.assertTrue("Type of array value [2] " + values[2].getClass().getCanonicalName() + " does not match the desired type String", values[2] instanceof String); Assert.assertTrue("Type of array value [3] " + values[3].getClass().getCanonicalName() + " does not match the desired type Long", values[3] instanceof Long); Assert.assertTrue("Type of array value [4] " + values[4].getClass().getCanonicalName() + " does not match the desired type Integer", values[4] instanceof Integer); Assert.assertTrue("Type of array value [5] " + values[5].getClass().getCanonicalName() + " does not match the desired type Long", values[5] instanceof Long); // check all object values Assert.assertEquals("Array value [0] " + values[0] + " does not match the desired value " + LONG_VALUES.get(i % LONG_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()), values[0] ); Assert.assertEquals("Array value [1] " + values[1] + " does not match the desired value " + STRING_VALUES.get(i % STRING_VALUES.size()), STRING_VALUES.get(i % STRING_VALUES.size()) == null?"":STRING_VALUES.get(i % STRING_VALUES.size()), values[1] ); Assert.assertEquals("Array value [2] " + values[2] + " does not match the desired value " + STRING_VALUES.get(i % STRING_VALUES.size()), STRING_VALUES.get(i % STRING_VALUES.size()) == null?"":STRING_VALUES.get(i % STRING_VALUES.size()), values[2] ); Assert.assertEquals("Array value [3] " + values[3] + " does not match the desired value " + LONG_VALUES.get(i % LONG_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()), values[3] ); Assert.assertEquals("Array value [4] " + values[4] + " does not match the desired value " + INT_VALUES.get(i % INT_VALUES.size()), INT_VALUES.get(i % INT_VALUES.size()), values[4] ); Assert.assertEquals("Array value [5] " + values[5] + " does not match the desired value " + LONG_VALUES.get(i % LONG_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()), values[5] ); } } /** * Tests {@link ClassLoadingRecord#TestClassLoadingRecord(String, String, long, long, long, String, int, int)}. */ @Test public void testBuffer() { // NOPMD (assert missing) for (int i=0;i<ARRAY_LENGTH;i++) { // initialize ClassLoadingRecord record = new ClassLoadingRecord(LONG_VALUES.get(i % LONG_VALUES.size()), STRING_VALUES.get(i % STRING_VALUES.size()), STRING_VALUES.get(i % STRING_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()), INT_VALUES.get(i % INT_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size())); // check values Assert.assertEquals("ClassLoadingRecord.timestamp values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTimestamp()); Assert.assertEquals("ClassLoadingRecord.hostname values are not equal.", STRING_VALUES.get(i % STRING_VALUES.size()) == null?"":STRING_VALUES.get(i % STRING_VALUES.size()), record.getHostname()); Assert.assertEquals("ClassLoadingRecord.vmName values are not equal.", STRING_VALUES.get(i % STRING_VALUES.size()) == null?"":STRING_VALUES.get(i % STRING_VALUES.size()), record.getVmName()); Assert.assertEquals("ClassLoadingRecord.totalLoadedClassCount values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTotalLoadedClassCount()); Assert.assertEquals("ClassLoadingRecord.loadedClassCount values are not equal.", (int) INT_VALUES.get(i % INT_VALUES.size()), record.getLoadedClassCount()); Assert.assertEquals("ClassLoadingRecord.unloadedClassCount values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getUnloadedClassCount()); } } /** * Tests {@link ClassLoadingRecord#TestClassLoadingRecord(String, String, long, long, long, String, int, int)}. */ @Test public void testParameterConstruction() { // NOPMD (assert missing) for (int i=0;i<ARRAY_LENGTH;i++) { // initialize ClassLoadingRecord record = new ClassLoadingRecord(LONG_VALUES.get(i % LONG_VALUES.size()), STRING_VALUES.get(i % STRING_VALUES.size()), STRING_VALUES.get(i % STRING_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()), INT_VALUES.get(i % INT_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size())); // check values Assert.assertEquals("ClassLoadingRecord.timestamp values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTimestamp()); Assert.assertEquals("ClassLoadingRecord.hostname values are not equal.", STRING_VALUES.get(i % STRING_VALUES.size()) == null?"":STRING_VALUES.get(i % STRING_VALUES.size()), record.getHostname()); Assert.assertEquals("ClassLoadingRecord.vmName values are not equal.", STRING_VALUES.get(i % STRING_VALUES.size()) == null?"":STRING_VALUES.get(i % STRING_VALUES.size()), record.getVmName()); Assert.assertEquals("ClassLoadingRecord.totalLoadedClassCount values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTotalLoadedClassCount()); Assert.assertEquals("ClassLoadingRecord.loadedClassCount values are not equal.", (int) INT_VALUES.get(i % INT_VALUES.size()), record.getLoadedClassCount()); Assert.assertEquals("ClassLoadingRecord.unloadedClassCount values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getUnloadedClassCount()); } } }
apache-2.0
scranton/camel
platforms/spring-boot/components-starter/camel-mvel-starter/src/main/java/org/apache/camel/language/mvel/springboot/MvelLanguageConfiguration.java
1547
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.language.mvel.springboot; import javax.annotation.Generated; import org.springframework.boot.context.properties.ConfigurationProperties; /** * For MVEL expressions and predicates * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo") @ConfigurationProperties(prefix = "camel.language.mvel") public class MvelLanguageConfiguration { /** * Whether to trim the value to remove leading and trailing whitespaces and * line breaks */ private Boolean trim = true; public Boolean getTrim() { return trim; } public void setTrim(Boolean trim) { this.trim = trim; } }
apache-2.0
AsuraTeam/monitor
server/src/main/java/com/asura/monitor/configure/entity/MonitorIndexAlarmEntity.java
16956
package com.asura.monitor.configure.entity; import com.asura.framework.base.entity.BaseEntity; /** * <p></p> * <p/> * <PRE> * <BR> * <BR>----------------------------------------------- * <BR> * </PRE> * * @author zhaozq14 * @version 1.0 * @date 2016-11-18 08:59:10 * @since 1.0 */ public class MonitorIndexAlarmEntity extends BaseEntity{ private String indexName; private String ipAddress; private boolean sendAlarm; private String sendMessages; private boolean isConfigure; private String allGroups; private String alarmCount; private String alarmInterval; public String getAlarmInterval() { return alarmInterval; } public void setAlarmInterval(String alarmInterval) { this.alarmInterval = alarmInterval; } public String getAlarmCount() { return alarmCount; } public void setAlarmCount(String alarmCount) { this.alarmCount = alarmCount; } public String getAllGroups() { return allGroups; } public void setAllGroups(String allGroups) { this.allGroups = allGroups; } public boolean getIsConfigure() { return isConfigure; } public void setIsConfigure(boolean noConfigure) { isConfigure = noConfigure; } public String getSendMessages() { return sendMessages; } public void setSendMessages(String sendMessages) { this.sendMessages = sendMessages; } public boolean getSendAlarm() { return sendAlarm; } public void setSendAlarm(boolean sendAlarm) { this.sendAlarm = sendAlarm; } public String getIndexName() { return indexName; } public void setIndexName(String indexName) { this.indexName = indexName; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } /** * This field corresponds to the database column monitor_index_alarm.index_id * Comment: 参考指标表id * @param indexId the value for monitor_index_alarm.index_id */ private java.lang.Integer indexId; /** * This field corresponds to the database column monitor_index_alarm.server_id * Comment: 参考cmdb的表server_id * @param serverId the value for monitor_index_alarm.server_id */ private java.lang.Integer serverId; /** * This field corresponds to the database column monitor_index_alarm.gt_value * Comment: * @param gtValue the value for monitor_index_alarm.gt_value */ private java.lang.String gtValue; /** * This field corresponds to the database column monitor_index_alarm.lt_value * Comment: * @param ltValue the value for monitor_index_alarm.lt_value */ private java.lang.String ltValue; /** * This field corresponds to the database column monitor_index_alarm.eq_value * Comment: * @param eqValue the value for monitor_index_alarm.eq_value */ private java.lang.String eqValue; /** * This field corresponds to the database column monitor_index_alarm.last_modify_time * Comment: 最近修改时间 * @param lastModifyTime the value for monitor_index_alarm.last_modify_time */ private java.sql.Timestamp lastModifyTime; /** * This field corresponds to the database column monitor_index_alarm.last_modify_user * Comment: 最近修改用户 * @param lastModifyUser the value for monitor_index_alarm.last_modify_user */ private java.lang.String lastModifyUser; /** * This field corresponds to the database column monitor_index_alarm.status_id * Comment: 条件达成后报警级别 * @param statusId the value for monitor_index_alarm.status_id */ private java.lang.Integer statusId; /** * This field corresponds to the database column monitor_index_alarm.weixin_groups * Comment: 微信组 * @param weixinGroups the value for monitor_index_alarm.weixin_groups */ private java.lang.String weixinGroups; /** * This field corresponds to the database column monitor_index_alarm.ding_groups * Comment: * @param dingGroups the value for monitor_index_alarm.ding_groups */ private java.lang.String dingGroups; /** * This field corresponds to the database column monitor_index_alarm.mobile_groups * Comment: * @param mobileGroups the value for monitor_index_alarm.mobile_groups */ private java.lang.String mobileGroups; /** * This field corresponds to the database column monitor_index_alarm.email_groups * Comment: * @param emailGroups the value for monitor_index_alarm.email_groups */ private java.lang.String emailGroups; /** * This field corresponds to the database column monitor_index_alarm.alarm_id * Comment: * @param alarmId the value for monitor_index_alarm.alarm_id */ private java.lang.Integer alarmId; /** * This field corresponds to the database column monitor_index_alarm.is_mobile * Comment: * @param isMobile the value for monitor_index_alarm.is_mobile */ private java.lang.Integer isMobile; /** * This field corresponds to the database column monitor_index_alarm.is_email * Comment: * @param isEmail the value for monitor_index_alarm.is_email */ private java.lang.Integer isEmail; /** * This field corresponds to the database column monitor_index_alarm.is_ding * Comment: * @param isDing the value for monitor_index_alarm.is_ding */ private java.lang.Integer isDing; /** * This field corresponds to the database column monitor_index_alarm.is_weixin * Comment: * @param isWeixin the value for monitor_index_alarm.is_weixin */ private java.lang.Integer isWeixin; /** * This field corresponds to the database column monitor_index_alarm.is_alarm * Comment: * @param isAlarm the value for monitor_index_alarm.is_alarm */ private java.lang.Integer isAlarm; /** * This field corresponds to the database column monitor_index_alarm.not_eq_value * Comment: * @param notEqValue the value for monitor_index_alarm.not_eq_value */ private java.lang.String notEqValue; /** * This field corresponds to the database column monitor_index_alarm.index_id * Comment: 参考指标表id * @param indexId the value for monitor_index_alarm.index_id */ public void setIndexId(java.lang.Integer indexId){ this.indexId = indexId; } /** * This field corresponds to the database column monitor_index_alarm.server_id * Comment: 参考cmdb的表server_id * @param serverId the value for monitor_index_alarm.server_id */ public void setServerId(java.lang.Integer serverId){ this.serverId = serverId; } /** * This field corresponds to the database column monitor_index_alarm.gt_value * Comment: * @param gtValue the value for monitor_index_alarm.gt_value */ public void setGtValue(java.lang.String gtValue){ this.gtValue = gtValue; } /** * This field corresponds to the database column monitor_index_alarm.lt_value * Comment: * @param ltValue the value for monitor_index_alarm.lt_value */ public void setLtValue(java.lang.String ltValue){ this.ltValue = ltValue; } /** * This field corresponds to the database column monitor_index_alarm.eq_value * Comment: * @param eqValue the value for monitor_index_alarm.eq_value */ public void setEqValue(java.lang.String eqValue){ this.eqValue = eqValue; } /** * This field corresponds to the database column monitor_index_alarm.last_modify_time * Comment: 最近修改时间 * @param lastModifyTime the value for monitor_index_alarm.last_modify_time */ public void setLastModifyTime(java.sql.Timestamp lastModifyTime){ this.lastModifyTime = lastModifyTime; } /** * This field corresponds to the database column monitor_index_alarm.last_modify_user * Comment: 最近修改用户 * @param lastModifyUser the value for monitor_index_alarm.last_modify_user */ public void setLastModifyUser(java.lang.String lastModifyUser){ this.lastModifyUser = lastModifyUser; } /** * This field corresponds to the database column monitor_index_alarm.status_id * Comment: 条件达成后报警级别 * @param statusId the value for monitor_index_alarm.status_id */ public void setStatusId(java.lang.Integer statusId){ this.statusId = statusId; } /** * This field corresponds to the database column monitor_index_alarm.weixin_groups * Comment: 微信组 * @param weixinGroups the value for monitor_index_alarm.weixin_groups */ public void setWeixinGroups(java.lang.String weixinGroups){ this.weixinGroups = weixinGroups; } /** * This field corresponds to the database column monitor_index_alarm.ding_groups * Comment: * @param dingGroups the value for monitor_index_alarm.ding_groups */ public void setDingGroups(java.lang.String dingGroups){ this.dingGroups = dingGroups; } /** * This field corresponds to the database column monitor_index_alarm.mobile_groups * Comment: * @param mobileGroups the value for monitor_index_alarm.mobile_groups */ public void setMobileGroups(java.lang.String mobileGroups){ this.mobileGroups = mobileGroups; } /** * This field corresponds to the database column monitor_index_alarm.email_groups * Comment: * @param emailGroups the value for monitor_index_alarm.email_groups */ public void setEmailGroups(java.lang.String emailGroups){ this.emailGroups = emailGroups; } /** * This field corresponds to the database column monitor_index_alarm.alarm_id * Comment: * @param alarmId the value for monitor_index_alarm.alarm_id */ public void setAlarmId(java.lang.Integer alarmId){ this.alarmId = alarmId; } /** * This field corresponds to the database column monitor_index_alarm.is_mobile * Comment: * @param isMobile the value for monitor_index_alarm.is_mobile */ public void setIsMobile(java.lang.Integer isMobile){ this.isMobile = isMobile; } /** * This field corresponds to the database column monitor_index_alarm.is_email * Comment: * @param isEmail the value for monitor_index_alarm.is_email */ public void setIsEmail(java.lang.Integer isEmail){ this.isEmail = isEmail; } /** * This field corresponds to the database column monitor_index_alarm.is_ding * Comment: * @param isDing the value for monitor_index_alarm.is_ding */ public void setIsDing(java.lang.Integer isDing){ this.isDing = isDing; } /** * This field corresponds to the database column monitor_index_alarm.is_weixin * Comment: * @param isWeixin the value for monitor_index_alarm.is_weixin */ public void setIsWeixin(java.lang.Integer isWeixin){ this.isWeixin = isWeixin; } /** * This field corresponds to the database column monitor_index_alarm.is_alarm * Comment: * @param isAlarm the value for monitor_index_alarm.is_alarm */ public void setIsAlarm(java.lang.Integer isAlarm){ this.isAlarm = isAlarm; } /** * This field corresponds to the database column monitor_index_alarm.not_eq_value * Comment: * @param notEqValue the value for monitor_index_alarm.not_eq_value */ public void setNotEqValue(java.lang.String notEqValue){ this.notEqValue = notEqValue; } /** * This field corresponds to the database column monitor_index_alarm.index_id * Comment: 参考指标表id * @return the value of monitor_index_alarm.index_id */ public java.lang.Integer getIndexId() { return indexId; } /** * This field corresponds to the database column monitor_index_alarm.server_id * Comment: 参考cmdb的表server_id * @return the value of monitor_index_alarm.server_id */ public java.lang.Integer getServerId() { return serverId; } /** * This field corresponds to the database column monitor_index_alarm.gt_value * Comment: * @return the value of monitor_index_alarm.gt_value */ public java.lang.String getGtValue() { return gtValue; } /** * This field corresponds to the database column monitor_index_alarm.lt_value * Comment: * @return the value of monitor_index_alarm.lt_value */ public java.lang.String getLtValue() { return ltValue; } /** * This field corresponds to the database column monitor_index_alarm.eq_value * Comment: * @return the value of monitor_index_alarm.eq_value */ public java.lang.String getEqValue() { return eqValue; } /** * This field corresponds to the database column monitor_index_alarm.last_modify_time * Comment: 最近修改时间 * @return the value of monitor_index_alarm.last_modify_time */ public java.sql.Timestamp getLastModifyTime() { return lastModifyTime; } /** * This field corresponds to the database column monitor_index_alarm.last_modify_user * Comment: 最近修改用户 * @return the value of monitor_index_alarm.last_modify_user */ public java.lang.String getLastModifyUser() { return lastModifyUser; } /** * This field corresponds to the database column monitor_index_alarm.status_id * Comment: 条件达成后报警级别 * @return the value of monitor_index_alarm.status_id */ public java.lang.Integer getStatusId() { return statusId; } /** * This field corresponds to the database column monitor_index_alarm.weixin_groups * Comment: 微信组 * @return the value of monitor_index_alarm.weixin_groups */ public java.lang.String getWeixinGroups() { return weixinGroups; } /** * This field corresponds to the database column monitor_index_alarm.ding_groups * Comment: * @return the value of monitor_index_alarm.ding_groups */ public java.lang.String getDingGroups() { return dingGroups; } /** * This field corresponds to the database column monitor_index_alarm.mobile_groups * Comment: * @return the value of monitor_index_alarm.mobile_groups */ public java.lang.String getMobileGroups() { return mobileGroups; } /** * This field corresponds to the database column monitor_index_alarm.email_groups * Comment: * @return the value of monitor_index_alarm.email_groups */ public java.lang.String getEmailGroups() { return emailGroups; } /** * This field corresponds to the database column monitor_index_alarm.alarm_id * Comment: * @return the value of monitor_index_alarm.alarm_id */ public java.lang.Integer getAlarmId() { return alarmId; } /** * This field corresponds to the database column monitor_index_alarm.is_mobile * Comment: * @return the value of monitor_index_alarm.is_mobile */ public java.lang.Integer getIsMobile() { return isMobile; } /** * This field corresponds to the database column monitor_index_alarm.is_email * Comment: * @return the value of monitor_index_alarm.is_email */ public java.lang.Integer getIsEmail() { return isEmail; } /** * This field corresponds to the database column monitor_index_alarm.is_ding * Comment: * @return the value of monitor_index_alarm.is_ding */ public java.lang.Integer getIsDing() { return isDing; } /** * This field corresponds to the database column monitor_index_alarm.is_weixin * Comment: * @return the value of monitor_index_alarm.is_weixin */ public java.lang.Integer getIsWeixin() { return isWeixin; } /** * This field corresponds to the database column monitor_index_alarm.is_alarm * Comment: * @return the value of monitor_index_alarm.is_alarm */ public java.lang.Integer getIsAlarm() { return isAlarm; } /** * This field corresponds to the database column monitor_index_alarm.not_eq_value * Comment: * @return the value of monitor_index_alarm.not_eq_value */ public java.lang.String getNotEqValue() { return notEqValue; } }
apache-2.0
dkhwangbo/druid
server/src/main/java/org/apache/druid/server/log/FileRequestLogger.java
4401
/* * 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.druid.server.log; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Throwables; import org.apache.druid.java.util.common.DateTimes; import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.java.util.common.concurrent.ScheduledExecutors; import org.apache.druid.java.util.common.guava.CloseQuietly; import org.apache.druid.java.util.common.lifecycle.LifecycleStart; import org.apache.druid.java.util.common.lifecycle.LifecycleStop; import org.apache.druid.server.RequestLogLine; import org.joda.time.DateTime; import org.joda.time.Duration; import org.joda.time.MutableDateTime; import org.joda.time.chrono.ISOChronology; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledExecutorService; /** */ public class FileRequestLogger implements RequestLogger { private final ObjectMapper objectMapper; private final ScheduledExecutorService exec; private final File baseDir; private final Object lock = new Object(); private DateTime currentDay; private OutputStreamWriter fileWriter; public FileRequestLogger(ObjectMapper objectMapper, ScheduledExecutorService exec, File baseDir) { this.exec = exec; this.objectMapper = objectMapper; this.baseDir = baseDir; } @LifecycleStart @Override public void start() throws Exception { try { baseDir.mkdirs(); MutableDateTime mutableDateTime = DateTimes.nowUtc().toMutableDateTime(ISOChronology.getInstanceUTC()); mutableDateTime.setMillisOfDay(0); synchronized (lock) { currentDay = mutableDateTime.toDateTime(ISOChronology.getInstanceUTC()); fileWriter = getFileWriter(); } long nextDay = currentDay.plusDays(1).getMillis(); Duration initialDelay = new Duration(nextDay - System.currentTimeMillis()); ScheduledExecutors.scheduleWithFixedDelay( exec, initialDelay, Duration.standardDays(1), new Callable<ScheduledExecutors.Signal>() { @Override public ScheduledExecutors.Signal call() { try { synchronized (lock) { currentDay = currentDay.plusDays(1); CloseQuietly.close(fileWriter); fileWriter = getFileWriter(); } } catch (Exception e) { Throwables.propagate(e); } return ScheduledExecutors.Signal.REPEAT; } } ); } catch (IOException e) { Throwables.propagate(e); } } private OutputStreamWriter getFileWriter() throws FileNotFoundException { return new OutputStreamWriter( new FileOutputStream(new File(baseDir, currentDay.toString("yyyy-MM-dd'.log'")), true), StandardCharsets.UTF_8 ); } @LifecycleStop @Override public void stop() { synchronized (lock) { CloseQuietly.close(fileWriter); } } @Override public void log(RequestLogLine requestLogLine) throws IOException { synchronized (lock) { fileWriter.write( StringUtils.format("%s%n", requestLogLine.getLine(objectMapper)) ); fileWriter.flush(); } } @Override public String toString() { return "FileRequestLogger{" + "baseDir=" + baseDir + '}'; } }
apache-2.0
coolBlee/EasyNote
app/src/main/java/com/coolblee/easynote/editor/EditActivity.java
4442
package com.coolblee.easynote.editor; import android.app.LoaderManager; import android.content.ContentUris; import android.content.ContentValues; import android.content.Loader; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import com.coolblee.coolblibrary.activity.BaseActivity; import com.coolblee.easynote.R; import com.coolblee.easynote.main.NotesLoader; import com.coolblee.easynote.provider.EasyNote.Notes; import com.coolblee.easynote.util.PageJumper; public class EditActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<Cursor> { private static final int NOTES_LOADER_ID = 428; private static final int STATE_CREAT_NEW = 1; private static final int STATE_EDIT = 2; private int mState = STATE_CREAT_NEW; private Uri mUri; private EditText mTileEditText, mContentEditText; private TypedArray mBgColors; private int mChoosedColor; @Override protected void initVariables(Bundle savedInstanceState) { mBgColors = this.getResources().obtainTypedArray(R.array.bg_colors); mChoosedColor = mBgColors.getColor(0, Color.WHITE); final long noteId = getIntent().getLongExtra(PageJumper.EXTRA_NOTE_ID, -1); if (noteId <= 0) { //create new note mode mState = STATE_CREAT_NEW; mUri = Notes.CONTENT_URI; } else { //edit a exists note mState = STATE_EDIT; mUri = ContentUris.withAppendedId(Notes.CONTENT_URI, noteId); } } @Override protected void initViews(Bundle savedInstanceState) { setContentView(R.layout.activity_edit); ActionBar actionBar = getSupportActionBar(); if (null != actionBar) { actionBar.setDisplayHomeAsUpEnabled(true); } mTileEditText = (EditText) this.findViewById(R.id.note_title); mContentEditText = (EditText) this.findViewById(R.id.note_content); } @Override protected void setViewsAction(Bundle savedInstanceState) { } private void saveNoteContent() { ContentValues values = new ContentValues(); values.put(Notes.TITLE, mTileEditText.getText().toString()); values.put(Notes.DETAIL, mContentEditText.getText().toString()); values.put(Notes.BACKGROUND_COLOR, mChoosedColor); if(STATE_CREAT_NEW == mState){ getContentResolver().insert(mUri, values); } else if(STATE_EDIT == mState){ getContentResolver().update(mUri, values, null, null); } } @Override protected void loadData(Bundle savedInstanceState) { if (STATE_EDIT == mState) { startLoadingNotes(); } } private void startLoadingNotes() { getLoaderManager().enableDebugLogging(true); getLoaderManager().restartLoader(NOTES_LOADER_ID, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new NotesLoader(this, mUri); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (null == data) { return; } data.moveToFirst(); mTileEditText.setText(data.getString(NotesLoader.NOTE_TITLE)); mContentEditText.setText(data.getString(NotesLoader.NOTE_DETAIL)); } @Override public void onLoaderReset(Loader<Cursor> loader) { } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.edit, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id == R.id.complete){ saveNoteContent(); return true; } return super.onOptionsItemSelected(item); } @Override protected void onDestroy() { super.onDestroy(); if(null != mBgColors) { mBgColors.recycle(); } } }
apache-2.0
omengye/ws
gcs/src/main/java/io/omengye/gcs/exception/GlobalExceptionHandler.java
1808
package io.omengye.gcs.exception; import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler; import org.springframework.boot.web.reactive.error.ErrorAttributes; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.server.*; import reactor.core.publisher.Mono; import java.util.Map; @Component public class GlobalExceptionHandler extends AbstractErrorWebExceptionHandler { public GlobalExceptionHandler(GlobalErrorAttributes g, ApplicationContext applicationContext, ServerCodecConfigurer serverCodecConfigurer) { super(g, new ResourceProperties(), applicationContext); super.setMessageWriters(serverCodecConfigurer.getWriters()); super.setMessageReaders(serverCodecConfigurer.getReaders()); } @Override protected RouterFunction<ServerResponse> getRoutingFunction( ErrorAttributes errorAttributes) { return RouterFunctions.route( RequestPredicates.all(), this::renderErrorResponse); } private Mono<ServerResponse> renderErrorResponse( ServerRequest request) { Map<String, Object> errorPropertiesMap = getErrorAttributes(request, false); return ServerResponse.status(HttpStatus.BAD_REQUEST) .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(errorPropertiesMap)); } }
apache-2.0
googleapis/java-retail
proto-google-cloud-retail-v2/src/main/java/com/google/cloud/retail/v2/ColorInfoOrBuilder.java
8033
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/retail/v2/common.proto package com.google.cloud.retail.v2; public interface ColorInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.retail.v2.ColorInfo) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The standard color families. Strongly recommended to use the following * standard color groups: "Red", "Pink", "Orange", "Yellow", "Purple", * "Green", "Cyan", "Blue", "Brown", "White", "Gray", "Black" and * "Mixed". Normally it is expected to have only 1 color family. May consider * using single "Mixed" instead of multiple values. * A maximum of 5 values are allowed. Each value must be a UTF-8 encoded * string with a length limit of 128 characters. Otherwise, an * INVALID_ARGUMENT error is returned. * Google Merchant Center property * [color](https://support.google.com/merchants/answer/6324487). Schema.org * property [Product.color](https://schema.org/color). * </pre> * * <code>repeated string color_families = 1;</code> * * @return A list containing the colorFamilies. */ java.util.List<java.lang.String> getColorFamiliesList(); /** * * * <pre> * The standard color families. Strongly recommended to use the following * standard color groups: "Red", "Pink", "Orange", "Yellow", "Purple", * "Green", "Cyan", "Blue", "Brown", "White", "Gray", "Black" and * "Mixed". Normally it is expected to have only 1 color family. May consider * using single "Mixed" instead of multiple values. * A maximum of 5 values are allowed. Each value must be a UTF-8 encoded * string with a length limit of 128 characters. Otherwise, an * INVALID_ARGUMENT error is returned. * Google Merchant Center property * [color](https://support.google.com/merchants/answer/6324487). Schema.org * property [Product.color](https://schema.org/color). * </pre> * * <code>repeated string color_families = 1;</code> * * @return The count of colorFamilies. */ int getColorFamiliesCount(); /** * * * <pre> * The standard color families. Strongly recommended to use the following * standard color groups: "Red", "Pink", "Orange", "Yellow", "Purple", * "Green", "Cyan", "Blue", "Brown", "White", "Gray", "Black" and * "Mixed". Normally it is expected to have only 1 color family. May consider * using single "Mixed" instead of multiple values. * A maximum of 5 values are allowed. Each value must be a UTF-8 encoded * string with a length limit of 128 characters. Otherwise, an * INVALID_ARGUMENT error is returned. * Google Merchant Center property * [color](https://support.google.com/merchants/answer/6324487). Schema.org * property [Product.color](https://schema.org/color). * </pre> * * <code>repeated string color_families = 1;</code> * * @param index The index of the element to return. * @return The colorFamilies at the given index. */ java.lang.String getColorFamilies(int index); /** * * * <pre> * The standard color families. Strongly recommended to use the following * standard color groups: "Red", "Pink", "Orange", "Yellow", "Purple", * "Green", "Cyan", "Blue", "Brown", "White", "Gray", "Black" and * "Mixed". Normally it is expected to have only 1 color family. May consider * using single "Mixed" instead of multiple values. * A maximum of 5 values are allowed. Each value must be a UTF-8 encoded * string with a length limit of 128 characters. Otherwise, an * INVALID_ARGUMENT error is returned. * Google Merchant Center property * [color](https://support.google.com/merchants/answer/6324487). Schema.org * property [Product.color](https://schema.org/color). * </pre> * * <code>repeated string color_families = 1;</code> * * @param index The index of the value to return. * @return The bytes of the colorFamilies at the given index. */ com.google.protobuf.ByteString getColorFamiliesBytes(int index); /** * * * <pre> * The color display names, which may be different from standard color family * names, such as the color aliases used in the website frontend. Normally * it is expected to have only 1 color. May consider using single "Mixed" * instead of multiple values. * A maximum of 25 colors are allowed. Each value must be a UTF-8 encoded * string with a length limit of 128 characters. Otherwise, an * INVALID_ARGUMENT error is returned. * Google Merchant Center property * [color](https://support.google.com/merchants/answer/6324487). Schema.org * property [Product.color](https://schema.org/color). * </pre> * * <code>repeated string colors = 2;</code> * * @return A list containing the colors. */ java.util.List<java.lang.String> getColorsList(); /** * * * <pre> * The color display names, which may be different from standard color family * names, such as the color aliases used in the website frontend. Normally * it is expected to have only 1 color. May consider using single "Mixed" * instead of multiple values. * A maximum of 25 colors are allowed. Each value must be a UTF-8 encoded * string with a length limit of 128 characters. Otherwise, an * INVALID_ARGUMENT error is returned. * Google Merchant Center property * [color](https://support.google.com/merchants/answer/6324487). Schema.org * property [Product.color](https://schema.org/color). * </pre> * * <code>repeated string colors = 2;</code> * * @return The count of colors. */ int getColorsCount(); /** * * * <pre> * The color display names, which may be different from standard color family * names, such as the color aliases used in the website frontend. Normally * it is expected to have only 1 color. May consider using single "Mixed" * instead of multiple values. * A maximum of 25 colors are allowed. Each value must be a UTF-8 encoded * string with a length limit of 128 characters. Otherwise, an * INVALID_ARGUMENT error is returned. * Google Merchant Center property * [color](https://support.google.com/merchants/answer/6324487). Schema.org * property [Product.color](https://schema.org/color). * </pre> * * <code>repeated string colors = 2;</code> * * @param index The index of the element to return. * @return The colors at the given index. */ java.lang.String getColors(int index); /** * * * <pre> * The color display names, which may be different from standard color family * names, such as the color aliases used in the website frontend. Normally * it is expected to have only 1 color. May consider using single "Mixed" * instead of multiple values. * A maximum of 25 colors are allowed. Each value must be a UTF-8 encoded * string with a length limit of 128 characters. Otherwise, an * INVALID_ARGUMENT error is returned. * Google Merchant Center property * [color](https://support.google.com/merchants/answer/6324487). Schema.org * property [Product.color](https://schema.org/color). * </pre> * * <code>repeated string colors = 2;</code> * * @param index The index of the value to return. * @return The bytes of the colors at the given index. */ com.google.protobuf.ByteString getColorsBytes(int index); }
apache-2.0
dragonflyor/AndroidDemo_Base
04_05_分割新闻客户端/gen/com/xioazhe/newsapp/R.java
164472
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.xioazhe.newsapp; public final class R { public static final class anim { public static final int abc_fade_in=0x7f040000; public static final int abc_fade_out=0x7f040001; public static final int abc_slide_in_bottom=0x7f040002; public static final int abc_slide_in_top=0x7f040003; public static final int abc_slide_out_bottom=0x7f040004; public static final int abc_slide_out_top=0x7f040005; } public static final class attr { /** Custom divider drawable to use for elements in the action bar. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionBarDivider=0x7f01000b; /** Custom item state list drawable background for action bar items. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionBarItemBackground=0x7f01000c; /** Size of the Action Bar, including the contextual bar used to present Action Modes. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int actionBarSize=0x7f01000a; /** Reference to a theme that should be used to inflate widgets and layouts destined for the action bar. Most of the time this will be a reference to the current theme, but when the action bar has a significantly different contrast profile than the rest of the activity the difference can become important. If this is set to @null the current theme will be used. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionBarSplitStyle=0x7f010008; /** Reference to a style for the Action Bar <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionBarStyle=0x7f010007; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionBarTabBarStyle=0x7f010004; /** Default style for tabs within an action bar <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionBarTabStyle=0x7f010003; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionBarTabTextStyle=0x7f010005; /** Reference to a theme that should be used to inflate widgets and layouts destined for the action bar. Most of the time this will be a reference to the current theme, but when the action bar has a significantly different contrast profile than the rest of the activity the difference can become important. If this is set to @null the current theme will be used. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionBarWidgetTheme=0x7f010009; /** Default action button style. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionButtonStyle=0x7f010012; /** Default ActionBar dropdown style. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionDropDownStyle=0x7f010043; /** An optional layout to be used as an action view. See {@link android.view.MenuItem#setActionView(android.view.View)} for more info. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionLayout=0x7f01004a; /** TextAppearance style that will be applied to text that appears within action menu items. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionMenuTextAppearance=0x7f01000d; /** Color for text that appears within action menu items. <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". */ public static final int actionMenuTextColor=0x7f01000e; /** Background drawable to use for action mode UI <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModeBackground=0x7f010038; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModeCloseButtonStyle=0x7f010037; /** Drawable to use for the close action mode button <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModeCloseDrawable=0x7f01003a; /** Drawable to use for the Copy action button in Contextual Action Bar <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModeCopyDrawable=0x7f01003c; /** Drawable to use for the Cut action button in Contextual Action Bar <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModeCutDrawable=0x7f01003b; /** Drawable to use for the Find action button in WebView selection action modes <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModeFindDrawable=0x7f010040; /** Drawable to use for the Paste action button in Contextual Action Bar <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModePasteDrawable=0x7f01003d; /** PopupWindow style to use for action modes when showing as a window overlay. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModePopupWindowStyle=0x7f010042; /** Drawable to use for the Select all action button in Contextual Action Bar <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModeSelectAllDrawable=0x7f01003e; /** Drawable to use for the Share action button in WebView selection action modes <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModeShareDrawable=0x7f01003f; /** Background drawable to use for action mode UI in the lower split bar <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModeSplitBackground=0x7f010039; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModeStyle=0x7f010036; /** Drawable to use for the Web Search action button in WebView selection action modes <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionModeWebSearchDrawable=0x7f010041; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int actionOverflowButtonStyle=0x7f010006; /** The name of an optional ActionProvider class to instantiate an action view and perform operations such as default action for that menu item. See {@link android.view.MenuItem#setActionProvider(android.view.ActionProvider)} for more info. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int actionProviderClass=0x7f01004c; /** The name of an optional View class to instantiate and use as an action view. See {@link android.view.MenuItem#setActionView(android.view.View)} for more info. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int actionViewClass=0x7f01004b; /** Default ActivityChooserView style. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int activityChooserViewStyle=0x7f010068; /** Specifies a background drawable for the action bar. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int background=0x7f01002b; /** Specifies a background drawable for the bottom component of a split action bar. <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". */ public static final int backgroundSplit=0x7f01002d; /** Specifies a background drawable for a second stacked row of the action bar. <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". */ public static final int backgroundStacked=0x7f01002c; /** A style that may be applied to Buttons placed within a LinearLayout with the style buttonBarStyle to form a button bar. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int buttonBarButtonStyle=0x7f010014; /** A style that may be applied to horizontal LinearLayouts to form a button bar. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int buttonBarStyle=0x7f010013; /** Specifies a layout for custom navigation. Overrides navigationMode. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int customNavigationLayout=0x7f01002e; /** Whether this spinner should mark child views as enabled/disabled when the spinner itself is enabled/disabled. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int disableChildrenWhenDisabled=0x7f010050; /** Options affecting how the action bar is displayed. <p>Must be one or more (separated by '|') of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>useLogo</code></td><td>0x1</td><td></td></tr> <tr><td><code>showHome</code></td><td>0x2</td><td></td></tr> <tr><td><code>homeAsUp</code></td><td>0x4</td><td></td></tr> <tr><td><code>showTitle</code></td><td>0x8</td><td></td></tr> <tr><td><code>showCustom</code></td><td>0x10</td><td></td></tr> <tr><td><code>disableHome</code></td><td>0x20</td><td></td></tr> </table> */ public static final int displayOptions=0x7f010024; /** Specifies the drawable used for item dividers. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int divider=0x7f01002a; /** A drawable that may be used as a horizontal divider between visual elements. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int dividerHorizontal=0x7f010017; /** Size of padding on either end of a divider. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int dividerPadding=0x7f010052; /** A drawable that may be used as a vertical divider between visual elements. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int dividerVertical=0x7f010016; /** ListPopupWindow comaptibility <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int dropDownListViewStyle=0x7f01001d; /** The preferred item height for dropdown lists. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int dropdownListPreferredItemHeight=0x7f010044; /** The drawable to show in the button for expanding the activities overflow popup. <strong>Note:</strong> Clients would like to set this drawable as a clue about the action the chosen activity will perform. For example, if share activity is to be chosen the drawable should give a clue that sharing is to be performed. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int expandActivityOverflowButtonDrawable=0x7f010067; /** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int height=0x7f010022; /** Specifies a drawable to use for the 'home as up' indicator. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int homeAsUpIndicator=0x7f01000f; /** Specifies a layout to use for the "home" section of the action bar. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int homeLayout=0x7f01002f; /** Specifies the drawable used for the application icon. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int icon=0x7f010028; /** The default state of the SearchView. If true, it will be iconified when not in use and expanded when clicked. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int iconifiedByDefault=0x7f010056; /** Specifies a style resource to use for an indeterminate progress spinner. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int indeterminateProgressStyle=0x7f010031; /** The maximal number of items initially shown in the activity list. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int initialActivityCount=0x7f010066; /** Specifies whether the theme is light, otherwise it is dark. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int isLightTheme=0x7f010055; /** Specifies padding that should be applied to the left and right sides of system-provided items in the bar. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int itemPadding=0x7f010033; /** Drawable used as a background for selected list items. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int listChoiceBackgroundIndicator=0x7f010048; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int listPopupWindowStyle=0x7f01001e; /** The preferred list item height. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int listPreferredItemHeight=0x7f010018; /** A larger, more robust list item height. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int listPreferredItemHeightLarge=0x7f01001a; /** A smaller, sleeker list item height. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int listPreferredItemHeightSmall=0x7f010019; /** The preferred padding along the left edge of list items. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int listPreferredItemPaddingLeft=0x7f01001b; /** The preferred padding along the right edge of list items. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int listPreferredItemPaddingRight=0x7f01001c; /** Specifies the drawable used for the application logo. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int logo=0x7f010029; /** The type of navigation to use. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>normal</code></td><td>0</td><td> Normal static title text </td></tr> <tr><td><code>listMode</code></td><td>1</td><td> The action bar will use a selection list for navigation. </td></tr> <tr><td><code>tabMode</code></td><td>2</td><td> The action bar will use a series of horizontal tabs for navigation. </td></tr> </table> */ public static final int navigationMode=0x7f010023; /** Sets the padding, in pixels, of the end edge; see {@link android.R.attr#padding}. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int paddingEnd=0x7f010035; /** Sets the padding, in pixels, of the start edge; see {@link android.R.attr#padding}. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int paddingStart=0x7f010034; /** Default Panel Menu style. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int panelMenuListTheme=0x7f010047; /** Default Panel Menu width. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int panelMenuListWidth=0x7f010046; /** Default PopupMenu style. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int popupMenuStyle=0x7f010045; /** Reference to a layout to use for displaying a prompt in the dropdown for spinnerMode="dropdown". This layout must contain a TextView with the id {@code @android:id/text1} to be populated with the prompt text. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int popupPromptView=0x7f01004f; /** Specifies the horizontal padding on either end for an embedded progress bar. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int progressBarPadding=0x7f010032; /** Specifies a style resource to use for an embedded progress bar. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int progressBarStyle=0x7f010030; /** The prompt to display when the spinner's dialog is shown. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int prompt=0x7f01004d; /** An optional query hint string to be displayed in the empty query field. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int queryHint=0x7f010057; /** SearchView dropdown background <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int searchDropdownBackground=0x7f010058; /** The list item height for search results. @hide <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int searchResultListItemHeight=0x7f010061; /** SearchView AutoCompleteTextView style <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int searchViewAutoCompleteTextView=0x7f010065; /** SearchView close button icon <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int searchViewCloseIcon=0x7f010059; /** SearchView query refinement icon <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int searchViewEditQuery=0x7f01005d; /** SearchView query refinement icon background <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int searchViewEditQueryBackground=0x7f01005e; /** SearchView Go button icon <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int searchViewGoIcon=0x7f01005a; /** SearchView Search icon <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int searchViewSearchIcon=0x7f01005b; /** SearchView text field background for the left section <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int searchViewTextField=0x7f01005f; /** SearchView text field background for the right section <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int searchViewTextFieldRight=0x7f010060; /** SearchView Voice button icon <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int searchViewVoiceIcon=0x7f01005c; /** A style that may be applied to buttons or other selectable items that should react to pressed and focus states, but that do not have a clear visual border along the edges. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int selectableItemBackground=0x7f010015; /** How this item should display in the Action Bar, if present. <p>Must be one or more (separated by '|') of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>never</code></td><td>0</td><td> Never show this item in an action bar, show it in the overflow menu instead. Mutually exclusive with "ifRoom" and "always". </td></tr> <tr><td><code>ifRoom</code></td><td>1</td><td> Show this item in an action bar if there is room for it as determined by the system. Favor this option over "always" where possible. Mutually exclusive with "never" and "always". </td></tr> <tr><td><code>always</code></td><td>2</td><td> Always show this item in an actionbar, even if it would override the system's limits of how much stuff to put there. This may make your action bar look bad on some screens. In most cases you should use "ifRoom" instead. Mutually exclusive with "ifRoom" and "never". </td></tr> <tr><td><code>withText</code></td><td>4</td><td> When this item is shown as an action in the action bar, show a text label with it even if it has an icon representation. </td></tr> <tr><td><code>collapseActionView</code></td><td>8</td><td> This item's action view collapses to a normal menu item. When expanded, the action view takes over a larger segment of its container. </td></tr> </table> */ public static final int showAsAction=0x7f010049; /** Setting for which dividers to show. <p>Must be one or more (separated by '|') of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>0</td><td></td></tr> <tr><td><code>beginning</code></td><td>1</td><td></td></tr> <tr><td><code>middle</code></td><td>2</td><td></td></tr> <tr><td><code>end</code></td><td>4</td><td></td></tr> </table> */ public static final int showDividers=0x7f010051; /** Default Spinner style. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int spinnerDropDownItemStyle=0x7f010054; /** Display mode for spinner options. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>dialog</code></td><td>0</td><td> Spinner options will be presented to the user as a dialog window. </td></tr> <tr><td><code>dropdown</code></td><td>1</td><td> Spinner options will be presented to the user as an inline dropdown anchored to the spinner widget itself. </td></tr> </table> */ public static final int spinnerMode=0x7f01004e; /** Default Spinner style. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int spinnerStyle=0x7f010053; /** Specifies subtitle text used for navigationMode="normal" <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int subtitle=0x7f010025; /** Specifies a style to use for subtitle text. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int subtitleTextStyle=0x7f010027; /** Present the text in ALL CAPS. This may use a small-caps form when available. <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a boolean value, either "<code>true</code>" or "<code>false</code>". */ public static final int textAllCaps=0x7f010069; /** Text color, typeface, size, and style for the text inside of a popup menu. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int textAppearanceLargePopupMenu=0x7f010010; /** The preferred TextAppearance for the primary text of list items. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int textAppearanceListItem=0x7f01001f; /** The preferred TextAppearance for the primary text of small list items. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int textAppearanceListItemSmall=0x7f010020; /** Text color, typeface, size, and style for system search result subtitle. Defaults to primary inverse text color. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int textAppearanceSearchResultSubtitle=0x7f010063; /** Text color, typeface, size, and style for system search result title. Defaults to primary inverse text color. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int textAppearanceSearchResultTitle=0x7f010062; /** Text color, typeface, size, and style for small text inside of a popup menu. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int textAppearanceSmallPopupMenu=0x7f010011; /** Text color for urls in search suggestions, used by things like global search <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". */ public static final int textColorSearchUrl=0x7f010064; /** <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int title=0x7f010021; /** Specifies a style to use for title text. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int titleTextStyle=0x7f010026; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int windowActionBar=0x7f010000; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int windowActionBarOverlay=0x7f010001; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int windowSplitActionBar=0x7f010002; } public static final class bool { public static final int abc_action_bar_embed_tabs_pre_jb=0x7f060000; public static final int abc_action_bar_expanded_action_views_exclusive=0x7f060001; /** Whether action menu items should be displayed in ALLCAPS or not. Defaults to true. If this is not appropriate for specific locales it should be disabled in that locale's resources. */ public static final int abc_config_actionMenuItemAllCaps=0x7f060005; /** Whether action menu items should obey the "withText" showAsAction flag. This may be set to false for situations where space is extremely limited. Whether action menu items should obey the "withText" showAsAction. This may be set to false for situations where space is extremely limited. */ public static final int abc_config_allowActionMenuItemTextWithIcon=0x7f060004; public static final int abc_config_showMenuShortcutsWhenKeyboardPresent=0x7f060003; public static final int abc_split_action_bar_is_narrow=0x7f060002; } public static final class color { public static final int abc_search_url_text_holo=0x7f070003; public static final int abc_search_url_text_normal=0x7f070000; public static final int abc_search_url_text_pressed=0x7f070002; public static final int abc_search_url_text_selected=0x7f070001; } public static final class dimen { /** Default height of an action bar. Default height of an action bar. Default height of an action bar. Default height of an action bar. Default height of an action bar. */ public static final int abc_action_bar_default_height=0x7f080002; /** Vertical padding around action bar icons. Vertical padding around action bar icons. Vertical padding around action bar icons. Vertical padding around action bar icons. Vertical padding around action bar icons. */ public static final int abc_action_bar_icon_vertical_padding=0x7f080003; /** Size of the indeterminate Progress Bar Size of the indeterminate Progress Bar */ public static final int abc_action_bar_progress_bar_size=0x7f08000a; /** Maximum height for a stacked tab bar as part of an action bar */ public static final int abc_action_bar_stacked_max_height=0x7f080009; /** Maximum width for a stacked action bar tab. This prevents action bar tabs from becoming too wide on a wide screen when only a few are present. */ public static final int abc_action_bar_stacked_tab_max_width=0x7f080001; /** Bottom margin for action bar subtitles Bottom margin for action bar subtitles Bottom margin for action bar subtitles Bottom margin for action bar subtitles Bottom margin for action bar subtitles */ public static final int abc_action_bar_subtitle_bottom_margin=0x7f080007; /** Text size for action bar subtitles Text size for action bar subtitles Text size for action bar subtitles Text size for action bar subtitles Text size for action bar subtitles */ public static final int abc_action_bar_subtitle_text_size=0x7f080005; /** Top margin for action bar subtitles Top margin for action bar subtitles Top margin for action bar subtitles Top margin for action bar subtitles Top margin for action bar subtitles */ public static final int abc_action_bar_subtitle_top_margin=0x7f080006; /** Text size for action bar titles Text size for action bar titles Text size for action bar titles Text size for action bar titles Text size for action bar titles */ public static final int abc_action_bar_title_text_size=0x7f080004; /** Minimum width for an action button in the menu area of an action bar Minimum width for an action button in the menu area of an action bar Minimum width for an action button in the menu area of an action bar */ public static final int abc_action_button_min_width=0x7f080008; /** The maximum width we would prefer dialogs to be. 0 if there is no maximum (let them grow as large as the screen). Actual values are specified for -large and -xlarge configurations. see comment in values/config.xml see comment in values/config.xml */ public static final int abc_config_prefDialogWidth=0x7f080000; /** Width of the icon in a dropdown list */ public static final int abc_dropdownitem_icon_width=0x7f080010; /** Text padding for dropdown items */ public static final int abc_dropdownitem_text_padding_left=0x7f08000e; public static final int abc_dropdownitem_text_padding_right=0x7f08000f; public static final int abc_panel_menu_list_width=0x7f08000b; /** Preferred width of the search view. */ public static final int abc_search_view_preferred_width=0x7f08000d; /** Minimum width of the search view text entry area. Minimum width of the search view text entry area. Minimum width of the search view text entry area. Minimum width of the search view text entry area. */ public static final int abc_search_view_text_min_width=0x7f08000c; /** Default screen margins, per the Android Design guidelines. Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). */ public static final int activity_horizontal_margin=0x7f080011; public static final int activity_vertical_margin=0x7f080012; } public static final class drawable { public static final int abc_ab_bottom_solid_dark_holo=0x7f020000; public static final int abc_ab_bottom_solid_light_holo=0x7f020001; public static final int abc_ab_bottom_transparent_dark_holo=0x7f020002; public static final int abc_ab_bottom_transparent_light_holo=0x7f020003; public static final int abc_ab_share_pack_holo_dark=0x7f020004; public static final int abc_ab_share_pack_holo_light=0x7f020005; public static final int abc_ab_solid_dark_holo=0x7f020006; public static final int abc_ab_solid_light_holo=0x7f020007; public static final int abc_ab_stacked_solid_dark_holo=0x7f020008; public static final int abc_ab_stacked_solid_light_holo=0x7f020009; public static final int abc_ab_stacked_transparent_dark_holo=0x7f02000a; public static final int abc_ab_stacked_transparent_light_holo=0x7f02000b; public static final int abc_ab_transparent_dark_holo=0x7f02000c; public static final int abc_ab_transparent_light_holo=0x7f02000d; public static final int abc_cab_background_bottom_holo_dark=0x7f02000e; public static final int abc_cab_background_bottom_holo_light=0x7f02000f; public static final int abc_cab_background_top_holo_dark=0x7f020010; public static final int abc_cab_background_top_holo_light=0x7f020011; public static final int abc_ic_ab_back_holo_dark=0x7f020012; public static final int abc_ic_ab_back_holo_light=0x7f020013; public static final int abc_ic_cab_done_holo_dark=0x7f020014; public static final int abc_ic_cab_done_holo_light=0x7f020015; public static final int abc_ic_clear=0x7f020016; public static final int abc_ic_clear_disabled=0x7f020017; public static final int abc_ic_clear_holo_light=0x7f020018; public static final int abc_ic_clear_normal=0x7f020019; public static final int abc_ic_clear_search_api_disabled_holo_light=0x7f02001a; public static final int abc_ic_clear_search_api_holo_light=0x7f02001b; public static final int abc_ic_commit_search_api_holo_dark=0x7f02001c; public static final int abc_ic_commit_search_api_holo_light=0x7f02001d; public static final int abc_ic_go=0x7f02001e; public static final int abc_ic_go_search_api_holo_light=0x7f02001f; public static final int abc_ic_menu_moreoverflow_normal_holo_dark=0x7f020020; public static final int abc_ic_menu_moreoverflow_normal_holo_light=0x7f020021; public static final int abc_ic_menu_share_holo_dark=0x7f020022; public static final int abc_ic_menu_share_holo_light=0x7f020023; public static final int abc_ic_search=0x7f020024; public static final int abc_ic_search_api_holo_light=0x7f020025; public static final int abc_ic_voice_search=0x7f020026; public static final int abc_ic_voice_search_api_holo_light=0x7f020027; public static final int abc_item_background_holo_dark=0x7f020028; public static final int abc_item_background_holo_light=0x7f020029; public static final int abc_list_divider_holo_dark=0x7f02002a; public static final int abc_list_divider_holo_light=0x7f02002b; public static final int abc_list_focused_holo=0x7f02002c; public static final int abc_list_longpressed_holo=0x7f02002d; public static final int abc_list_pressed_holo_dark=0x7f02002e; public static final int abc_list_pressed_holo_light=0x7f02002f; public static final int abc_list_selector_background_transition_holo_dark=0x7f020030; public static final int abc_list_selector_background_transition_holo_light=0x7f020031; public static final int abc_list_selector_disabled_holo_dark=0x7f020032; public static final int abc_list_selector_disabled_holo_light=0x7f020033; public static final int abc_list_selector_holo_dark=0x7f020034; public static final int abc_list_selector_holo_light=0x7f020035; public static final int abc_menu_dropdown_panel_holo_dark=0x7f020036; public static final int abc_menu_dropdown_panel_holo_light=0x7f020037; public static final int abc_menu_hardkey_panel_holo_dark=0x7f020038; public static final int abc_menu_hardkey_panel_holo_light=0x7f020039; public static final int abc_search_dropdown_dark=0x7f02003a; public static final int abc_search_dropdown_light=0x7f02003b; public static final int abc_spinner_ab_default_holo_dark=0x7f02003c; public static final int abc_spinner_ab_default_holo_light=0x7f02003d; public static final int abc_spinner_ab_disabled_holo_dark=0x7f02003e; public static final int abc_spinner_ab_disabled_holo_light=0x7f02003f; public static final int abc_spinner_ab_focused_holo_dark=0x7f020040; public static final int abc_spinner_ab_focused_holo_light=0x7f020041; public static final int abc_spinner_ab_holo_dark=0x7f020042; public static final int abc_spinner_ab_holo_light=0x7f020043; public static final int abc_spinner_ab_pressed_holo_dark=0x7f020044; public static final int abc_spinner_ab_pressed_holo_light=0x7f020045; public static final int abc_tab_indicator_ab_holo=0x7f020046; public static final int abc_tab_selected_focused_holo=0x7f020047; public static final int abc_tab_selected_holo=0x7f020048; public static final int abc_tab_selected_pressed_holo=0x7f020049; public static final int abc_tab_unselected_pressed_holo=0x7f02004a; public static final int abc_textfield_search_default_holo_dark=0x7f02004b; public static final int abc_textfield_search_default_holo_light=0x7f02004c; public static final int abc_textfield_search_right_default_holo_dark=0x7f02004d; public static final int abc_textfield_search_right_default_holo_light=0x7f02004e; public static final int abc_textfield_search_right_selected_holo_dark=0x7f02004f; public static final int abc_textfield_search_right_selected_holo_light=0x7f020050; public static final int abc_textfield_search_selected_holo_dark=0x7f020051; public static final int abc_textfield_search_selected_holo_light=0x7f020052; public static final int abc_textfield_searchview_holo_dark=0x7f020053; public static final int abc_textfield_searchview_holo_light=0x7f020054; public static final int abc_textfield_searchview_right_holo_dark=0x7f020055; public static final int abc_textfield_searchview_right_holo_light=0x7f020056; public static final int ic_launcher=0x7f020057; } public static final class id { public static final int action_bar=0x7f05001c; public static final int action_bar_activity_content=0x7f050015; public static final int action_bar_container=0x7f05001b; public static final int action_bar_overlay_layout=0x7f05001f; public static final int action_bar_root=0x7f05001a; public static final int action_bar_subtitle=0x7f050023; public static final int action_bar_title=0x7f050022; public static final int action_context_bar=0x7f05001d; public static final int action_menu_divider=0x7f050016; public static final int action_menu_presenter=0x7f050017; public static final int action_mode_close_button=0x7f050024; public static final int action_settings=0x7f050042; public static final int activity_chooser_view_content=0x7f050025; public static final int always=0x7f05000b; public static final int beginning=0x7f050011; public static final int checkbox=0x7f05002d; public static final int collapseActionView=0x7f05000d; public static final int container=0x7f05003c; public static final int default_activity_button=0x7f050028; public static final int dialog=0x7f05000e; public static final int disableHome=0x7f050008; public static final int dropdown=0x7f05000f; public static final int edit_query=0x7f050030; public static final int end=0x7f050013; public static final int expand_activities_button=0x7f050026; public static final int expanded_menu=0x7f05002c; public static final int home=0x7f050014; public static final int homeAsUp=0x7f050005; public static final int icon=0x7f05002a; public static final int ifRoom=0x7f05000a; public static final int image=0x7f050027; public static final int listMode=0x7f050001; public static final int list_item=0x7f050029; public static final int lv=0x7f05003d; public static final int middle=0x7f050012; public static final int never=0x7f050009; public static final int none=0x7f050010; public static final int normal=0x7f050000; public static final int progress_circular=0x7f050018; public static final int progress_horizontal=0x7f050019; public static final int radio=0x7f05002f; public static final int search_badge=0x7f050032; public static final int search_bar=0x7f050031; public static final int search_button=0x7f050033; public static final int search_close_btn=0x7f050038; public static final int search_edit_frame=0x7f050034; public static final int search_go_btn=0x7f05003a; public static final int search_mag_icon=0x7f050035; public static final int search_plate=0x7f050036; public static final int search_src_text=0x7f050037; public static final int search_voice_btn=0x7f05003b; public static final int shortcut=0x7f05002e; public static final int showCustom=0x7f050007; public static final int showHome=0x7f050004; public static final int showTitle=0x7f050006; public static final int siv=0x7f05003e; public static final int split_action_bar=0x7f05001e; public static final int submit_area=0x7f050039; public static final int tabMode=0x7f050002; public static final int title=0x7f05002b; public static final int top_action_bar=0x7f050020; public static final int tv_comment=0x7f050041; public static final int tv_detail=0x7f050040; public static final int tv_title=0x7f05003f; public static final int up=0x7f050021; public static final int useLogo=0x7f050003; public static final int withText=0x7f05000c; } public static final class integer { /** The maximum number of action buttons that should be permitted within an action bar/action mode. This will be used to determine how many showAsAction="ifRoom" items can fit. "always" items can override this. The maximum number of action buttons that should be permitted within an action bar/action mode. This will be used to determine how many showAsAction="ifRoom" items can fit. "always" items can override this. The maximum number of action buttons that should be permitted within an action bar/action mode. This will be used to determine how many showAsAction="ifRoom" items can fit. "always" items can override this. The maximum number of action buttons that should be permitted within an action bar/action mode. This will be used to determine how many showAsAction="ifRoom" items can fit. "always" items can override this. The maximum number of action buttons that should be permitted within an action bar/action mode. This will be used to determine how many showAsAction="ifRoom" items can fit. "always" items can override this. The maximum number of action buttons that should be permitted within an action bar/action mode. This will be used to determine how many showAsAction="ifRoom" items can fit. "always" items can override this. The maximum number of action buttons that should be permitted within an action bar/action mode. This will be used to determine how many showAsAction="ifRoom" items can fit. "always" items can override this. */ public static final int abc_max_action_buttons=0x7f090000; } public static final class layout { public static final int abc_action_bar_decor=0x7f030000; public static final int abc_action_bar_decor_include=0x7f030001; public static final int abc_action_bar_decor_overlay=0x7f030002; public static final int abc_action_bar_home=0x7f030003; public static final int abc_action_bar_tab=0x7f030004; public static final int abc_action_bar_tabbar=0x7f030005; public static final int abc_action_bar_title_item=0x7f030006; public static final int abc_action_bar_view_list_nav_layout=0x7f030007; public static final int abc_action_menu_item_layout=0x7f030008; public static final int abc_action_menu_layout=0x7f030009; public static final int abc_action_mode_bar=0x7f03000a; public static final int abc_action_mode_close_item=0x7f03000b; public static final int abc_activity_chooser_view=0x7f03000c; public static final int abc_activity_chooser_view_include=0x7f03000d; public static final int abc_activity_chooser_view_list_item=0x7f03000e; public static final int abc_expanded_menu_layout=0x7f03000f; public static final int abc_list_menu_item_checkbox=0x7f030010; public static final int abc_list_menu_item_icon=0x7f030011; public static final int abc_list_menu_item_layout=0x7f030012; public static final int abc_list_menu_item_radio=0x7f030013; public static final int abc_popup_menu_item_layout=0x7f030014; public static final int abc_search_dropdown_item_icons_2line=0x7f030015; public static final int abc_search_view=0x7f030016; public static final int activity_main=0x7f030017; public static final int fragment_main=0x7f030018; public static final int items_listview=0x7f030019; public static final int support_simple_spinner_dropdown_item=0x7f03001a; } public static final class menu { public static final int main=0x7f0c0000; } public static final class string { /** Content description for the action bar "home" affordance. [CHAR LIMIT=NONE] */ public static final int abc_action_bar_home_description=0x7f0a0001; /** Content description for the action bar "up" affordance. [CHAR LIMIT=NONE] */ public static final int abc_action_bar_up_description=0x7f0a0002; /** Content description for the action menu overflow button. [CHAR LIMIT=NONE] */ public static final int abc_action_menu_overflow_description=0x7f0a0003; /** Label for the "Done" button on the far left of action mode toolbars. */ public static final int abc_action_mode_done=0x7f0a0000; /** Title for a button to expand the list of activities in ActivityChooserView [CHAR LIMIT=25] */ public static final int abc_activity_chooser_view_see_all=0x7f0a000a; /** ActivityChooserView - accessibility support Description of the shwoing of a popup window with activities to choose from. [CHAR LIMIT=NONE] */ public static final int abc_activitychooserview_choose_application=0x7f0a0009; /** SearchView accessibility description for clear button [CHAR LIMIT=NONE] */ public static final int abc_searchview_description_clear=0x7f0a0006; /** SearchView accessibility description for search text field [CHAR LIMIT=NONE] */ public static final int abc_searchview_description_query=0x7f0a0005; /** SearchView accessibility description for search button [CHAR LIMIT=NONE] */ public static final int abc_searchview_description_search=0x7f0a0004; /** SearchView accessibility description for submit button [CHAR LIMIT=NONE] */ public static final int abc_searchview_description_submit=0x7f0a0007; /** SearchView accessibility description for voice button [CHAR LIMIT=NONE] */ public static final int abc_searchview_description_voice=0x7f0a0008; /** Description of the choose target button in a ShareActionProvider (share UI). [CHAR LIMIT=NONE] */ public static final int abc_shareactionprovider_share_with=0x7f0a000c; /** Description of a share target (both in the list of such or the default share button) in a ShareActionProvider (share UI). [CHAR LIMIT=NONE] */ public static final int abc_shareactionprovider_share_with_application=0x7f0a000b; public static final int action_settings=0x7f0a000f; public static final int app_name=0x7f0a000d; public static final int hello_world=0x7f0a000e; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f0b0083; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f0b0084; /** Mimic text appearance in select_dialog_item.xml */ public static final int TextAppearance_AppCompat_Base_CompactMenu_Dialog=0x7f0b0063; public static final int TextAppearance_AppCompat_Base_SearchResult=0x7f0b006d; public static final int TextAppearance_AppCompat_Base_SearchResult_Subtitle=0x7f0b006f; /** Search View result styles */ public static final int TextAppearance_AppCompat_Base_SearchResult_Title=0x7f0b006e; public static final int TextAppearance_AppCompat_Base_Widget_PopupMenu_Large=0x7f0b0069; public static final int TextAppearance_AppCompat_Base_Widget_PopupMenu_Small=0x7f0b006a; public static final int TextAppearance_AppCompat_Light_Base_SearchResult=0x7f0b0070; public static final int TextAppearance_AppCompat_Light_Base_SearchResult_Subtitle=0x7f0b0072; /** TextAppearance.Holo.Light.SearchResult.* are private so we extend from the default versions instead (which are exactly the same). */ public static final int TextAppearance_AppCompat_Light_Base_SearchResult_Title=0x7f0b0071; public static final int TextAppearance_AppCompat_Light_Base_Widget_PopupMenu_Large=0x7f0b006b; public static final int TextAppearance_AppCompat_Light_Base_Widget_PopupMenu_Small=0x7f0b006c; public static final int TextAppearance_AppCompat_Light_SearchResult_Subtitle=0x7f0b0035; public static final int TextAppearance_AppCompat_Light_SearchResult_Title=0x7f0b0034; public static final int TextAppearance_AppCompat_Light_Widget_PopupMenu_Large=0x7f0b0030; public static final int TextAppearance_AppCompat_Light_Widget_PopupMenu_Small=0x7f0b0031; public static final int TextAppearance_AppCompat_SearchResult_Subtitle=0x7f0b0033; public static final int TextAppearance_AppCompat_SearchResult_Title=0x7f0b0032; public static final int TextAppearance_AppCompat_Widget_ActionBar_Menu=0x7f0b001a; public static final int TextAppearance_AppCompat_Widget_ActionBar_Subtitle=0x7f0b0006; public static final int TextAppearance_AppCompat_Widget_ActionBar_Subtitle_Inverse=0x7f0b0008; public static final int TextAppearance_AppCompat_Widget_ActionBar_Title=0x7f0b0005; public static final int TextAppearance_AppCompat_Widget_ActionBar_Title_Inverse=0x7f0b0007; public static final int TextAppearance_AppCompat_Widget_ActionMode_Subtitle=0x7f0b001e; public static final int TextAppearance_AppCompat_Widget_ActionMode_Subtitle_Inverse=0x7f0b0020; public static final int TextAppearance_AppCompat_Widget_ActionMode_Title=0x7f0b001d; public static final int TextAppearance_AppCompat_Widget_ActionMode_Title_Inverse=0x7f0b001f; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Menu=0x7f0b0054; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Subtitle=0x7f0b0056; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Subtitle_Inverse=0x7f0b0058; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Title=0x7f0b0055; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Title_Inverse=0x7f0b0057; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Subtitle=0x7f0b0051; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Subtitle_Inverse=0x7f0b0053; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Title=0x7f0b0050; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Title_Inverse=0x7f0b0052; public static final int TextAppearance_AppCompat_Widget_Base_DropDownItem=0x7f0b0061; public static final int TextAppearance_AppCompat_Widget_DropDownItem=0x7f0b0021; public static final int TextAppearance_AppCompat_Widget_PopupMenu_Large=0x7f0b002e; public static final int TextAppearance_AppCompat_Widget_PopupMenu_Small=0x7f0b002f; public static final int TextAppearance_Widget_AppCompat_Base_ExpandedMenu_Item=0x7f0b0062; public static final int TextAppearance_Widget_AppCompat_ExpandedMenu_Item=0x7f0b0028; /** Themes in the "Theme.AppCompat" family will contain an action bar by default. If Holo themes are available on the current platform version they will be used. A limited Holo-styled action bar will be provided on platform versions older than 3.0. (API 11) These theme declarations contain any version-independent specification. Items that need to vary based on platform version should be defined in the corresponding "Theme.Base" theme. Platform-independent theme providing an action bar in a dark-themed activity. */ public static final int Theme_AppCompat=0x7f0b0077; /** Menu/item attributes */ public static final int Theme_AppCompat_Base_CompactMenu=0x7f0b0081; public static final int Theme_AppCompat_Base_CompactMenu_Dialog=0x7f0b0082; /** Menu/item attributes */ public static final int Theme_AppCompat_CompactMenu=0x7f0b007a; public static final int Theme_AppCompat_CompactMenu_Dialog=0x7f0b007b; /** Platform-independent theme providing an action bar in a light-themed activity. */ public static final int Theme_AppCompat_Light=0x7f0b0078; /** Platform-independent theme providing an action bar in a dark-themed activity. */ public static final int Theme_AppCompat_Light_DarkActionBar=0x7f0b0079; /** Base platform-dependent theme */ public static final int Theme_Base=0x7f0b007c; /** Base platform-dependent theme providing an action bar in a dark-themed activity. Base platform-dependent theme providing an action bar in a dark-themed activity. */ public static final int Theme_Base_AppCompat=0x7f0b007e; /** Base platform-dependent theme providing an action bar in a light-themed activity. Base platform-dependent theme providing an action bar in a light-themed activity. */ public static final int Theme_Base_AppCompat_Light=0x7f0b007f; /** Base platform-dependent theme providing a dark action bar in a light-themed activity. Base platform-dependent theme providing a dark action bar in a light-themed activity. */ public static final int Theme_Base_AppCompat_Light_DarkActionBar=0x7f0b0080; /** Base platform-dependent theme providing a light-themed activity. */ public static final int Theme_Base_Light=0x7f0b007d; /** Styles in here can be extended for customisation in your application. Each utilises one of the Base styles. If Holo themes are available on the current platform version they will be used instead of the compat styles. */ public static final int Widget_AppCompat_ActionBar=0x7f0b0000; public static final int Widget_AppCompat_ActionBar_Solid=0x7f0b0002; public static final int Widget_AppCompat_ActionBar_TabBar=0x7f0b0011; public static final int Widget_AppCompat_ActionBar_TabText=0x7f0b0017; public static final int Widget_AppCompat_ActionBar_TabView=0x7f0b0014; public static final int Widget_AppCompat_ActionButton=0x7f0b000b; public static final int Widget_AppCompat_ActionButton_CloseMode=0x7f0b000d; public static final int Widget_AppCompat_ActionButton_Overflow=0x7f0b000f; public static final int Widget_AppCompat_ActionMode=0x7f0b001b; public static final int Widget_AppCompat_ActivityChooserView=0x7f0b0038; public static final int Widget_AppCompat_AutoCompleteTextView=0x7f0b0036; public static final int Widget_AppCompat_Base_ActionBar=0x7f0b003a; public static final int Widget_AppCompat_Base_ActionBar_Solid=0x7f0b003c; public static final int Widget_AppCompat_Base_ActionBar_TabBar=0x7f0b0045; public static final int Widget_AppCompat_Base_ActionBar_TabText=0x7f0b004b; public static final int Widget_AppCompat_Base_ActionBar_TabView=0x7f0b0048; /** Action Button Styles */ public static final int Widget_AppCompat_Base_ActionButton=0x7f0b003f; public static final int Widget_AppCompat_Base_ActionButton_CloseMode=0x7f0b0041; public static final int Widget_AppCompat_Base_ActionButton_Overflow=0x7f0b0043; public static final int Widget_AppCompat_Base_ActionMode=0x7f0b004e; public static final int Widget_AppCompat_Base_ActivityChooserView=0x7f0b0075; /** AutoCompleteTextView styles (for SearchView) */ public static final int Widget_AppCompat_Base_AutoCompleteTextView=0x7f0b0073; public static final int Widget_AppCompat_Base_DropDownItem_Spinner=0x7f0b005d; /** Popup Menu */ public static final int Widget_AppCompat_Base_ListPopupWindow=0x7f0b0065; /** Spinner Widgets */ public static final int Widget_AppCompat_Base_ListView_DropDown=0x7f0b005f; public static final int Widget_AppCompat_Base_ListView_Menu=0x7f0b0064; public static final int Widget_AppCompat_Base_PopupMenu=0x7f0b0067; public static final int Widget_AppCompat_Base_ProgressBar=0x7f0b005a; /** Progress Bar */ public static final int Widget_AppCompat_Base_ProgressBar_Horizontal=0x7f0b0059; /** Action Bar Spinner Widgets */ public static final int Widget_AppCompat_Base_Spinner=0x7f0b005b; public static final int Widget_AppCompat_DropDownItem_Spinner=0x7f0b0024; public static final int Widget_AppCompat_Light_ActionBar=0x7f0b0001; public static final int Widget_AppCompat_Light_ActionBar_Solid=0x7f0b0003; public static final int Widget_AppCompat_Light_ActionBar_Solid_Inverse=0x7f0b0004; public static final int Widget_AppCompat_Light_ActionBar_TabBar=0x7f0b0012; public static final int Widget_AppCompat_Light_ActionBar_TabBar_Inverse=0x7f0b0013; public static final int Widget_AppCompat_Light_ActionBar_TabText=0x7f0b0018; public static final int Widget_AppCompat_Light_ActionBar_TabText_Inverse=0x7f0b0019; public static final int Widget_AppCompat_Light_ActionBar_TabView=0x7f0b0015; public static final int Widget_AppCompat_Light_ActionBar_TabView_Inverse=0x7f0b0016; public static final int Widget_AppCompat_Light_ActionButton=0x7f0b000c; public static final int Widget_AppCompat_Light_ActionButton_CloseMode=0x7f0b000e; public static final int Widget_AppCompat_Light_ActionButton_Overflow=0x7f0b0010; public static final int Widget_AppCompat_Light_ActionMode_Inverse=0x7f0b001c; public static final int Widget_AppCompat_Light_ActivityChooserView=0x7f0b0039; public static final int Widget_AppCompat_Light_AutoCompleteTextView=0x7f0b0037; public static final int Widget_AppCompat_Light_Base_ActionBar=0x7f0b003b; public static final int Widget_AppCompat_Light_Base_ActionBar_Solid=0x7f0b003d; public static final int Widget_AppCompat_Light_Base_ActionBar_Solid_Inverse=0x7f0b003e; public static final int Widget_AppCompat_Light_Base_ActionBar_TabBar=0x7f0b0046; public static final int Widget_AppCompat_Light_Base_ActionBar_TabBar_Inverse=0x7f0b0047; public static final int Widget_AppCompat_Light_Base_ActionBar_TabText=0x7f0b004c; public static final int Widget_AppCompat_Light_Base_ActionBar_TabText_Inverse=0x7f0b004d; public static final int Widget_AppCompat_Light_Base_ActionBar_TabView=0x7f0b0049; public static final int Widget_AppCompat_Light_Base_ActionBar_TabView_Inverse=0x7f0b004a; public static final int Widget_AppCompat_Light_Base_ActionButton=0x7f0b0040; public static final int Widget_AppCompat_Light_Base_ActionButton_CloseMode=0x7f0b0042; public static final int Widget_AppCompat_Light_Base_ActionButton_Overflow=0x7f0b0044; public static final int Widget_AppCompat_Light_Base_ActionMode_Inverse=0x7f0b004f; public static final int Widget_AppCompat_Light_Base_ActivityChooserView=0x7f0b0076; public static final int Widget_AppCompat_Light_Base_AutoCompleteTextView=0x7f0b0074; public static final int Widget_AppCompat_Light_Base_DropDownItem_Spinner=0x7f0b005e; public static final int Widget_AppCompat_Light_Base_ListPopupWindow=0x7f0b0066; public static final int Widget_AppCompat_Light_Base_ListView_DropDown=0x7f0b0060; public static final int Widget_AppCompat_Light_Base_PopupMenu=0x7f0b0068; public static final int Widget_AppCompat_Light_Base_Spinner=0x7f0b005c; public static final int Widget_AppCompat_Light_DropDownItem_Spinner=0x7f0b0025; public static final int Widget_AppCompat_Light_ListPopupWindow=0x7f0b002a; public static final int Widget_AppCompat_Light_ListView_DropDown=0x7f0b0027; public static final int Widget_AppCompat_Light_PopupMenu=0x7f0b002c; public static final int Widget_AppCompat_Light_Spinner_DropDown_ActionBar=0x7f0b0023; public static final int Widget_AppCompat_ListPopupWindow=0x7f0b0029; public static final int Widget_AppCompat_ListView_DropDown=0x7f0b0026; public static final int Widget_AppCompat_ListView_Menu=0x7f0b002d; public static final int Widget_AppCompat_PopupMenu=0x7f0b002b; public static final int Widget_AppCompat_ProgressBar=0x7f0b000a; public static final int Widget_AppCompat_ProgressBar_Horizontal=0x7f0b0009; public static final int Widget_AppCompat_Spinner_DropDown_ActionBar=0x7f0b0022; } public static final class styleable { /** ============================================ Attributes used to style the Action Bar. These should be set on your theme; the default actionBarStyle will propagate them to the correct elements as needed. Please Note: when overriding attributes for an ActionBar style you must specify each attribute twice: once with the "android:" namespace prefix and once without. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #ActionBar_background com.xioazhe.newsapp:background}</code></td><td> Specifies a background drawable for the action bar.</td></tr> <tr><td><code>{@link #ActionBar_backgroundSplit com.xioazhe.newsapp:backgroundSplit}</code></td><td> Specifies a background drawable for the bottom component of a split action bar.</td></tr> <tr><td><code>{@link #ActionBar_backgroundStacked com.xioazhe.newsapp:backgroundStacked}</code></td><td> Specifies a background drawable for a second stacked row of the action bar.</td></tr> <tr><td><code>{@link #ActionBar_customNavigationLayout com.xioazhe.newsapp:customNavigationLayout}</code></td><td> Specifies a layout for custom navigation.</td></tr> <tr><td><code>{@link #ActionBar_displayOptions com.xioazhe.newsapp:displayOptions}</code></td><td> Options affecting how the action bar is displayed.</td></tr> <tr><td><code>{@link #ActionBar_divider com.xioazhe.newsapp:divider}</code></td><td> Specifies the drawable used for item dividers.</td></tr> <tr><td><code>{@link #ActionBar_height com.xioazhe.newsapp:height}</code></td><td> Specifies a fixed height.</td></tr> <tr><td><code>{@link #ActionBar_homeLayout com.xioazhe.newsapp:homeLayout}</code></td><td> Specifies a layout to use for the "home" section of the action bar.</td></tr> <tr><td><code>{@link #ActionBar_icon com.xioazhe.newsapp:icon}</code></td><td> Specifies the drawable used for the application icon.</td></tr> <tr><td><code>{@link #ActionBar_indeterminateProgressStyle com.xioazhe.newsapp:indeterminateProgressStyle}</code></td><td> Specifies a style resource to use for an indeterminate progress spinner.</td></tr> <tr><td><code>{@link #ActionBar_itemPadding com.xioazhe.newsapp:itemPadding}</code></td><td> Specifies padding that should be applied to the left and right sides of system-provided items in the bar.</td></tr> <tr><td><code>{@link #ActionBar_logo com.xioazhe.newsapp:logo}</code></td><td> Specifies the drawable used for the application logo.</td></tr> <tr><td><code>{@link #ActionBar_navigationMode com.xioazhe.newsapp:navigationMode}</code></td><td> The type of navigation to use.</td></tr> <tr><td><code>{@link #ActionBar_progressBarPadding com.xioazhe.newsapp:progressBarPadding}</code></td><td> Specifies the horizontal padding on either end for an embedded progress bar.</td></tr> <tr><td><code>{@link #ActionBar_progressBarStyle com.xioazhe.newsapp:progressBarStyle}</code></td><td> Specifies a style resource to use for an embedded progress bar.</td></tr> <tr><td><code>{@link #ActionBar_subtitle com.xioazhe.newsapp:subtitle}</code></td><td> Specifies subtitle text used for navigationMode="normal" </td></tr> <tr><td><code>{@link #ActionBar_subtitleTextStyle com.xioazhe.newsapp:subtitleTextStyle}</code></td><td> Specifies a style to use for subtitle text.</td></tr> <tr><td><code>{@link #ActionBar_title com.xioazhe.newsapp:title}</code></td><td> Specifies title text used for navigationMode="normal" </td></tr> <tr><td><code>{@link #ActionBar_titleTextStyle com.xioazhe.newsapp:titleTextStyle}</code></td><td> Specifies a style to use for title text.</td></tr> </table> @see #ActionBar_background @see #ActionBar_backgroundSplit @see #ActionBar_backgroundStacked @see #ActionBar_customNavigationLayout @see #ActionBar_displayOptions @see #ActionBar_divider @see #ActionBar_height @see #ActionBar_homeLayout @see #ActionBar_icon @see #ActionBar_indeterminateProgressStyle @see #ActionBar_itemPadding @see #ActionBar_logo @see #ActionBar_navigationMode @see #ActionBar_progressBarPadding @see #ActionBar_progressBarStyle @see #ActionBar_subtitle @see #ActionBar_subtitleTextStyle @see #ActionBar_title @see #ActionBar_titleTextStyle */ public static final int[] ActionBar = { 0x7f010021, 0x7f010022, 0x7f010023, 0x7f010024, 0x7f010025, 0x7f010026, 0x7f010027, 0x7f010028, 0x7f010029, 0x7f01002a, 0x7f01002b, 0x7f01002c, 0x7f01002d, 0x7f01002e, 0x7f01002f, 0x7f010030, 0x7f010031, 0x7f010032, 0x7f010033 }; /** <p> @attr description Specifies a background drawable for the action bar. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:background */ public static final int ActionBar_background = 10; /** <p> @attr description Specifies a background drawable for the bottom component of a split action bar. <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:backgroundSplit */ public static final int ActionBar_backgroundSplit = 12; /** <p> @attr description Specifies a background drawable for a second stacked row of the action bar. <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:backgroundStacked */ public static final int ActionBar_backgroundStacked = 11; /** <p> @attr description Specifies a layout for custom navigation. Overrides navigationMode. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:customNavigationLayout */ public static final int ActionBar_customNavigationLayout = 13; /** <p> @attr description Options affecting how the action bar is displayed. <p>Must be one or more (separated by '|') of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>useLogo</code></td><td>0x1</td><td></td></tr> <tr><td><code>showHome</code></td><td>0x2</td><td></td></tr> <tr><td><code>homeAsUp</code></td><td>0x4</td><td></td></tr> <tr><td><code>showTitle</code></td><td>0x8</td><td></td></tr> <tr><td><code>showCustom</code></td><td>0x10</td><td></td></tr> <tr><td><code>disableHome</code></td><td>0x20</td><td></td></tr> </table> <p>This is a private symbol. @attr name com.xioazhe.newsapp:displayOptions */ public static final int ActionBar_displayOptions = 3; /** <p> @attr description Specifies the drawable used for item dividers. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:divider */ public static final int ActionBar_divider = 9; /** <p> @attr description Specifies a fixed height. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:height */ public static final int ActionBar_height = 1; /** <p> @attr description Specifies a layout to use for the "home" section of the action bar. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:homeLayout */ public static final int ActionBar_homeLayout = 14; /** <p> @attr description Specifies the drawable used for the application icon. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:icon */ public static final int ActionBar_icon = 7; /** <p> @attr description Specifies a style resource to use for an indeterminate progress spinner. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:indeterminateProgressStyle */ public static final int ActionBar_indeterminateProgressStyle = 16; /** <p> @attr description Specifies padding that should be applied to the left and right sides of system-provided items in the bar. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:itemPadding */ public static final int ActionBar_itemPadding = 18; /** <p> @attr description Specifies the drawable used for the application logo. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:logo */ public static final int ActionBar_logo = 8; /** <p> @attr description The type of navigation to use. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>normal</code></td><td>0</td><td> Normal static title text </td></tr> <tr><td><code>listMode</code></td><td>1</td><td> The action bar will use a selection list for navigation. </td></tr> <tr><td><code>tabMode</code></td><td>2</td><td> The action bar will use a series of horizontal tabs for navigation. </td></tr> </table> <p>This is a private symbol. @attr name com.xioazhe.newsapp:navigationMode */ public static final int ActionBar_navigationMode = 2; /** <p> @attr description Specifies the horizontal padding on either end for an embedded progress bar. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:progressBarPadding */ public static final int ActionBar_progressBarPadding = 17; /** <p> @attr description Specifies a style resource to use for an embedded progress bar. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:progressBarStyle */ public static final int ActionBar_progressBarStyle = 15; /** <p> @attr description Specifies subtitle text used for navigationMode="normal" <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:subtitle */ public static final int ActionBar_subtitle = 4; /** <p> @attr description Specifies a style to use for subtitle text. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:subtitleTextStyle */ public static final int ActionBar_subtitleTextStyle = 6; /** <p> @attr description Specifies title text used for navigationMode="normal" <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:title */ public static final int ActionBar_title = 0; /** <p> @attr description Specifies a style to use for title text. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:titleTextStyle */ public static final int ActionBar_titleTextStyle = 5; /** Valid LayoutParams for views placed in the action bar as custom views. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #ActionBarLayout_android_layout_gravity android:layout_gravity}</code></td><td></td></tr> </table> @see #ActionBarLayout_android_layout_gravity */ public static final int[] ActionBarLayout = { 0x010100b3 }; /** <p>This symbol is the offset where the {@link android.R.attr#layout_gravity} attribute's value can be found in the {@link #ActionBarLayout} array. @attr name android:layout_gravity */ public static final int ActionBarLayout_android_layout_gravity = 0; /** These attributes are meant to be specified and customized by the app. The system will read and apply them as needed. These attributes control properties of the activity window, such as whether an action bar should be present and whether it should overlay content. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #ActionBarWindow_windowActionBar com.xioazhe.newsapp:windowActionBar}</code></td><td></td></tr> <tr><td><code>{@link #ActionBarWindow_windowActionBarOverlay com.xioazhe.newsapp:windowActionBarOverlay}</code></td><td></td></tr> <tr><td><code>{@link #ActionBarWindow_windowSplitActionBar com.xioazhe.newsapp:windowSplitActionBar}</code></td><td></td></tr> </table> @see #ActionBarWindow_windowActionBar @see #ActionBarWindow_windowActionBarOverlay @see #ActionBarWindow_windowSplitActionBar */ public static final int[] ActionBarWindow = { 0x7f010000, 0x7f010001, 0x7f010002 }; /** <p>This symbol is the offset where the {@link com.xioazhe.newsapp.R.attr#windowActionBar} attribute's value can be found in the {@link #ActionBarWindow} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.xioazhe.newsapp:windowActionBar */ public static final int ActionBarWindow_windowActionBar = 0; /** <p>This symbol is the offset where the {@link com.xioazhe.newsapp.R.attr#windowActionBarOverlay} attribute's value can be found in the {@link #ActionBarWindow} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.xioazhe.newsapp:windowActionBarOverlay */ public static final int ActionBarWindow_windowActionBarOverlay = 1; /** <p>This symbol is the offset where the {@link com.xioazhe.newsapp.R.attr#windowSplitActionBar} attribute's value can be found in the {@link #ActionBarWindow} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.xioazhe.newsapp:windowSplitActionBar */ public static final int ActionBarWindow_windowSplitActionBar = 2; /** Attributes that can be used with a ActionMenuItemView. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #ActionMenuItemView_android_minWidth android:minWidth}</code></td><td></td></tr> </table> @see #ActionMenuItemView_android_minWidth */ public static final int[] ActionMenuItemView = { 0x0101013f }; /** <p>This symbol is the offset where the {@link android.R.attr#minWidth} attribute's value can be found in the {@link #ActionMenuItemView} array. @attr name android:minWidth */ public static final int ActionMenuItemView_android_minWidth = 0; /** Size of padding on either end of a divider. */ public static final int[] ActionMenuView = { }; /** Attributes that can be used with a ActionMode. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #ActionMode_background com.xioazhe.newsapp:background}</code></td><td> Specifies a background for the action mode bar.</td></tr> <tr><td><code>{@link #ActionMode_backgroundSplit com.xioazhe.newsapp:backgroundSplit}</code></td><td> Specifies a background for the split action mode bar.</td></tr> <tr><td><code>{@link #ActionMode_height com.xioazhe.newsapp:height}</code></td><td> Specifies a fixed height for the action mode bar.</td></tr> <tr><td><code>{@link #ActionMode_subtitleTextStyle com.xioazhe.newsapp:subtitleTextStyle}</code></td><td> Specifies a style to use for subtitle text.</td></tr> <tr><td><code>{@link #ActionMode_titleTextStyle com.xioazhe.newsapp:titleTextStyle}</code></td><td> Specifies a style to use for title text.</td></tr> </table> @see #ActionMode_background @see #ActionMode_backgroundSplit @see #ActionMode_height @see #ActionMode_subtitleTextStyle @see #ActionMode_titleTextStyle */ public static final int[] ActionMode = { 0x7f010022, 0x7f010026, 0x7f010027, 0x7f01002b, 0x7f01002d }; /** <p> @attr description Specifies a background for the action mode bar. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:background */ public static final int ActionMode_background = 3; /** <p> @attr description Specifies a background for the split action mode bar. <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:backgroundSplit */ public static final int ActionMode_backgroundSplit = 4; /** <p> @attr description Specifies a fixed height for the action mode bar. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:height */ public static final int ActionMode_height = 0; /** <p> @attr description Specifies a style to use for subtitle text. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:subtitleTextStyle */ public static final int ActionMode_subtitleTextStyle = 2; /** <p> @attr description Specifies a style to use for title text. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:titleTextStyle */ public static final int ActionMode_titleTextStyle = 1; /** Attrbitutes for a ActivityChooserView. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #ActivityChooserView_expandActivityOverflowButtonDrawable com.xioazhe.newsapp:expandActivityOverflowButtonDrawable}</code></td><td> The drawable to show in the button for expanding the activities overflow popup.</td></tr> <tr><td><code>{@link #ActivityChooserView_initialActivityCount com.xioazhe.newsapp:initialActivityCount}</code></td><td> The maximal number of items initially shown in the activity list.</td></tr> </table> @see #ActivityChooserView_expandActivityOverflowButtonDrawable @see #ActivityChooserView_initialActivityCount */ public static final int[] ActivityChooserView = { 0x7f010066, 0x7f010067 }; /** <p> @attr description The drawable to show in the button for expanding the activities overflow popup. <strong>Note:</strong> Clients would like to set this drawable as a clue about the action the chosen activity will perform. For example, if share activity is to be chosen the drawable should give a clue that sharing is to be performed. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:expandActivityOverflowButtonDrawable */ public static final int ActivityChooserView_expandActivityOverflowButtonDrawable = 1; /** <p> @attr description The maximal number of items initially shown in the activity list. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:initialActivityCount */ public static final int ActivityChooserView_initialActivityCount = 0; /** Attributes that can be used with a CompatTextView. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #CompatTextView_textAllCaps com.xioazhe.newsapp:textAllCaps}</code></td><td> Present the text in ALL CAPS.</td></tr> </table> @see #CompatTextView_textAllCaps */ public static final int[] CompatTextView = { 0x7f010069 }; /** <p> @attr description Present the text in ALL CAPS. This may use a small-caps form when available. <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:textAllCaps */ public static final int CompatTextView_textAllCaps = 0; /** Attributes that can be used with a LinearLayoutICS. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #LinearLayoutICS_divider com.xioazhe.newsapp:divider}</code></td><td> Drawable to use as a vertical divider between buttons.</td></tr> <tr><td><code>{@link #LinearLayoutICS_dividerPadding com.xioazhe.newsapp:dividerPadding}</code></td><td> Size of padding on either end of a divider.</td></tr> <tr><td><code>{@link #LinearLayoutICS_showDividers com.xioazhe.newsapp:showDividers}</code></td><td> Setting for which dividers to show.</td></tr> </table> @see #LinearLayoutICS_divider @see #LinearLayoutICS_dividerPadding @see #LinearLayoutICS_showDividers */ public static final int[] LinearLayoutICS = { 0x7f01002a, 0x7f010051, 0x7f010052 }; /** <p> @attr description Drawable to use as a vertical divider between buttons. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:divider */ public static final int LinearLayoutICS_divider = 0; /** <p> @attr description Size of padding on either end of a divider. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:dividerPadding */ public static final int LinearLayoutICS_dividerPadding = 2; /** <p> @attr description Setting for which dividers to show. <p>Must be one or more (separated by '|') of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>0</td><td></td></tr> <tr><td><code>beginning</code></td><td>1</td><td></td></tr> <tr><td><code>middle</code></td><td>2</td><td></td></tr> <tr><td><code>end</code></td><td>4</td><td></td></tr> </table> <p>This is a private symbol. @attr name com.xioazhe.newsapp:showDividers */ public static final int LinearLayoutICS_showDividers = 1; /** Base attributes that are available to all groups. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #MenuGroup_android_checkableBehavior android:checkableBehavior}</code></td><td> Whether the items are capable of displaying a check mark.</td></tr> <tr><td><code>{@link #MenuGroup_android_enabled android:enabled}</code></td><td> Whether the items are enabled.</td></tr> <tr><td><code>{@link #MenuGroup_android_id android:id}</code></td><td> The ID of the group.</td></tr> <tr><td><code>{@link #MenuGroup_android_menuCategory android:menuCategory}</code></td><td> The category applied to all items within this group.</td></tr> <tr><td><code>{@link #MenuGroup_android_orderInCategory android:orderInCategory}</code></td><td> The order within the category applied to all items within this group.</td></tr> <tr><td><code>{@link #MenuGroup_android_visible android:visible}</code></td><td> Whether the items are shown/visible.</td></tr> </table> @see #MenuGroup_android_checkableBehavior @see #MenuGroup_android_enabled @see #MenuGroup_android_id @see #MenuGroup_android_menuCategory @see #MenuGroup_android_orderInCategory @see #MenuGroup_android_visible */ public static final int[] MenuGroup = { 0x0101000e, 0x010100d0, 0x01010194, 0x010101de, 0x010101df, 0x010101e0 }; /** <p> @attr description Whether the items are capable of displaying a check mark. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#checkableBehavior}. @attr name android:checkableBehavior */ public static final int MenuGroup_android_checkableBehavior = 5; /** <p> @attr description Whether the items are enabled. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#enabled}. @attr name android:enabled */ public static final int MenuGroup_android_enabled = 0; /** <p> @attr description The ID of the group. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#id}. @attr name android:id */ public static final int MenuGroup_android_id = 1; /** <p> @attr description The category applied to all items within this group. (This will be or'ed with the orderInCategory attribute.) <p>This corresponds to the global attribute resource symbol {@link android.R.attr#menuCategory}. @attr name android:menuCategory */ public static final int MenuGroup_android_menuCategory = 3; /** <p> @attr description The order within the category applied to all items within this group. (This will be or'ed with the category attribute.) <p>This corresponds to the global attribute resource symbol {@link android.R.attr#orderInCategory}. @attr name android:orderInCategory */ public static final int MenuGroup_android_orderInCategory = 4; /** <p> @attr description Whether the items are shown/visible. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#visible}. @attr name android:visible */ public static final int MenuGroup_android_visible = 2; /** Base attributes that are available to all Item objects. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #MenuItem_actionLayout com.xioazhe.newsapp:actionLayout}</code></td><td> An optional layout to be used as an action view.</td></tr> <tr><td><code>{@link #MenuItem_actionProviderClass com.xioazhe.newsapp:actionProviderClass}</code></td><td> The name of an optional ActionProvider class to instantiate an action view and perform operations such as default action for that menu item.</td></tr> <tr><td><code>{@link #MenuItem_actionViewClass com.xioazhe.newsapp:actionViewClass}</code></td><td> The name of an optional View class to instantiate and use as an action view.</td></tr> <tr><td><code>{@link #MenuItem_android_alphabeticShortcut android:alphabeticShortcut}</code></td><td> The alphabetic shortcut key.</td></tr> <tr><td><code>{@link #MenuItem_android_checkable android:checkable}</code></td><td> Whether the item is capable of displaying a check mark.</td></tr> <tr><td><code>{@link #MenuItem_android_checked android:checked}</code></td><td> Whether the item is checked.</td></tr> <tr><td><code>{@link #MenuItem_android_enabled android:enabled}</code></td><td> Whether the item is enabled.</td></tr> <tr><td><code>{@link #MenuItem_android_icon android:icon}</code></td><td> The icon associated with this item.</td></tr> <tr><td><code>{@link #MenuItem_android_id android:id}</code></td><td> The ID of the item.</td></tr> <tr><td><code>{@link #MenuItem_android_menuCategory android:menuCategory}</code></td><td> The category applied to the item.</td></tr> <tr><td><code>{@link #MenuItem_android_numericShortcut android:numericShortcut}</code></td><td> The numeric shortcut key.</td></tr> <tr><td><code>{@link #MenuItem_android_onClick android:onClick}</code></td><td> Name of a method on the Context used to inflate the menu that will be called when the item is clicked.</td></tr> <tr><td><code>{@link #MenuItem_android_orderInCategory android:orderInCategory}</code></td><td> The order within the category applied to the item.</td></tr> <tr><td><code>{@link #MenuItem_android_title android:title}</code></td><td> The title associated with the item.</td></tr> <tr><td><code>{@link #MenuItem_android_titleCondensed android:titleCondensed}</code></td><td> The condensed title associated with the item.</td></tr> <tr><td><code>{@link #MenuItem_android_visible android:visible}</code></td><td> Whether the item is shown/visible.</td></tr> <tr><td><code>{@link #MenuItem_showAsAction com.xioazhe.newsapp:showAsAction}</code></td><td> How this item should display in the Action Bar, if present.</td></tr> </table> @see #MenuItem_actionLayout @see #MenuItem_actionProviderClass @see #MenuItem_actionViewClass @see #MenuItem_android_alphabeticShortcut @see #MenuItem_android_checkable @see #MenuItem_android_checked @see #MenuItem_android_enabled @see #MenuItem_android_icon @see #MenuItem_android_id @see #MenuItem_android_menuCategory @see #MenuItem_android_numericShortcut @see #MenuItem_android_onClick @see #MenuItem_android_orderInCategory @see #MenuItem_android_title @see #MenuItem_android_titleCondensed @see #MenuItem_android_visible @see #MenuItem_showAsAction */ public static final int[] MenuItem = { 0x01010002, 0x0101000e, 0x010100d0, 0x01010106, 0x01010194, 0x010101de, 0x010101df, 0x010101e1, 0x010101e2, 0x010101e3, 0x010101e4, 0x010101e5, 0x0101026f, 0x7f010049, 0x7f01004a, 0x7f01004b, 0x7f01004c }; /** <p> @attr description An optional layout to be used as an action view. See {@link android.view.MenuItem#setActionView(android.view.View)} for more info. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:actionLayout */ public static final int MenuItem_actionLayout = 14; /** <p> @attr description The name of an optional ActionProvider class to instantiate an action view and perform operations such as default action for that menu item. See {@link android.view.MenuItem#setActionProvider(android.view.ActionProvider)} for more info. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:actionProviderClass */ public static final int MenuItem_actionProviderClass = 16; /** <p> @attr description The name of an optional View class to instantiate and use as an action view. See {@link android.view.MenuItem#setActionView(android.view.View)} for more info. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:actionViewClass */ public static final int MenuItem_actionViewClass = 15; /** <p> @attr description The alphabetic shortcut key. This is the shortcut when using a keyboard with alphabetic keys. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#alphabeticShortcut}. @attr name android:alphabeticShortcut */ public static final int MenuItem_android_alphabeticShortcut = 9; /** <p> @attr description Whether the item is capable of displaying a check mark. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#checkable}. @attr name android:checkable */ public static final int MenuItem_android_checkable = 11; /** <p> @attr description Whether the item is checked. Note that you must first have enabled checking with the checkable attribute or else the check mark will not appear. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#checked}. @attr name android:checked */ public static final int MenuItem_android_checked = 3; /** <p> @attr description Whether the item is enabled. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#enabled}. @attr name android:enabled */ public static final int MenuItem_android_enabled = 1; /** <p> @attr description The icon associated with this item. This icon will not always be shown, so the title should be sufficient in describing this item. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#icon}. @attr name android:icon */ public static final int MenuItem_android_icon = 0; /** <p> @attr description The ID of the item. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#id}. @attr name android:id */ public static final int MenuItem_android_id = 2; /** <p> @attr description The category applied to the item. (This will be or'ed with the orderInCategory attribute.) <p>This corresponds to the global attribute resource symbol {@link android.R.attr#menuCategory}. @attr name android:menuCategory */ public static final int MenuItem_android_menuCategory = 5; /** <p> @attr description The numeric shortcut key. This is the shortcut when using a numeric (e.g., 12-key) keyboard. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#numericShortcut}. @attr name android:numericShortcut */ public static final int MenuItem_android_numericShortcut = 10; /** <p> @attr description Name of a method on the Context used to inflate the menu that will be called when the item is clicked. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#onClick}. @attr name android:onClick */ public static final int MenuItem_android_onClick = 12; /** <p> @attr description The order within the category applied to the item. (This will be or'ed with the category attribute.) <p>This corresponds to the global attribute resource symbol {@link android.R.attr#orderInCategory}. @attr name android:orderInCategory */ public static final int MenuItem_android_orderInCategory = 6; /** <p> @attr description The title associated with the item. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#title}. @attr name android:title */ public static final int MenuItem_android_title = 7; /** <p> @attr description The condensed title associated with the item. This is used in situations where the normal title may be too long to be displayed. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#titleCondensed}. @attr name android:titleCondensed */ public static final int MenuItem_android_titleCondensed = 8; /** <p> @attr description Whether the item is shown/visible. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#visible}. @attr name android:visible */ public static final int MenuItem_android_visible = 4; /** <p> @attr description How this item should display in the Action Bar, if present. <p>Must be one or more (separated by '|') of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>never</code></td><td>0</td><td> Never show this item in an action bar, show it in the overflow menu instead. Mutually exclusive with "ifRoom" and "always". </td></tr> <tr><td><code>ifRoom</code></td><td>1</td><td> Show this item in an action bar if there is room for it as determined by the system. Favor this option over "always" where possible. Mutually exclusive with "never" and "always". </td></tr> <tr><td><code>always</code></td><td>2</td><td> Always show this item in an actionbar, even if it would override the system's limits of how much stuff to put there. This may make your action bar look bad on some screens. In most cases you should use "ifRoom" instead. Mutually exclusive with "ifRoom" and "never". </td></tr> <tr><td><code>withText</code></td><td>4</td><td> When this item is shown as an action in the action bar, show a text label with it even if it has an icon representation. </td></tr> <tr><td><code>collapseActionView</code></td><td>8</td><td> This item's action view collapses to a normal menu item. When expanded, the action view takes over a larger segment of its container. </td></tr> </table> <p>This is a private symbol. @attr name com.xioazhe.newsapp:showAsAction */ public static final int MenuItem_showAsAction = 13; /** Attributes that can be used with a MenuView. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #MenuView_android_headerBackground android:headerBackground}</code></td><td> Default background for the menu header.</td></tr> <tr><td><code>{@link #MenuView_android_horizontalDivider android:horizontalDivider}</code></td><td> Default horizontal divider between rows of menu items.</td></tr> <tr><td><code>{@link #MenuView_android_itemBackground android:itemBackground}</code></td><td> Default background for each menu item.</td></tr> <tr><td><code>{@link #MenuView_android_itemIconDisabledAlpha android:itemIconDisabledAlpha}</code></td><td> Default disabled icon alpha for each menu item that shows an icon.</td></tr> <tr><td><code>{@link #MenuView_android_itemTextAppearance android:itemTextAppearance}</code></td><td> Default appearance of menu item text.</td></tr> <tr><td><code>{@link #MenuView_android_preserveIconSpacing android:preserveIconSpacing}</code></td><td> Whether space should be reserved in layout when an icon is missing.</td></tr> <tr><td><code>{@link #MenuView_android_verticalDivider android:verticalDivider}</code></td><td> Default vertical divider between menu items.</td></tr> <tr><td><code>{@link #MenuView_android_windowAnimationStyle android:windowAnimationStyle}</code></td><td> Default animations for the menu.</td></tr> </table> @see #MenuView_android_headerBackground @see #MenuView_android_horizontalDivider @see #MenuView_android_itemBackground @see #MenuView_android_itemIconDisabledAlpha @see #MenuView_android_itemTextAppearance @see #MenuView_android_preserveIconSpacing @see #MenuView_android_verticalDivider @see #MenuView_android_windowAnimationStyle */ public static final int[] MenuView = { 0x010100ae, 0x0101012c, 0x0101012d, 0x0101012e, 0x0101012f, 0x01010130, 0x01010131, 0x01010435 }; /** <p> @attr description Default background for the menu header. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#headerBackground}. @attr name android:headerBackground */ public static final int MenuView_android_headerBackground = 4; /** <p> @attr description Default horizontal divider between rows of menu items. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#horizontalDivider}. @attr name android:horizontalDivider */ public static final int MenuView_android_horizontalDivider = 2; /** <p> @attr description Default background for each menu item. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#itemBackground}. @attr name android:itemBackground */ public static final int MenuView_android_itemBackground = 5; /** <p> @attr description Default disabled icon alpha for each menu item that shows an icon. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#itemIconDisabledAlpha}. @attr name android:itemIconDisabledAlpha */ public static final int MenuView_android_itemIconDisabledAlpha = 6; /** <p> @attr description Default appearance of menu item text. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#itemTextAppearance}. @attr name android:itemTextAppearance */ public static final int MenuView_android_itemTextAppearance = 1; /** <p> @attr description Whether space should be reserved in layout when an icon is missing. <p>This is a private symbol. @attr name android:preserveIconSpacing */ public static final int MenuView_android_preserveIconSpacing = 7; /** <p> @attr description Default vertical divider between menu items. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#verticalDivider}. @attr name android:verticalDivider */ public static final int MenuView_android_verticalDivider = 3; /** <p> @attr description Default animations for the menu. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#windowAnimationStyle}. @attr name android:windowAnimationStyle */ public static final int MenuView_android_windowAnimationStyle = 0; /** Attributes that can be used with a SearchView. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #SearchView_android_imeOptions android:imeOptions}</code></td><td> The IME options to set on the query text field.</td></tr> <tr><td><code>{@link #SearchView_android_inputType android:inputType}</code></td><td> The input type to set on the query text field.</td></tr> <tr><td><code>{@link #SearchView_android_maxWidth android:maxWidth}</code></td><td> An optional maximum width of the SearchView.</td></tr> <tr><td><code>{@link #SearchView_iconifiedByDefault com.xioazhe.newsapp:iconifiedByDefault}</code></td><td> The default state of the SearchView.</td></tr> <tr><td><code>{@link #SearchView_queryHint com.xioazhe.newsapp:queryHint}</code></td><td> An optional query hint string to be displayed in the empty query field.</td></tr> </table> @see #SearchView_android_imeOptions @see #SearchView_android_inputType @see #SearchView_android_maxWidth @see #SearchView_iconifiedByDefault @see #SearchView_queryHint */ public static final int[] SearchView = { 0x0101011f, 0x01010220, 0x01010264, 0x7f010056, 0x7f010057 }; /** <p> @attr description The IME options to set on the query text field. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#imeOptions}. @attr name android:imeOptions */ public static final int SearchView_android_imeOptions = 2; /** <p> @attr description The input type to set on the query text field. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#inputType}. @attr name android:inputType */ public static final int SearchView_android_inputType = 1; /** <p> @attr description An optional maximum width of the SearchView. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#maxWidth}. @attr name android:maxWidth */ public static final int SearchView_android_maxWidth = 0; /** <p> @attr description The default state of the SearchView. If true, it will be iconified when not in use and expanded when clicked. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:iconifiedByDefault */ public static final int SearchView_iconifiedByDefault = 3; /** <p> @attr description An optional query hint string to be displayed in the empty query field. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:queryHint */ public static final int SearchView_queryHint = 4; /** Attributes that can be used with a Spinner. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #Spinner_android_dropDownHorizontalOffset android:dropDownHorizontalOffset}</code></td><td> Horizontal offset from the spinner widget for positioning the dropdown in spinnerMode="dropdown".</td></tr> <tr><td><code>{@link #Spinner_android_dropDownSelector android:dropDownSelector}</code></td><td> List selector to use for spinnerMode="dropdown" display.</td></tr> <tr><td><code>{@link #Spinner_android_dropDownVerticalOffset android:dropDownVerticalOffset}</code></td><td> Vertical offset from the spinner widget for positioning the dropdown in spinnerMode="dropdown".</td></tr> <tr><td><code>{@link #Spinner_android_dropDownWidth android:dropDownWidth}</code></td><td> Width of the dropdown in spinnerMode="dropdown".</td></tr> <tr><td><code>{@link #Spinner_android_gravity android:gravity}</code></td><td> Gravity setting for positioning the currently selected item.</td></tr> <tr><td><code>{@link #Spinner_android_popupBackground android:popupBackground}</code></td><td> Background drawable to use for the dropdown in spinnerMode="dropdown".</td></tr> <tr><td><code>{@link #Spinner_disableChildrenWhenDisabled com.xioazhe.newsapp:disableChildrenWhenDisabled}</code></td><td> Whether this spinner should mark child views as enabled/disabled when the spinner itself is enabled/disabled.</td></tr> <tr><td><code>{@link #Spinner_popupPromptView com.xioazhe.newsapp:popupPromptView}</code></td><td> Reference to a layout to use for displaying a prompt in the dropdown for spinnerMode="dropdown".</td></tr> <tr><td><code>{@link #Spinner_prompt com.xioazhe.newsapp:prompt}</code></td><td> The prompt to display when the spinner's dialog is shown.</td></tr> <tr><td><code>{@link #Spinner_spinnerMode com.xioazhe.newsapp:spinnerMode}</code></td><td> Display mode for spinner options.</td></tr> </table> @see #Spinner_android_dropDownHorizontalOffset @see #Spinner_android_dropDownSelector @see #Spinner_android_dropDownVerticalOffset @see #Spinner_android_dropDownWidth @see #Spinner_android_gravity @see #Spinner_android_popupBackground @see #Spinner_disableChildrenWhenDisabled @see #Spinner_popupPromptView @see #Spinner_prompt @see #Spinner_spinnerMode */ public static final int[] Spinner = { 0x010100af, 0x01010175, 0x01010176, 0x01010262, 0x010102ac, 0x010102ad, 0x7f01004d, 0x7f01004e, 0x7f01004f, 0x7f010050 }; /** <p> @attr description Horizontal offset from the spinner widget for positioning the dropdown in spinnerMode="dropdown". <p>This corresponds to the global attribute resource symbol {@link android.R.attr#dropDownHorizontalOffset}. @attr name android:dropDownHorizontalOffset */ public static final int Spinner_android_dropDownHorizontalOffset = 4; /** <p> @attr description List selector to use for spinnerMode="dropdown" display. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#dropDownSelector}. @attr name android:dropDownSelector */ public static final int Spinner_android_dropDownSelector = 1; /** <p> @attr description Vertical offset from the spinner widget for positioning the dropdown in spinnerMode="dropdown". <p>This corresponds to the global attribute resource symbol {@link android.R.attr#dropDownVerticalOffset}. @attr name android:dropDownVerticalOffset */ public static final int Spinner_android_dropDownVerticalOffset = 5; /** <p> @attr description Width of the dropdown in spinnerMode="dropdown". <p>This corresponds to the global attribute resource symbol {@link android.R.attr#dropDownWidth}. @attr name android:dropDownWidth */ public static final int Spinner_android_dropDownWidth = 3; /** <p> @attr description Gravity setting for positioning the currently selected item. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#gravity}. @attr name android:gravity */ public static final int Spinner_android_gravity = 0; /** <p> @attr description Background drawable to use for the dropdown in spinnerMode="dropdown". <p>This corresponds to the global attribute resource symbol {@link android.R.attr#popupBackground}. @attr name android:popupBackground */ public static final int Spinner_android_popupBackground = 2; /** <p> @attr description Whether this spinner should mark child views as enabled/disabled when the spinner itself is enabled/disabled. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:disableChildrenWhenDisabled */ public static final int Spinner_disableChildrenWhenDisabled = 9; /** <p> @attr description Reference to a layout to use for displaying a prompt in the dropdown for spinnerMode="dropdown". This layout must contain a TextView with the id {@code @android:id/text1} to be populated with the prompt text. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:popupPromptView */ public static final int Spinner_popupPromptView = 8; /** <p> @attr description The prompt to display when the spinner's dialog is shown. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:prompt */ public static final int Spinner_prompt = 6; /** <p> @attr description Display mode for spinner options. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>dialog</code></td><td>0</td><td> Spinner options will be presented to the user as a dialog window. </td></tr> <tr><td><code>dropdown</code></td><td>1</td><td> Spinner options will be presented to the user as an inline dropdown anchored to the spinner widget itself. </td></tr> </table> <p>This is a private symbol. @attr name com.xioazhe.newsapp:spinnerMode */ public static final int Spinner_spinnerMode = 7; /** These are the standard attributes that make up a complete theme. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #Theme_actionDropDownStyle com.xioazhe.newsapp:actionDropDownStyle}</code></td><td> Default ActionBar dropdown style.</td></tr> <tr><td><code>{@link #Theme_dropdownListPreferredItemHeight com.xioazhe.newsapp:dropdownListPreferredItemHeight}</code></td><td> The preferred item height for dropdown lists.</td></tr> <tr><td><code>{@link #Theme_listChoiceBackgroundIndicator com.xioazhe.newsapp:listChoiceBackgroundIndicator}</code></td><td> Drawable used as a background for selected list items.</td></tr> <tr><td><code>{@link #Theme_panelMenuListTheme com.xioazhe.newsapp:panelMenuListTheme}</code></td><td> Default Panel Menu style.</td></tr> <tr><td><code>{@link #Theme_panelMenuListWidth com.xioazhe.newsapp:panelMenuListWidth}</code></td><td> Default Panel Menu width.</td></tr> <tr><td><code>{@link #Theme_popupMenuStyle com.xioazhe.newsapp:popupMenuStyle}</code></td><td> Default PopupMenu style.</td></tr> </table> @see #Theme_actionDropDownStyle @see #Theme_dropdownListPreferredItemHeight @see #Theme_listChoiceBackgroundIndicator @see #Theme_panelMenuListTheme @see #Theme_panelMenuListWidth @see #Theme_popupMenuStyle */ public static final int[] Theme = { 0x7f010043, 0x7f010044, 0x7f010045, 0x7f010046, 0x7f010047, 0x7f010048 }; /** <p> @attr description Default ActionBar dropdown style. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:actionDropDownStyle */ public static final int Theme_actionDropDownStyle = 0; /** <p> @attr description The preferred item height for dropdown lists. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:dropdownListPreferredItemHeight */ public static final int Theme_dropdownListPreferredItemHeight = 1; /** <p> @attr description Drawable used as a background for selected list items. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:listChoiceBackgroundIndicator */ public static final int Theme_listChoiceBackgroundIndicator = 5; /** <p> @attr description Default Panel Menu style. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:panelMenuListTheme */ public static final int Theme_panelMenuListTheme = 4; /** <p> @attr description Default Panel Menu width. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:panelMenuListWidth */ public static final int Theme_panelMenuListWidth = 3; /** <p> @attr description Default PopupMenu style. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>This is a private symbol. @attr name com.xioazhe.newsapp:popupMenuStyle */ public static final int Theme_popupMenuStyle = 2; /** Attributes that can be used with a View. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #View_android_focusable android:focusable}</code></td><td> Boolean that controls whether a view can take focus.</td></tr> <tr><td><code>{@link #View_paddingEnd com.xioazhe.newsapp:paddingEnd}</code></td><td> Sets the padding, in pixels, of the end edge; see {@link android.R.attr#padding}.</td></tr> <tr><td><code>{@link #View_paddingStart com.xioazhe.newsapp:paddingStart}</code></td><td> Sets the padding, in pixels, of the start edge; see {@link android.R.attr#padding}.</td></tr> </table> @see #View_android_focusable @see #View_paddingEnd @see #View_paddingStart */ public static final int[] View = { 0x010100da, 0x7f010034, 0x7f010035 }; /** <p> @attr description Boolean that controls whether a view can take focus. By default the user can not move focus to a view; by setting this attribute to true the view is allowed to take focus. This value does not impact the behavior of directly calling {@link android.view.View#requestFocus}, which will always request focus regardless of this view. It only impacts where focus navigation will try to move focus. <p>This corresponds to the global attribute resource symbol {@link android.R.attr#focusable}. @attr name android:focusable */ public static final int View_android_focusable = 0; /** <p> @attr description Sets the padding, in pixels, of the end edge; see {@link android.R.attr#padding}. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:paddingEnd */ public static final int View_paddingEnd = 2; /** <p> @attr description Sets the padding, in pixels, of the start edge; see {@link android.R.attr#padding}. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.xioazhe.newsapp:paddingStart */ public static final int View_paddingStart = 1; }; }
apache-2.0
fengshao0907/hazelcast-simulator
simulator/src/main/java/com/hazelcast/simulator/coordinator/PerformanceMonitor.java
7064
package com.hazelcast.simulator.coordinator; import com.hazelcast.simulator.coordinator.remoting.AgentClient; import com.hazelcast.simulator.coordinator.remoting.AgentsClient; import com.hazelcast.simulator.worker.commands.GetPerformanceStateCommand; import com.hazelcast.simulator.worker.commands.PerformanceState; import com.hazelcast.util.EmptyStatement; import org.apache.log4j.Logger; import java.io.File; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import static com.hazelcast.simulator.utils.CommonUtils.formatDouble; import static com.hazelcast.simulator.utils.CommonUtils.formatLong; import static com.hazelcast.simulator.utils.CommonUtils.sleepSeconds; import static com.hazelcast.simulator.utils.FileUtils.appendText; import static java.lang.String.format; /** * Responsible for collecting performance metrics from the agents and logging/storing it. */ @SuppressWarnings("checkstyle:magicnumber") class PerformanceMonitor { private final PerformanceThread thread; private final AtomicBoolean started = new AtomicBoolean(); PerformanceMonitor(AgentsClient agentsClient) { if (agentsClient == null) { throw new NullPointerException(); } thread = new PerformanceThread(agentsClient); } void start() { if (started.compareAndSet(false, true)) { thread.start(); } } void stop() { if (started.compareAndSet(true, false)) { try { thread.isRunning = false; thread.interrupt(); thread.join(TimeUnit.SECONDS.toMillis(5)); } catch (InterruptedException e) { EmptyStatement.ignore(e); } } } void logDetailedPerformanceInfo() { if (started.get()) { thread.logDetailedPerformanceInfo(); } } String getPerformanceNumbers() { if (started.get()) { return thread.getPerformanceNumbers(); } return ""; } private static class PerformanceThread extends Thread { private static final AtomicBoolean PERFORMANCE_WRITTEN = new AtomicBoolean(); private static final Logger LOGGER = Logger.getLogger(PerformanceMonitor.class); private final ConcurrentMap<AgentClient, PerformanceState> performancePerAgent = new ConcurrentHashMap<AgentClient, PerformanceState>(); private final AgentsClient agentsClient; // throughput in last measurement interval private double intervalThroughput; // overall throughput since test started private double totalThroughput; // total operation count since test started private long totalOperationCount; private volatile boolean isRunning = true; public PerformanceThread(AgentsClient agentsClient) { super("PerformanceThread"); setDaemon(true); this.agentsClient = agentsClient; } @Override public void run() { while (isRunning) { sleepSeconds(1); try { checkPerformance(); } catch (TimeoutException e) { LOGGER.warn("There was a timeout retrieving performance information from the members."); } catch (Exception e) { LOGGER.fatal("Exception in PerformanceThread.run() of PerformanceMonitor", e); } } } private synchronized void checkPerformance() throws TimeoutException { GetPerformanceStateCommand command = new GetPerformanceStateCommand(); Map<AgentClient, List<PerformanceState>> result = agentsClient.executeOnAllWorkersDetailed(command); long tmpTotalOperationCount = 0; double tmpIntervalThroughput = 0; double tmpTotalThroughput = 0; for (Map.Entry<AgentClient, List<PerformanceState>> entry : result.entrySet()) { AgentClient agentClient = entry.getKey(); long operationCountPerAgent = 0; PerformanceState agentPerformance = new PerformanceState(); for (PerformanceState value : entry.getValue()) { if (value != null && !value.isEmpty()) { tmpIntervalThroughput += value.getIntervalThroughput(); tmpTotalThroughput += value.getTotalThroughput(); operationCountPerAgent += value.getOperationCount(); agentPerformance.add(value); } } tmpTotalOperationCount += operationCountPerAgent; performancePerAgent.put(agentClient, agentPerformance); } totalOperationCount = tmpTotalOperationCount; intervalThroughput = tmpIntervalThroughput; totalThroughput = tmpTotalThroughput; } private synchronized void logDetailedPerformanceInfo() { if (!PERFORMANCE_WRITTEN.compareAndSet(false, true)) { return; } if (totalOperationCount < 0) { LOGGER.info("Performance information is not available!"); return; } appendText(totalThroughput + "\n", new File("performance.txt")); if (totalOperationCount > 0) { LOGGER.info(format("Total performance %s%% %s ops %s ops/s", formatDouble(100, 7), formatLong(totalOperationCount, 15), formatDouble(totalThroughput, 15))); } for (Map.Entry<AgentClient, PerformanceState> entry : performancePerAgent.entrySet()) { AgentClient client = entry.getKey(); PerformanceState performancePerAgent = entry.getValue(); double percentage = 0; if (totalOperationCount > 0) { percentage = 100 * (performancePerAgent.getOperationCount() * 1.0d) / totalOperationCount; } LOGGER.info(format(" Agent %-15s %s%% %s ops %s ops/s", client.getPublicAddress(), formatDouble(percentage, 7), formatLong(performancePerAgent.getOperationCount(), 15), formatDouble(performancePerAgent.getTotalThroughput(), 15))); } } private synchronized String getPerformanceNumbers() { if (intervalThroughput < 0) { return " (performance not available)"; } return String.format("%s ops %s ops/s", formatLong(totalOperationCount, 15), formatDouble(intervalThroughput, 15) ); } } }
apache-2.0
catholicon/jackrabbit-oak
oak-lucene/src/test/java/org/apache/jackrabbit/oak/plugins/index/lucene/SecureFacetTest.java
14257
/* * 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.jackrabbit.oak.plugins.index.lucene; import com.google.common.collect.Maps; import com.google.common.io.Closer; import org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils; import org.apache.jackrabbit.oak.Oak; import org.apache.jackrabbit.oak.commons.concurrent.ExecutorCloser; import org.apache.jackrabbit.oak.jcr.Jcr; import org.apache.jackrabbit.oak.plugins.index.lucene.util.IndexDefinitionBuilder; import org.apache.jackrabbit.oak.plugins.index.search.IndexDefinition; import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore; import org.apache.jackrabbit.oak.query.facet.FacetResult; import org.apache.jackrabbit.oak.query.facet.FacetResult.Facet; import org.apache.jackrabbit.oak.spi.commit.Observer; import org.apache.jackrabbit.oak.spi.query.QueryIndexProvider; import org.apache.jackrabbit.oak.spi.state.NodeStore; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import javax.jcr.*; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import javax.jcr.security.Privilege; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.apache.jackrabbit.commons.JcrUtils.getOrCreateByPath; import static org.apache.jackrabbit.oak.InitialContentHelper.INITIAL_CONTENT; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_DEFINITIONS_NODE_TYPE; import static org.apache.jackrabbit.oak.plugins.index.search.FulltextIndexConstants.*; import static org.junit.Assert.*; public class SecureFacetTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(new File("target")); private Closer closer; private Session session; private Node indexNode; private QueryManager qe; private static final int NUM_LEAF_NODES = STATISTICAL_FACET_SAMPLE_SIZE_DEFAULT; private static final int NUM_LABELS = 4; private Map<String, Integer> actualLabelCount = Maps.newHashMap(); private Map<String, Integer> actualAclLabelCount = Maps.newHashMap(); private Map<String, Integer> actualAclPar1LabelCount = Maps.newHashMap(); @Before public void setup() throws Exception { closer = Closer.create(); createRepository(); createIndex(); } private void createRepository() throws RepositoryException, IOException { ExecutorService executorService = Executors.newFixedThreadPool(2); closer.register(new ExecutorCloser(executorService)); IndexCopier copier = new IndexCopier(executorService, temporaryFolder.getRoot()); LuceneIndexEditorProvider editorProvider = new LuceneIndexEditorProvider(copier); LuceneIndexProvider queryIndexProvider = new LuceneIndexProvider(copier); NodeStore nodeStore = new MemoryNodeStore(INITIAL_CONTENT); Oak oak = new Oak(nodeStore) .with((QueryIndexProvider) queryIndexProvider) .with((Observer) queryIndexProvider) .with(editorProvider); Jcr jcr = new Jcr(oak); @NotNull Repository repository = jcr.createRepository(); session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()), null); closer.register(session::logout); // we'd always query anonymously Session anonSession = repository.login(new GuestCredentials()); closer.register(anonSession::logout); qe = anonSession.getWorkspace().getQueryManager(); } @After public void after() throws IOException { closer.close(); IndexDefinition.setDisableStoredIndexDefinition(false); } private void createIndex() throws RepositoryException { IndexDefinitionBuilder idxBuilder = new IndexDefinitionBuilder(); idxBuilder.noAsync().evaluatePathRestrictions() .indexRule("nt:base") .property("cons") .propertyIndex() .property("foo") .getBuilderTree().setProperty(PROP_FACETS, true); indexNode = getOrCreateByPath("/oak:index", "nt:unstructured", session) .addNode("index", INDEX_DEFINITIONS_NODE_TYPE); idxBuilder.build(indexNode); session.save(); } private void createLargeDataset() throws RepositoryException { Random rGen = new Random(42); int[] labelCount = new int[NUM_LABELS]; int[] aclLabelCount = new int[NUM_LABELS]; int[] aclPar1LabelCount = new int[NUM_LABELS]; Node par = allow(getOrCreateByPath("/parent", "oak:Unstructured", session)); for (int i = 0; i < 4; i++) { Node subPar = par.addNode("par" + i); for (int j = 0; j < NUM_LEAF_NODES; j++) { Node child = subPar.addNode("c" + j); child.setProperty("cons", "val"); // Add a random label out of "l0", "l1", "l2", "l3" int labelNum = rGen.nextInt(NUM_LABELS); child.setProperty("foo", "l" + labelNum); labelCount[labelNum]++; if (i != 0) { aclLabelCount[labelNum]++; } if (i == 1) { aclPar1LabelCount[labelNum]++; } } // deny access for one sub-parent if (i == 0) { deny(subPar); } } session.save(); for (int i = 0; i < labelCount.length; i++) { actualLabelCount.put("l" + i, labelCount[i]); actualAclLabelCount.put("l" + i, aclLabelCount[i]); actualAclPar1LabelCount.put("l" + i, aclPar1LabelCount[i]); } assertNotEquals("Acl-ed and actual counts mustn't be same", actualLabelCount, actualAclLabelCount); } @Test public void secureFacets() throws Exception { createLargeDataset(); assertEquals(actualAclLabelCount, getFacets()); } @Test public void secureFacets_withOneLabelInaccessible() throws Exception { createLargeDataset(); Node inaccessibleChild = deny(session.getNode("/parent").addNode("par4")).addNode("c0"); inaccessibleChild.setProperty("cons", "val"); inaccessibleChild.setProperty("foo", "l4"); session.save(); assertEquals(actualAclLabelCount, getFacets()); } @Test public void insecureFacets() throws Exception { Node facetConfig = getOrCreateByPath(indexNode.getPath() + "/" + FACETS, "nt:unstructured", session); facetConfig.setProperty(PROP_SECURE_FACETS, PROP_SECURE_FACETS_VALUE_INSECURE); indexNode.setProperty(PROP_REFRESH_DEFN, true); session.save(); createLargeDataset(); assertEquals(actualLabelCount, getFacets()); } @Test public void statisticalFacets() throws Exception { Node facetConfig = getOrCreateByPath(indexNode.getPath() + "/" + FACETS, "nt:unstructured", session); facetConfig.setProperty(PROP_SECURE_FACETS, PROP_SECURE_FACETS_VALUE_STATISTICAL); indexNode.setProperty(PROP_REFRESH_DEFN, true); session.save(); createLargeDataset(); Map<String, Integer> facets = getFacets(); assertEquals("Unexpected number of facets", actualAclLabelCount.size(), facets.size()); for (Map.Entry<String, Integer> facet : actualAclLabelCount.entrySet()) { String facetLabel = facet.getKey(); int facetCount = facets.get(facetLabel); float ratio = ((float)facetCount) / facet.getValue(); assertTrue("Facet count for label: " + facetLabel + " is outside of 10% margin of error. " + "Expected: " + facet.getValue() + "; Got: " + facetCount + "; Ratio: " + ratio, Math.abs(ratio - 1) < 0.1); } } @Test public void statisticalFacets_withHitCountSameAsSampleSize() throws Exception { Node facetConfig = getOrCreateByPath(indexNode.getPath() + "/" + FACETS, "nt:unstructured", session); facetConfig.setProperty(PROP_SECURE_FACETS, PROP_SECURE_FACETS_VALUE_STATISTICAL); indexNode.setProperty(PROP_REFRESH_DEFN, true); session.save(); createLargeDataset(); Map<String, Integer> facets = getFacets("/parent/par1"); assertEquals("Unexpected number of facets", actualAclPar1LabelCount.size(), facets.size()); for (Map.Entry<String, Integer> facet : actualAclPar1LabelCount.entrySet()) { String facetLabel = facet.getKey(); int facetCount = facets.get(facetLabel); float ratio = ((float)facetCount) / facet.getValue(); assertTrue("Facet count for label: " + facetLabel + " is outside of 10% margin of error. " + "Expected: " + facet.getValue() + "; Got: " + facetCount + "; Ratio: " + ratio, Math.abs(ratio - 1) < 0.1); } } @Test public void statisticalFacets_withOneLabelInaccessible() throws Exception { Node facetConfig = getOrCreateByPath(indexNode.getPath() + "/" + FACETS, "nt:unstructured", session); facetConfig.setProperty(PROP_SECURE_FACETS, PROP_SECURE_FACETS_VALUE_STATISTICAL); indexNode.setProperty(PROP_REFRESH_DEFN, true); session.save(); createLargeDataset(); Node inaccessibleChild = deny(session.getNode("/parent").addNode("par4")).addNode("c0"); inaccessibleChild.setProperty("cons", "val"); inaccessibleChild.setProperty("foo", "l4"); session.save(); Map<String, Integer> facets = getFacets(); assertEquals("Unexpected number of facets", actualAclLabelCount.size(), facets.size()); for (Map.Entry<String, Integer> facet : actualAclLabelCount.entrySet()) { String facetLabel = facet.getKey(); int facetCount = facets.get(facetLabel); float ratio = ((float)facetCount) / facet.getValue(); assertTrue("Facet count for label: " + facetLabel + " is outside of 10% margin of error. " + "Expected: " + facet.getValue() + "; Got: " + facetCount + "; Ratio: " + ratio, Math.abs(ratio - 1) < 0.1); } } @Test public void secureFacets_withAdminSession() throws Exception { Node facetConfig = getOrCreateByPath(indexNode.getPath() + "/" + FACETS, "nt:unstructured", session); facetConfig.setProperty(PROP_SECURE_FACETS, PROP_SECURE_FACETS_VALUE_INSECURE); indexNode.setProperty(PROP_REFRESH_DEFN, true); session.save(); createLargeDataset(); qe = session.getWorkspace().getQueryManager(); assertEquals(actualLabelCount, getFacets()); } @Test public void statisticalFacets_withAdminSession() throws Exception { Node facetConfig = getOrCreateByPath(indexNode.getPath() + "/" + FACETS, "nt:unstructured", session); facetConfig.setProperty(PROP_SECURE_FACETS, PROP_SECURE_FACETS_VALUE_STATISTICAL); indexNode.setProperty(PROP_REFRESH_DEFN, true); session.save(); createLargeDataset(); qe = session.getWorkspace().getQueryManager(); Map<String, Integer> facets = getFacets(); assertEquals("Unexpected number of facets", actualLabelCount.size(), facets.size()); for (Map.Entry<String, Integer> facet : actualLabelCount.entrySet()) { String facetLabel = facet.getKey(); int facetCount = facets.get(facetLabel); float ratio = ((float)facetCount) / facet.getValue(); assertTrue("Facet count for label: " + facetLabel + " is outside of 5% margin of error. " + "Expected: " + facet.getValue() + "; Got: " + facetCount + "; Ratio: " + ratio, Math.abs(ratio - 1) < 0.05); } } private Map<String, Integer> getFacets() throws Exception { return getFacets(null); } private Map<String, Integer> getFacets(String path) throws Exception { Map<String, Integer> map = Maps.newHashMap(); String pathCons = ""; if (path != null) { pathCons = " AND ISDESCENDANTNODE('" + path + "')"; } String query = "SELECT [rep:facet(foo)] FROM [nt:base] WHERE [cons] = 'val'" + pathCons; Query q = qe.createQuery(query, Query.JCR_SQL2); QueryResult queryResult = q.execute(); FacetResult facetResult = new FacetResult(queryResult); Set<String> dims = facetResult.getDimensions(); for (String dim : dims) { List<Facet> facets = facetResult.getFacets(dim); for (Facet facet : facets) { map.put(facet.getLabel(), facet.getCount()); } } return map; } @SuppressWarnings("UnusedReturnValue") private Node deny(Node node) throws RepositoryException { AccessControlUtils.deny(node, "anonymous", Privilege.JCR_ALL); return node; } private Node allow(Node node) throws RepositoryException { AccessControlUtils.allow(node, "anonymous", Privilege.JCR_READ); return node; } }
apache-2.0
flumebase/flumebase
src/main/java/com/odiago/flumebase/exec/FlowInfo.java
2079
/** * Licensed to Odiago, Inc. under one or more contributor license * agreements. See the NOTICE.txt file distributed with this work for * additional information regarding copyright ownership. Odiago, Inc. * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.odiago.flumebase.exec; import com.odiago.flumebase.thrift.TFlowInfo; /** * Status information about a flow to report back to the client. */ public class FlowInfo { /** FlowId of this flow. */ public final FlowId flowId; /** The query that is being executed. */ public final String query; /** Stream name associated with the output of this flow. */ public final String streamName; public FlowInfo(FlowId id, String q, String name) { flowId = id; query = q; streamName = name; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(flowId.getId()); sb.append("\t"); if (null != streamName) { sb.append(streamName); } sb.append("\t"); sb.append(query); return sb.toString(); } public TFlowInfo toThrift() { TFlowInfo out = new TFlowInfo(); out.setFlowId(flowId.toThrift()); out.setQuery(query); out.setStreamName(streamName); return out; } public static FlowInfo fromThrift(TFlowInfo other) { return new FlowInfo(FlowId.fromThrift(other.flowId), other.query, other.streamName); } /** @return the columns associated with our toString() output. */ public static String getHeader() { return "FlowId\tStream\tQuery"; } }
apache-2.0
xuzhongxing/deeplearning4j
deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/paramavg/aggregator/ParameterAveragingAggregationTuple.java
985
package org.deeplearning4j.spark.impl.paramavg.aggregator; import lombok.AllArgsConstructor; import lombok.Data; import org.deeplearning4j.api.storage.Persistable; import org.deeplearning4j.api.storage.StorageMetaData; import org.deeplearning4j.spark.api.stats.SparkTrainingStats; import org.nd4j.linalg.api.ndarray.INDArray; import java.io.Serializable; import java.util.Collection; /** * Simple helper tuple used to execute parameter averaging * * @author Alex Black */ @AllArgsConstructor @Data public class ParameterAveragingAggregationTuple implements Serializable { private final INDArray parametersSum; private final INDArray updaterStateSum; private final double scoreSum; private final int aggregationsCount; private final SparkTrainingStats sparkTrainingStats; private final Collection<StorageMetaData> listenerMetaData; private final Collection<Persistable> listenerStaticInfo; private final Collection<Persistable> listenerUpdates; }
apache-2.0
ViniciusBezerra94/Forum
src/main/java/br/com/forum/model/Postagem.java
774
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.forum.model; /** * * @author vinicius */ public class Postagem { private String nome; private String mensagem; public Postagem(String nome, String mensagem) { this.nome = nome; this.mensagem = mensagem; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getMensagem() { return mensagem; } public void setMensagem(String mensagem) { this.mensagem = mensagem; } }
apache-2.0
nabedge/e-font-size
e-font-size.core/src/main/java/org/mixer2/eclipse/efontsize/core/SampleHandler.java
1006
package org.mixer2.eclipse.efontsize.core; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; /** * Executed by click menu.<br/> */ public class SampleHandler extends AbstractHandler { private final IWorkbenchWindow window; /** * constructor. */ public SampleHandler() { IWorkbench workbench = PlatformUI.getWorkbench(); this.window = workbench.getActiveWorkbenchWindow(); } /** * {@inheritDoc} */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { MessageDialog.openInformation(window.getShell(), "Eclipse Plugin Archetype", "Hello, Maven+Eclipse world,\n e-font-size is built with Tycho"); return null; } }
apache-2.0
Mahfa/AndroidColorPop
demo/src/main/java/com/mahfa/colorpop/demo/GridAdapter.java
3684
package com.mahfa.colorpop.demo; import com.mahfa.colorpop.FragmentInformer; import com.mahfa.colorpop.demo.R; import com.mahfa.colorpop.demo.SecondFragmentList; import android.content.res.Resources; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentTransaction; public class GridAdapter extends BaseAdapter { FragmentActivity fragment_activity; private LayoutInflater layout_inflater; private int app_blue_color; private int app_green_color; private int app_red_color; private int app_amber_color; public GridAdapter(FragmentActivity fragment_activity) { this.fragment_activity = fragment_activity; layout_inflater = LayoutInflater.from(fragment_activity); Resources res = fragment_activity.getResources(); app_blue_color = res.getColor(R.color.app_blue); app_green_color = res.getColor(R.color.app_green); app_red_color = res.getColor(R.color.app_red); app_amber_color = res.getColor(R.color.app_amber); } @Override public int getCount() { return 100; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = layout_inflater.inflate(R.layout.adapter_grid, parent, false); ViewHolder holder = new ViewHolder(); holder.cirlce = (ImageView) convertView.findViewById(R.id.circle); holder.title = (TextView) convertView.findViewById(R.id.title); convertView.setTag(holder); } final int item_color = getItemColor(position); final ViewHolder holder = (ViewHolder) convertView.getTag(); holder.title.setText("Grid Item " + (position + 1)); if (item_color == app_green_color) { holder.cirlce.setImageResource(R.drawable.green_circle); } else if (item_color == app_blue_color) { holder.cirlce.setImageResource(R.drawable.blue_circle); } else if (item_color == app_red_color) { holder.cirlce.setImageResource(R.drawable.red_circle); } else if (item_color == app_amber_color) { holder.cirlce.setImageResource(R.drawable.grey_circle); } convertView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FragmentInformer informer = new FragmentInformer( fragment_activity); informer.setCircleColor(item_color); boolean is_views_behind_status_bar = false; if (android.os.Build.VERSION.SDK_INT >= 19) { is_views_behind_status_bar = true; } informer.setBaseView(holder.cirlce, FragmentInformer.MODE_CENTER, is_views_behind_status_bar); SecondFragmentList fragment = new SecondFragmentList(); informer.informColorPopFragment(fragment); FragmentTransaction transaction = fragment_activity .getSupportFragmentManager().beginTransaction(); transaction.setCustomAnimations(0, R.anim.abc_popup_exit, 0, R.anim.abc_popup_exit); transaction.addToBackStack(null); transaction.add(android.R.id.content, fragment); transaction.commit(); } }); return convertView; } private static class ViewHolder { ImageView cirlce; TextView title; } private int getItemColor(int pos) { if (pos == 1) { return app_green_color; } if (pos % 6 == 0) { return app_amber_color; } else if (pos % 4 == 0) { return app_blue_color; } else if (pos % 3 == 0) { return app_green_color; } return app_red_color; } }
apache-2.0
Ricardo-Lechuga/gnb-wallet
app/src/main/java/es/ujaen/rlc00008/gnbwallet/domain/model/BrandType.java
131
package es.ujaen.rlc00008.gnbwallet.domain.model; /** * Created by Ricardo on 4/6/16. */ public enum BrandType { WISA, YAM }
apache-2.0
RicardoSouzaCarvalho/ICarWash
src/java/br/icarwash/control/SolicitarServico.java
2148
package br.icarwash.control; import br.icarwash.dao.ClienteDAO; import br.icarwash.dao.ClienteEnderecoDAO; import br.icarwash.dao.EnderecoDAO; import br.icarwash.dao.ServicoDAO; import br.icarwash.model.Cliente; import br.icarwash.model.ClienteEndereco; import br.icarwash.model.Endereco; import br.icarwash.model.Usuario; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet(name = "SolicitarServico", urlPatterns = {"/SolicitarServico", "/solicitar-servico"}) public class SolicitarServico extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection conexao = (Connection) request.getAttribute("conexao"); HttpSession session = ((HttpServletRequest) request).getSession(true); Usuario usuario = (Usuario) session.getAttribute("user"); Cliente cliente = new Cliente.ClienteBuilder() .withUsuario(usuario) .build(); cliente = new ClienteDAO(conexao).localizarPorIdUsuario(cliente); ArrayList<ClienteEndereco> clienteEnderecos = new ClienteEnderecoDAO(conexao).selecionaEnderecoPorIdCliente(cliente); ArrayList<Endereco> enderecos = new ArrayList<>(); for (ClienteEndereco clienteEndereco : clienteEnderecos) { enderecos.add(new EnderecoDAO(conexao).localizarPorId(clienteEndereco.getEndereco())); } request.setAttribute("servicos", new ServicoDAO(conexao).listar()); request.setAttribute("enderecos", enderecos); request.setAttribute("taxaMedio", 1.05); request.setAttribute("taxaGrande", 1.10); RequestDispatcher rd = request.getRequestDispatcher("/solicitar_servico.jsp"); rd.forward(request, response); } }
apache-2.0
jGauravGupta/nbmodeler
modeler-impl/src/main/java/org/netbeans/modeler/component/ModelerPanelTopComponent.java
17328
/** * Copyright 2013-2019 Gaurav Gupta * * 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.netbeans.modeler.component; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.KeyListener; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.text.DefaultEditorKit; import org.netbeans.api.visual.widget.Widget; import org.netbeans.modeler.component.save.SaveDiagram; import org.netbeans.modeler.component.save.ui.SaveNotifierYesNo; import org.netbeans.modeler.core.ModelerCore; import org.netbeans.modeler.core.ModelerFile; import org.netbeans.modeler.palette.PaletteSupport; import org.netbeans.modeler.specification.model.DiagramModel; import org.netbeans.modeler.specification.model.document.IModelerScene; import org.netbeans.modeler.specification.model.document.widget.IBaseElementWidget; import org.netbeans.modeler.widget.transferable.cp.WidgetTransferable; import org.netbeans.spi.navigator.NavigatorLookupHint; import org.netbeans.spi.palette.PaletteController; import org.openide.NotifyDescriptor; import org.openide.awt.Toolbar; import org.openide.cookies.SaveCookie; import org.openide.explorer.ExplorerManager; import org.openide.explorer.ExplorerUtils; import org.openide.nodes.Node; import org.openide.util.Lookup; import org.openide.util.NbBundle.Messages; import org.openide.util.actions.CallbackSystemAction; import org.openide.util.actions.SystemAction; import org.openide.util.lookup.AbstractLookup; import org.openide.util.lookup.InstanceContent; import org.openide.util.lookup.ProxyLookup; import org.openide.windows.TopComponent; import org.openide.actions.FindAction; import org.openide.windows.WindowManager; /** * Top component which displays something. */ @TopComponent.Description( preferredID = "ModelerPanelTopComponent", persistenceType = TopComponent.PERSISTENCE_NEVER) @TopComponent.OpenActionRegistration( displayName = "#CTL_ModelerPanelAction", preferredID = "ModelerPanelTopComponent") @Messages({ "CTL_ModelerPanelAction=ModelerPanel", "CTL_ModelerPanelTopComponent=ModelerPanel Window", "HINT_ModelerPanelTopComponent=This is a ModelerPanel window" }) public class ModelerPanelTopComponent extends TopComponent implements ExplorerManager.Provider, IModelerPanel { private ExplorerManager explorerManager; private ModelerFile modelerFile; private IModelerScene modelerScene; private Toolbar editorToolbar; private JScrollPane scrollPane; private SaveDiagram saveCookies; @Override public void init(ModelerFile modelerFile) { saveCookies = new SaveDiagram(modelerFile); this.modelerFile = modelerFile; modelerScene = modelerFile.getModelerDiagramModel().getModelerScene(); this.setName(modelerFile.getName()); this.setIcon(modelerFile.getIcon()); this.setToolTipText(modelerFile.getTooltip()); setFocusable(true); initComponents(); setupActionMap(getActionMap()); initLookup(); } private InstanceContent lookupContent = new InstanceContent(); private Lookup lookup = null; private Lookup exploreLookup; private PaletteController paletteController; @Override public Lookup getLookup() { if (lookup == null) { Lookup[] content = {super.getLookup(), new AbstractLookup(lookupContent)}; lookup = new ProxyLookup(content); } return lookup; } private void initLookup() { explorerManager = new ExplorerManager(); lookupContent.add(exploreLookup = ExplorerUtils.createLookup(explorerManager, getActionMap())); //getActionMap() => setupActionMap(getActionMap()) to apply custom action key // it is commented because KeyAdapter functionality is added for key listener if (!modelerFile.getModelerDiagramModel().getPaletteConfig().getCategoryNodeConfigs().isEmpty()) { lookupContent.add(paletteController = PaletteSupport.createPalette(modelerFile)); } lookupContent.add(modelerFile.getModelerScene()); if (modelerFile.getModelerFileDataObject() != null) { lookupContent.add(modelerFile.getModelerFileDataObject()); } lookupContent.add(getNavigatorCookie()); } private void cleanLookup() { lookupContent.remove(exploreLookup); // if (!modelerFile.getVendorSpecification().getPaletteConfig().getCategoryNodeConfigs().isEmpty()) { // lookupContent.remove(paletteController); // } lookupContent.remove(modelerFile.getModelerScene()); if(modelerFile.getModelerFileDataObject()!=null){ lookupContent.remove(modelerFile.getModelerFileDataObject()); } lookupContent.remove(getNavigatorCookie()); navigatorCookie = null; exploreLookup = null; paletteController = null; } private NavigatorHint navigatorCookie = null; private NavigatorHint getNavigatorCookie() { if (navigatorCookie == null) { navigatorCookie = new NavigatorHint(); } return navigatorCookie; } /** * @return the forceClose */ private boolean isForceClose() { return forceClose; } public class NavigatorHint implements NavigatorLookupHint, Node.Cookie { @Override public String getContentType() { if(ModelerPanelTopComponent.this.getModelerFile().getModelerFileDataObject()==null){ return null; } return ModelerPanelTopComponent.this.getModelerFile().getModelerFileDataObject().getPrimaryFile().getMIMEType(); } } @Override public ExplorerManager getExplorerManager() { return explorerManager; } private ActionMap setupActionMap(javax.swing.ActionMap map) { CallbackSystemAction a = SystemAction.get(FindAction.class); map.put(a.getActionMapKey(), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { modelerFile.getModelerDiagramEngine().searchWidget(); } }); map.put(DefaultEditorKit.copyAction, new javax.swing.AbstractAction() { @Override public void actionPerformed(ActionEvent ev) { WidgetTransferable.copy(modelerScene); } }); map.put(DefaultEditorKit.pasteAction, new javax.swing.AbstractAction() { @Override public void actionPerformed(ActionEvent ev) { Object[] selectedObjects = modelerScene.getSelectedObjects().toArray(); if (selectedObjects.length == 1) { Widget selectedWidget = modelerScene.findWidget(selectedObjects[0]); if (selectedWidget instanceof IBaseElementWidget) { WidgetTransferable.paste((IBaseElementWidget) selectedWidget); } } else { WidgetTransferable.paste((IBaseElementWidget) modelerScene); } } }); return map; } @Override public void initializeToolBar() { SwingUtilities.invokeLater(() -> { modelerFile.getModelerDiagramEngine().buildToolBar(editorToolbar); }); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { setLayout(new java.awt.BorderLayout()); scrollPane = new javax.swing.JScrollPane(); add(scrollPane, java.awt.BorderLayout.CENTER); JScrollBar vertical = scrollPane.getVerticalScrollBar(); vertical.setUnitIncrement(5); InputMap im = vertical.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(KeyStroke.getKeyStroke("DOWN"), "positiveUnitIncrement"); im.put(KeyStroke.getKeyStroke("UP"), "negativeUnitIncrement"); JScrollBar horizontal = scrollPane.getHorizontalScrollBar(); horizontal.setUnitIncrement(5); im = horizontal.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(KeyStroke.getKeyStroke("RIGHT"), "positiveUnitIncrement"); im.put(KeyStroke.getKeyStroke("LEFT"), "negativeUnitIncrement"); editorToolbar = new Toolbar("Diagram Toolbar", false); add(editorToolbar, BorderLayout.NORTH); if (modelerScene.getView() == null) { scrollPane.setViewportView(modelerScene.createView()); } else { scrollPane.setViewportView(modelerScene.getView()); } } @Override public void componentOpened() { super.componentOpened(); } @Override public void componentClosed() { super.componentClosed(); cleanReference(); } private void cleanReference() { if (this.getModelerFile() != null) { ModelerCore.removeModelerFile(this.getModelerFile()); } SwingUtilities.invokeLater(() -> { modelerScene.cleanReference(); for (KeyListener keyListener : this.getKeyListeners()) { this.removeKeyListener(keyListener); } modelerFile.getModelerDiagramEngine().cleanToolBar(editorToolbar); cleanLookup(); if (modelerFile.getModelerFileDataObject() != null) { modelerFile.getModelerFileDataObject().removeSaveCookie(); } modelerFile.setModelerDiagramModel(null); modelerScene.getBaseElements().clear(); modelerScene.setBaseElementSpec(null); System.gc(); }); } @Override public void componentShowing() { //this function is added to handle multiple topcompoent for single file if (modelerFile.getModelerFileDataObject() != null) { if (persistenceState == Boolean.FALSE) { modelerFile.getModelerFileDataObject().addSaveCookie(saveCookies); } else { modelerFile.getModelerFileDataObject().removeSaveCookie(); } } } /** * @return the modelerFile */ @Override public ModelerFile getModelerFile() { return modelerFile; } @Override public int getPersistenceType() { return TopComponent.PERSISTENCE_NEVER; } private static final int RESULT_CANCEL = 0; private static final int RESULT_NO = 1; private static final int RESULT_YES = 2; private boolean forceClose = false; @Override public final void forceClose() { forceClose = true; SwingUtilities.invokeLater(ModelerPanelTopComponent.this::close); } @Override public boolean canClose() { boolean safeToClose = true; if (isForceClose()) { return true; } if (modelerFile.getModelerFileDataObject() == null || modelerFile.getModelerFileDataObject().getCookie(SaveCookie.class) == null || modelerFile.getModelerFileDataObject().getCookie(SaveCookie.class) != this.saveCookies) { modelerScene.destroy(); if (modelerFile.getParentFile() != null) { modelerFile.getParentFile().removeChildrenFile(modelerFile); } return true; } //prompt to save before close switch (saveDiagram()) { case RESULT_YES: modelerFile.save(); break; case RESULT_NO: if(modelerFile.getModelerFileDataObject()!=null) modelerFile.getModelerFileDataObject().setDirty(false, saveCookies); break; case RESULT_CANCEL: safeToClose = false; break; } if (safeToClose) { modelerScene.destroy(); if (modelerFile.getParentFile() != null) { modelerFile.getParentFile().removeChildrenFile(modelerFile); } } return safeToClose; } private void setDiagramDisplayName(final String name) { SwingUtilities.invokeLater(() -> { setDisplayName(name); }); } private int saveDiagram() { DiagramModel diagram = this.getModelerFile().getModelerDiagramModel().getDiagramModel(); String title = "Save Diagram"; // NOI18N int result; Object response = SaveNotifierYesNo.getDefault().displayNotifier( title, diagram.getName(), this.getModelerFile().getName()); if (response == SaveNotifierYesNo.SAVE_ALWAYS_OPTION) { result = RESULT_YES; } else if (response == NotifyDescriptor.YES_OPTION) { result = RESULT_YES; } else if (response == NotifyDescriptor.NO_OPTION) { result = RESULT_NO; } else // cancel or closed (x button) { result = RESULT_CANCEL; } return result; } private boolean persistenceState = true; private final static String SPACE_STAR = " *"; @Override public void changePersistenceState(boolean state) { if (modelerFile.getModelerFileDataObject() == null || persistenceState == state) { return; } String diagramName = modelerFile.getName(); String displayName; persistenceState = state; if (persistenceState == Boolean.FALSE) { displayName = /*"<b>" + */ diagramName + SPACE_STAR/* +"</b>"*/; modelerFile.getModelerFileDataObject().addSaveCookie(saveCookies); } else { displayName = diagramName; modelerFile.getModelerFileDataObject().removeSaveCookie(); } this.setDiagramDisplayName(displayName); } @Override public boolean isPersistenceState() { return persistenceState; } private static void handlePropertyPanelEvent() { TopComponent.getRegistry().addPropertyChangeListener(evt -> { String property = evt.getPropertyName(); Object oldValue = evt.getOldValue(); Object newValue = evt.getNewValue(); if (property.equals(TopComponent.Registry.PROP_ACTIVATED)) { if((oldValue instanceof TopComponent.Cloneable)//MultiViewCloneableTopComponent && newValue instanceof ModelerPanelTopComponent) { openPropertyPanel(); } else if((oldValue instanceof ModelerPanelTopComponent) && newValue instanceof ModelerPanelTopComponent) { //ignore } else if(oldValue instanceof ModelerPanelTopComponent && newValue instanceof TopComponent.Cloneable) { closePropertyPanel(); } } else if (property.equals(TopComponent.Registry.PROP_TC_OPENED)) { if(newValue instanceof ModelerPanelTopComponent) { openPropertyPanel(); } } else if (property.equals(TopComponent.Registry.PROP_TC_CLOSED)) { if(newValue instanceof ModelerPanelTopComponent) { closePropertyPanel(); } } }); } private static void openPropertyPanel() { TopComponent propertyWindow = WindowManager.getDefault().findTopComponent("properties"); // NOI18N try { if (!propertyWindow.isOpened()) { propertyWindow.open(); propertyWindow.requestActive(); } } catch (Exception ex) { // ignore } } private static void closePropertyPanel() { TopComponent propertyWindow = WindowManager.getDefault().findTopComponent("properties"); // NOI18N if (propertyWindow.isOpened()) { propertyWindow.close(); } } static { handlePropertyPanelEvent(); } }
apache-2.0
dhaval0129/PSAlgs
src/main/java/com/psalgs/dp/MinimumCostPath.java
1523
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.psalgs.dp; /** * * @author djoshi * * Reference: * http://www.geeksforgeeks.org/dynamic-programming-set-6-min-cost-path/ */ public class MinimumCostPath { /* A utility function that returns minimum of 3 integers */ private static int min(int x, int y, int z) { if (x < y) { return (x < z) ? x : z; } else { return (y < z) ? y : z; } } private static int minCost(int cost[][], int m, int n) { int tc[][] = new int[m + 1][n + 1]; tc[0][0] = cost[0][0]; /* Initialize first column of total cost(tc) array */ for (int i = 1; i <= m; i++) { tc[i][0] = tc[i - 1][0] + cost[i][0]; } /* Initialize first row of tc array */ for (int j = 1; j <= n; j++) { tc[0][j] = tc[0][j - 1] + cost[0][j]; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { tc[i][j] = min(tc[i - 1][j - 1], tc[i - 1][j], tc[i][j - 1]) + cost[i][j]; } } return tc[m][n]; } public static void main(String args[]) { int cost[][] = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; System.out.println("minimum cost to reach (2,2) = " + minCost(cost, 2, 2)); } }
apache-2.0
lokling/AndroiditoJZ
emsclient/src/main/java/no/java/ems/client/android/model/Event.java
339
package no.java.ems.client.android.model; import java.net.URI; public class Event extends EMSBaseEntity { public static final String SESSION_COLLECTION = "session collection"; public Event(Item item) { super(item); } public URI getSessionHref() { return super.getLink(SESSION_COLLECTION).href; } }
apache-2.0
daedric/buck
src/com/facebook/buck/cli/UninstallCommand.java
6514
/* * Copyright 2012-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.android.AdbHelper; import com.facebook.buck.android.HasInstallableApk; import com.facebook.buck.event.ConsoleEvent; import com.facebook.buck.json.BuildFileParseException; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetException; import com.facebook.buck.parser.NoSuchBuildTargetException; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.TargetGraphAndBuildTargets; import com.facebook.buck.step.AdbOptions; import com.facebook.buck.step.ExecutionContext; import com.facebook.buck.step.TargetDeviceOptions; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.MoreExceptions; import com.facebook.infer.annotation.SuppressFieldNotInitialized; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; import java.io.IOException; import java.util.List; public class UninstallCommand extends AbstractCommand { public static class UninstallOptions { @VisibleForTesting static final String KEEP_LONG_ARG = "--keep"; @VisibleForTesting static final String KEEP_SHORT_ARG = "-k"; @Option( name = KEEP_LONG_ARG, aliases = { KEEP_SHORT_ARG }, usage = "Keep user data when uninstalling.") private boolean keepData = false; public boolean shouldKeepUserData() { return keepData; } } @AdditionalOptions @SuppressFieldNotInitialized private UninstallOptions uninstallOptions; @AdditionalOptions @SuppressFieldNotInitialized private AdbCommandLineOptions adbOptions; @AdditionalOptions @SuppressFieldNotInitialized private TargetDeviceCommandLineOptions deviceOptions; @Argument private List<String> arguments = Lists.newArrayList(); public List<String> getArguments() { return arguments; } public UninstallOptions uninstallOptions() { return uninstallOptions; } public AdbOptions adbOptions(BuckConfig buckConfig) { return adbOptions.getAdbOptions(buckConfig); } public TargetDeviceOptions targetDeviceOptions() { return deviceOptions.getTargetDeviceOptions(); } @Override public int runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException { // Parse all of the build targets specified by the user. BuildRuleResolver resolver; ImmutableSet<BuildTarget> buildTargets; try (CommandThreadManager pool = new CommandThreadManager( "Uninstall", getConcurrencyLimit(params.getBuckConfig()))) { TargetGraphAndBuildTargets result = params.getParser() .buildTargetGraphForTargetNodeSpecs( params.getBuckEventBus(), params.getCell(), getEnableParserProfiling(), pool.getExecutor(), parseArgumentsAsTargetNodeSpecs( params.getBuckConfig(), getArguments()), /* ignoreBuckAutodepsFiles */ false); buildTargets = result.getBuildTargets(); resolver = Preconditions.checkNotNull( params.getActionGraphCache().getActionGraph( params.getBuckEventBus(), params.getBuckConfig().isActionGraphCheckingEnabled(), result.getTargetGraph(), params.getBuckConfig().getKeySeed()) ).getResolver(); } catch (BuildTargetException | BuildFileParseException e) { params.getBuckEventBus().post(ConsoleEvent.severe( MoreExceptions.getHumanReadableOrLocalizedMessage(e))); return 1; } // Make sure that only one build target is specified. if (buildTargets.size() != 1) { params.getBuckEventBus().post(ConsoleEvent.severe( "Must specify exactly one android_binary() rule.")); return 1; } BuildTarget buildTarget = Iterables.get(buildTargets, 0); // Find the android_binary() rule from the parse. BuildRule buildRule; try { buildRule = resolver.requireRule(buildTarget); } catch (NoSuchBuildTargetException e) { throw new HumanReadableException(e.getHumanReadableErrorMessage()); } if (!(buildRule instanceof HasInstallableApk)) { params.getBuckEventBus().post(ConsoleEvent.severe(String.format( "Specified rule %s must be of type android_binary() or apk_genrule() but was %s().\n", buildRule.getFullyQualifiedName(), buildRule.getType()))); return 1; } HasInstallableApk hasInstallableApk = (HasInstallableApk) buildRule; // We need this in case adb isn't already running. try (ExecutionContext context = createExecutionContext(params)) { final AdbHelper adbHelper = new AdbHelper( adbOptions(params.getBuckConfig()), targetDeviceOptions(), context, params.getConsole(), params.getBuckEventBus(), params.getBuckConfig().getRestartAdbOnFailure()); // Find application package name from manifest and uninstall from matching devices. SourcePathResolver pathResolver = new SourcePathResolver(new SourcePathRuleFinder(resolver)); String appId = AdbHelper.tryToExtractPackageNameFromManifest( pathResolver, hasInstallableApk.getApkInfo()); return adbHelper.uninstallApp( appId, uninstallOptions().shouldKeepUserData() ) ? 0 : 1; } } @Override public String getShortDescription() { return "uninstalls an APK"; } @Override public boolean isReadOnly() { return false; } }
apache-2.0
fujiazhiyu/PrimaryCalculator
pc/src/main/java/entity/ExpRec.java
1515
package entity; /** * Created by Bruce-Jiang on 2016/10/17. * 联合实体 */ public class ExpRec { /** * 用户编号 */ private int uId; /** * 表达式ID */ private int eId; /** * 表达式 */ private String exp; /** * 用户给出的答案 */ private String result; /** * 正确答案 */ private String pResult; /** * 做题次数 */ private int num; public ExpRec(){} public ExpRec(int uId, int eId,String exp,String result,String pResult, int num){ this.eId = eId; this.uId = uId; this.exp = exp; this.pResult = pResult; this.result = result; this.num = num; } public int getuId() { return uId; } public void setuId(int uId) { this.uId = uId; } public int geteId() { return eId; } public void seteId(int eId) { this.eId = eId; } public String getExp() { return exp; } public void setExp(String exp) { this.exp = exp; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getpResult() { return pResult; } public void setpResult(String pResult) { this.pResult = pResult; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } }
apache-2.0
nvoron23/incubator-calcite
core/src/test/java/net/hydromatic/optiq/test/TableInRootSchemaTest.java
5978
/* * 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 net.hydromatic.optiq.test; import net.hydromatic.linq4j.*; import net.hydromatic.optiq.*; import net.hydromatic.optiq.impl.AbstractTableQueryable; import net.hydromatic.optiq.impl.java.AbstractQueryableTable; import net.hydromatic.optiq.jdbc.OptiqConnection; import net.hydromatic.optiq.rules.java.EnumerableConvention; import net.hydromatic.optiq.rules.java.JavaRules; import org.eigenbase.rel.RelNode; import org.eigenbase.relopt.RelOptTable; import org.eigenbase.reltype.RelDataType; import org.eigenbase.reltype.RelDataTypeFactory; import org.eigenbase.util.Pair; import com.google.common.collect.ImmutableMultiset; import org.junit.Test; import java.sql.*; import java.util.*; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; public class TableInRootSchemaTest { /** Test case for issue 85, "Adding a table to the root schema causes breakage * in OptiqPrepareImpl". */ @Test public void testAddingTableInRootSchema() throws Exception { Class.forName("net.hydromatic.optiq.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:calcite:"); OptiqConnection optiqConnection = connection.unwrap(OptiqConnection.class); optiqConnection.getRootSchema().add("SAMPLE", new SimpleTable()); Statement statement = optiqConnection.createStatement(); ResultSet resultSet = statement.executeQuery("select A, SUM(B) from SAMPLE group by A"); assertThat( ImmutableMultiset.of( "A=foo; EXPR$1=8", "A=bar; EXPR$1=4"), equalTo(OptiqAssert.toSet(resultSet))); final ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); assertThat(resultSetMetaData.getColumnName(1), equalTo("A")); assertThat(resultSetMetaData.getTableName(1), equalTo("SAMPLE")); assertThat(resultSetMetaData.getSchemaName(1), nullValue()); // Per JDBC, column name should be null. But DBUnit requires every column // to have a name, so the driver uses the label. assertThat(resultSetMetaData.getColumnName(2), equalTo("EXPR$1")); assertThat(resultSetMetaData.getTableName(2), nullValue()); assertThat(resultSetMetaData.getSchemaName(2), nullValue()); resultSet.close(); statement.close(); connection.close(); } public static class SimpleTable extends AbstractQueryableTable implements TranslatableTable { private String[] columnNames = { "A", "B" }; private Class[] columnTypes = { String.class, Integer.class }; private Object[][] rows = new Object[3][]; SimpleTable() { super(Object[].class); rows[0] = new Object[] { "foo", 5 }; rows[1] = new Object[] { "bar", 4 }; rows[2] = new Object[] { "foo", 3 }; } public RelDataType getRowType(RelDataTypeFactory typeFactory) { int columnCount = columnNames.length; final List<Pair<String, RelDataType>> columnDesc = new ArrayList<Pair<String, RelDataType>>(columnCount); for (int i = 0; i < columnCount; i++) { final RelDataType colType = typeFactory .createJavaType(columnTypes[i]); columnDesc.add(Pair.of(columnNames[i], colType)); } return typeFactory.createStructType(columnDesc); } public Iterator<Object[]> iterator() { return Linq4j.enumeratorIterator(enumerator()); } public Enumerator<Object[]> enumerator() { return enumeratorImpl(null); } public <T> Queryable<T> asQueryable(QueryProvider queryProvider, SchemaPlus schema, String tableName) { return new AbstractTableQueryable<T>(queryProvider, schema, this, tableName) { public Enumerator<T> enumerator() { //noinspection unchecked return (Enumerator<T>) enumeratorImpl(null); } }; } private Enumerator<Object[]> enumeratorImpl(final int[] fields) { return new Enumerator<Object[]>() { private Object[] current; private Iterator<Object[]> iterator = Arrays.asList(rows) .iterator(); public Object[] current() { return current; } public boolean moveNext() { if (iterator.hasNext()) { Object[] full = iterator.next(); current = fields != null ? convertRow(full) : full; return true; } else { current = null; return false; } } public void reset() { throw new UnsupportedOperationException(); } public void close() { // noop } private Object[] convertRow(Object[] full) { final Object[] objects = new Object[fields.length]; for (int i = 0; i < fields.length; i++) { objects[i] = full[fields[i]]; } return objects; } }; } // keep public RelNode toRel(RelOptTable.ToRelContext context, RelOptTable relOptTable) { return new JavaRules.EnumerableTableAccessRel(context.getCluster(), context.getCluster().traitSetOf(EnumerableConvention.INSTANCE), relOptTable, (Class) getElementType()); } } } // End TableInRootSchemaTest.java
apache-2.0
davidkarlsen/mycila
mycila-testing-plugins/mycila-testing-db/src/test/java/com/mycila/testing/plugin/db/DatabasePluginUsage.java
3111
/** * Copyright (C) 2008 Mathieu Carbou <mathieu.carbou@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mycila.testing.plugin.db; import com.mycila.testing.core.MycilaTesting; import com.mycila.testing.plugin.db.api.Db; import com.mycila.testing.plugin.db.api.DbDataSource; import com.mycila.testing.plugin.db.api.SqlResults; import com.mycila.testing.testng.MycilaTestNGTest; import org.h2.Driver; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import javax.sql.DataSource; /** * @author Mathieu Carbou (mathieu.carbou@gmail.com) */ public final class DatabasePluginUsage extends MycilaTestNGTest { static { MycilaTesting.debug(); } @DbDataSource(driver = Driver.class, url = "jdbc:h2:file:./target/db") DataSource dataSource; @DbDataSource(driver = Driver.class, url = "jdbc:h2:file:./target/db") Db db; @BeforeClass public void setup() throws Exception { assertNotNull(dataSource); db.runScript("/create.sql"); } @Test public void test_insert() throws Exception { db .prepare("INSERT INTO PERSON VALUES('1', 'math', 'M')").commit() .prepare("INSERT INTO PERSON VALUES('2', 'cassie', 'F')").commit(); System.out.println(db.prepare("select * from person;").query()); } @Test public void test_complex_requests() throws Exception { db.prepare("INSERT INTO PERSON VALUES(?, ?, ?)") .setInt(1, 10).setString(2, "complex1").setString(3, "F").push() .setInt(1, 11).setString(2, "complex2").setString(3, "M").commit() .prepare("INSERT INTO PERSON VALUES(?, ?, ?)") .setInt(1, 13).setString(2, "complex3").setString(3, "F").push() .rollback(); System.out.println(db.prepare("select * from person;").query()); } @Test public void test_batch() throws Exception { db.newBatch() .add("INSERT INTO PERSON VALUES('5', 'jello', 'M')") .add("INSERT INTO PERSON VALUES('6', 'jelly', 'F')") .addScript("/insert.sql") .commit() .newBatch() .add("INSERT INTO PERSON VALUES('7', 'jella', 'F')") .rollback(); System.out.println(db.prepare("select * from person;").query()); } @Test public void test_select() throws Exception { SqlResults sqlResults = db.prepare("SELECT ID, NAME, SEX as S FROM PERSON").query(); System.out.println(sqlResults); } }
apache-2.0
nafae/developer
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201308/LineItemOperationError.java
4444
/** * LineItemOperationError.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.v201308; /** * Lists all errors for executing operations on line items */ public class LineItemOperationError extends com.google.api.ads.dfp.axis.v201308.ApiError implements java.io.Serializable { /* The error reason represented by an enum. */ private com.google.api.ads.dfp.axis.v201308.LineItemOperationErrorReason reason; public LineItemOperationError() { } public LineItemOperationError( java.lang.String fieldPath, java.lang.String trigger, java.lang.String errorString, java.lang.String apiErrorType, com.google.api.ads.dfp.axis.v201308.LineItemOperationErrorReason reason) { super( fieldPath, trigger, errorString, apiErrorType); this.reason = reason; } /** * Gets the reason value for this LineItemOperationError. * * @return reason * The error reason represented by an enum. */ public com.google.api.ads.dfp.axis.v201308.LineItemOperationErrorReason getReason() { return reason; } /** * Sets the reason value for this LineItemOperationError. * * @param reason * The error reason represented by an enum. */ public void setReason(com.google.api.ads.dfp.axis.v201308.LineItemOperationErrorReason reason) { this.reason = reason; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof LineItemOperationError)) return false; LineItemOperationError other = (LineItemOperationError) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.reason==null && other.getReason()==null) || (this.reason!=null && this.reason.equals(other.getReason()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getReason() != null) { _hashCode += getReason().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(LineItemOperationError.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "LineItemOperationError")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("reason"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "reason")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "LineItemOperationError.Reason")); 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); } }
apache-2.0
tntim96/closure-compiler
test/com/google/javascript/jscomp/Es6ToEs3ConverterTest.java
66631
/* * Copyright 2014 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; /** * Test case for {@link Es6ToEs3Converter}. * * @author tbreisacher@google.com (Tyler Breisacher) */ public final class Es6ToEs3ConverterTest extends CompilerTestCase { private static final String EXTERNS_BASE = LINE_JOINER.join( "/**", " * @param {...*} var_args", " * @return {*}", " */", "Function.prototype.apply = function(var_args) {};", "", "/**", " * @param {...*} var_args", " * @return {*}", " */", "Function.prototype.call = function(var_args) {};", "", "function Object() {}", "Object.defineProperties;", "", // Stub out just enough of es6_runtime.js to satisfy the typechecker. // In a real compilation, the entire library will be loaded by // the InjectEs6RuntimeLibrary pass. "$jscomp.copyProperties = function(x,y) {};", "$jscomp.inherits = function(x,y) {};"); private LanguageMode languageOut; @Override public void setUp() { setAcceptedLanguage(LanguageMode.ECMASCRIPT6); languageOut = LanguageMode.ECMASCRIPT3; enableAstValidation(true); disableTypeCheck(); runTypeCheckAfterProcessing = true; compareJsDoc = true; } @Override protected CompilerOptions getOptions() { CompilerOptions options = super.getOptions(); options.setLanguageOut(languageOut); return options; } protected final PassFactory makePassFactory( String name, final CompilerPass pass) { return new PassFactory(name, true/* one-time pass */) { @Override protected CompilerPass create(AbstractCompiler compiler) { return pass; } }; } @Override public CompilerPass getProcessor(final Compiler compiler) { PhaseOptimizer optimizer = new PhaseOptimizer(compiler, null, null); optimizer.addOneTimePass( makePassFactory("Es6RenameVariablesInParamLists", new Es6RenameVariablesInParamLists(compiler))); optimizer.addOneTimePass( makePassFactory("es6ConvertSuper", new Es6ConvertSuper(compiler))); optimizer.addOneTimePass( makePassFactory("convertEs6", new Es6ToEs3Converter(compiler))); optimizer.addOneTimePass( makePassFactory("Es6RewriteLetConst", new Es6RewriteLetConst(compiler))); return optimizer; } @Override protected int getNumRepetitions() { return 1; } public void testObjectLiteralStringKeysWithNoValue() { test("var x = {a, b};", "var x = {a: a, b: b};"); } public void testClassGenerator() { test( "class C { *foo() { yield 1; } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C.prototype.foo = function*() { yield 1;};")); } public void testClassStatement() { test("class C { }", "/** @constructor @struct */ var C = function() {};"); test( "class C { constructor() {} }", "/** @constructor @struct */ var C = function() {};"); test( "class C { method() {}; }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C.prototype.method = function() {};")); test( "class C { constructor(a) { this.a = a; } }", "/** @constructor @struct */ var C = function(a) { this.a = a; };"); test( "class C { constructor() {} foo() {} }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C.prototype.foo = function() {};")); test( "class C { constructor() {}; foo() {}; bar() {} }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C.prototype.foo = function() {};", "C.prototype.bar = function() {};")); test( "class C { foo() {}; bar() {} }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C.prototype.foo = function() {};", "C.prototype.bar = function() {};")); test( LINE_JOINER.join( "class C {", " constructor(a) { this.a = a; }", "", " foo() { console.log(this.a); }", "", " bar() { alert(this.a); }", "}"), LINE_JOINER.join( "/** @constructor @struct */", "var C = function(a) { this.a = a; };", "C.prototype.foo = function() { console.log(this.a); };", "C.prototype.bar = function() { alert(this.a); };")); } public void testClassWithNgInject() { test( "class A { /** @ngInject */ constructor($scope) {} }", "/** @constructor @struct @ngInject */ var A = function($scope) {}"); test( "/** @ngInject */ class A { constructor($scope) {} }", "/** @constructor @struct @ngInject */ var A = function($scope) {}"); } public void testAnonymousSuper() { testError("f(class extends D { f() { super.g() } })", Es6ToEs3Converter.CANNOT_CONVERT); } public void testClassWithJsDoc() { test("class C { }", "/** @constructor @struct */ var C = function() { };"); test( "/** @deprecated */ class C { }", "/** @constructor @struct @deprecated */ var C = function() {};"); test( "/** @dict */ class C { }", "/** @constructor @dict */ var C = function() {};"); } public void testInterfaceWithJsDoc() { test( LINE_JOINER.join( "/**", " * Converts Xs to Ys.", " * @interface", " */", "class Converter {", " /**", " * @param {X} x", " * @return {Y}", " */", " convert(x) {}", "}"), LINE_JOINER.join( "/**", " * Converts Xs to Ys.", " * @interface", " */", "var Converter = function() { };", "", "/**", " * @param {X} x", " * @return {Y}", " */", "Converter.prototype.convert = function(x) {};")); } public void testCtorWithJsDoc() { test( "class C { /** @param {boolean} b */ constructor(b) {} }", LINE_JOINER.join( "/**", " * @param {boolean} b", " * @constructor", " * @struct", " */", "var C = function(b) {};")); } public void testMemberWithJsDoc() { test( "class C { /** @param {boolean} b */ foo(b) {} }", LINE_JOINER.join( "/**", " * @constructor", " * @struct", " */", "var C = function() {};", "", "/** @param {boolean} b */", "C.prototype.foo = function(b) {};")); } public void testClassStatementInsideIf() { test( "if (foo) { class C { } }", "if (foo) { /** @constructor @struct */ var C = function() {}; }"); test( "if (foo) class C {}", "if (foo) { /** @constructor @struct */ var C = function() {}; }"); } /** * Class expressions that are the RHS of a 'var' statement. */ public void testClassExpressionInVar() { test("var C = class { }", "/** @constructor @struct */ var C = function() {}"); test( "var C = class { foo() {} }", LINE_JOINER.join( "/** @constructor @struct */ var C = function() {}", "", "C.prototype.foo = function() {}")); test("var C = class C { }", "/** @constructor @struct */ var C = function() {}"); test( "var C = class C { foo() {} }", LINE_JOINER.join( "/** @constructor @struct */ var C = function() {}", "", "C.prototype.foo = function() {};")); } /** * Class expressions that are the RHS of an assignment. */ public void testClassExpressionInAssignment() { // TODO (mattloring) update these tests for unique renaming (CL in review) test("goog.example.C = class { }", "/** @constructor @struct */ goog.example.C = function() {}"); test( "goog.example.C = class { foo() {} }", LINE_JOINER.join( "/** @constructor @struct */ goog.example.C = function() {}", "goog.example.C.prototype.foo = function() {};")); } /** * Class expressions that are not in a 'var' or simple 'assign' node. * We don't bother transpiling these cases because the transpiled code * will be very difficult to typecheck. */ public void testClassExpression() { enableAstValidation(false); testError("var C = new (class {})();", Es6ToEs3Converter.CANNOT_CONVERT); testError("var C = new (foo || (foo = class { }))();", Es6ToEs3Converter.CANNOT_CONVERT); testError("(condition ? obj1 : obj2).prop = class C { };", Es6ToEs3Converter.CANNOT_CONVERT); } public void testExtends() { compareJsDoc = false; test( "class D {} class C extends D {}", LINE_JOINER.join( "/** @constructor @struct */", "var D = function() {};", "/** @constructor @struct @extends {D} */", "var C = function(var_args) { D.apply(this, arguments); };", "$jscomp.copyProperties(C, D);", "$jscomp.inherits(C, D);")); test( "class D {} class C extends D { constructor() { super(); } }", LINE_JOINER.join( "/** @constructor @struct */", "var D = function() {};", "/** @constructor @struct @extends {D} */", "var C = function() {", " D.call(this);", "}", "$jscomp.copyProperties(C, D);", "$jscomp.inherits(C, D);")); test( "class D {} class C extends D { constructor(str) { super(str); } }", LINE_JOINER.join( "/** @constructor @struct */", "var D = function() {};", "/** @constructor @struct @extends {D} */", "var C = function(str) { ", " D.call(this, str);", "}", "$jscomp.copyProperties(C, D);", "$jscomp.inherits(C, D);")); test( "class C extends ns.D { }", LINE_JOINER.join( "/** @constructor @struct @extends {ns.D} */", "var C = function(var_args) { ns.D.apply(this, arguments); };", "$jscomp.copyProperties(C, ns.D);", "$jscomp.inherits(C, ns.D);")); } public void testInvalidExtends() { testError("class C extends foo() {}", Es6ToEs3Converter.DYNAMIC_EXTENDS_TYPE); testError("class C extends function(){} {}", Es6ToEs3Converter.DYNAMIC_EXTENDS_TYPE); testError("class A {}; class B {}; class C extends (foo ? A : B) {}", Es6ToEs3Converter.DYNAMIC_EXTENDS_TYPE); } public void testExtendsInterface() { test( LINE_JOINER.join( "/** @interface */", "class D {", " f() {}", "}", "/** @interface */", "class C extends D {", " g() {}", "}"), LINE_JOINER.join( "/** @interface */", "var D = function() {};", "D.prototype.f = function() {};", "/** @interface @extends{D} */", "var C = function(var_args) { D.apply(this, arguments); };", "C.prototype.g = function() {};")); } public void testImplementsInterface() { test( LINE_JOINER.join( "/** @interface */", "class D {", " f() {}", "}", "/** @implements {D} */", "class C {", " f() {console.log('hi');}", "}"), LINE_JOINER.join( "/** @interface */", "var D = function() {};", "D.prototype.f = function() {};", "/** @constructor @struct @implements{D} */", "var C = function() {};", "C.prototype.f = function() {console.log('hi');};")); } public void testSuperCall() { compareJsDoc = false; test( "class D {} class C extends D { constructor() { super(); } }", LINE_JOINER.join( "/** @constructor @struct */", "var D = function() {};", "/** @constructor @struct @extends {D} */", "var C = function() {", " D.call(this);", "}", "$jscomp.copyProperties(C, D);", "$jscomp.inherits(C, D);")); test( "class D {} class C extends D { constructor(str) { super(str); } }", LINE_JOINER.join( "/** @constructor @struct */", "var D = function() {}", "/** @constructor @struct @extends {D} */", "var C = function(str) {", " D.call(this,str);", "}", "$jscomp.copyProperties(C, D);", "$jscomp.inherits(C, D);")); test( LINE_JOINER.join( "class D {}", "class C extends D {", " constructor() { }", " foo() { return super.foo(); }", "}"), LINE_JOINER.join( "/** @constructor @struct */", "var D = function() {}", "/** @constructor @struct @extends {D} */", "var C = function() { }", "$jscomp.copyProperties(C, D);", "$jscomp.inherits(C, D);", "C.prototype.foo = function() {", " return D.prototype.foo.call(this);", "}")); test( LINE_JOINER.join( "class D {}", "class C extends D {", " constructor() {}", " foo(bar) { return super.foo(bar); }", "}"), LINE_JOINER.join( "/** @constructor @struct */", "var D = function() {}", "/** @constructor @struct @extends {D} */", "var C = function() {};", "$jscomp.copyProperties(C, D);", "$jscomp.inherits(C, D);", "C.prototype.foo = function(bar) {", " return D.prototype.foo.call(this, bar);", "}")); testError("class C { constructor() { super(); } }", Es6ConvertSuper.NO_SUPERTYPE); testError("class C { f() { super(); } }", Es6ConvertSuper.NO_SUPERTYPE); testError("class C { static f() { super(); } }", Es6ConvertSuper.NO_SUPERTYPE); test( "class C { method() { class D extends C { constructor() { super(); }}}}", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {}", "C.prototype.method = function() {", " /** @constructor @struct @extends{C} */", " var D = function() {", " C.call(this);", " }", " $jscomp.copyProperties(D, C);", " $jscomp.inherits(D, C);", "};")); testError("var i = super();", Es6ConvertSuper.NO_SUPERTYPE); test( "class D {} class C extends D { constructor() {}; f() {super();} }", LINE_JOINER.join( "/** @constructor @struct */", "var D = function() {};", "/** @constructor @struct @extends {D} */", "var C = function() {}", "$jscomp.copyProperties(C, D);", "$jscomp.inherits(C, D);", "C.prototype.f = function() {", " D.prototype.f.call(this);", "}")); } public void testMultiNameClass() { test("var F = class G {}", "/** @constructor @struct */ var F = function() {};"); test("F = class G {}", "/** @constructor @struct */ F = function() {};"); } public void testClassNested() { test( "class C { f() { class D {} } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C.prototype.f = function() {", " /** @constructor @struct */", " var D = function() {}", "};")); compareJsDoc = false; test( "class C { f() { class D extends C {} } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C.prototype.f = function() {", " /** @constructor @struct @extends{C} */", " var D = function(var_args) { C.apply(this, arguments); };", " $jscomp.copyProperties(D, C);", " $jscomp.inherits(D, C);", "};")); } public void testSuperGet() { testError("class D {} class C extends D { f() {var i = super.c;} }", Es6ToEs3Converter.CANNOT_CONVERT_YET); testError("class D {} class C extends D { static f() {var i = super.c;} }", Es6ToEs3Converter.CANNOT_CONVERT_YET); testError("class D {} class C extends D { f() {var i; i = super[s];} }", Es6ToEs3Converter.CANNOT_CONVERT_YET); testError("class D {} class C extends D { f() {return super.s;} }", Es6ToEs3Converter.CANNOT_CONVERT_YET); testError("class D {} class C extends D { f() {m(super.s);} }", Es6ToEs3Converter.CANNOT_CONVERT_YET); testError( "class D {} class C extends D { foo() { return super.m.foo(); } }", Es6ToEs3Converter.CANNOT_CONVERT_YET); testError( "class D {} class C extends D { static foo() { return super.m.foo(); } }", Es6ToEs3Converter.CANNOT_CONVERT_YET); } public void testSuperNew() { testError("class D {} class C extends D { f() {var s = new super;} }", Es6ToEs3Converter.CANNOT_CONVERT_YET); testError("class D {} class C extends D { f(str) {var s = new super(str);} }", Es6ToEs3Converter.CANNOT_CONVERT_YET); } public void testSuperSpread() { test( LINE_JOINER.join( "class D {}", "class C extends D {", " constructor(args) {", " super(...args)", " }", "}"), LINE_JOINER.join( "/** @constructor @struct */", "var D = function(){};", "/** @constructor @struct @extends {D} */", "var C=function(args) {", " D.call.apply(D, [].concat([this], args));", "};", "$jscomp.copyProperties(C,D);", "$jscomp.inherits(C,D);")); } public void testSuperCallNonConstructor() { compareJsDoc = false; test( "class S extends B { static f() { super(); } }", LINE_JOINER.join( "/** @constructor @struct @extends {B} */", "var S = function(var_args) { B.apply(this, arguments); };", "$jscomp.copyProperties(S, B);", "$jscomp.inherits(S, B);", "/** @this {?} */", "S.f=function() { B.f.call(this) }")); test( "class S extends B { f() { super(); } }", LINE_JOINER.join( "/** @constructor @struct @extends {B} */", "var S = function(var_args) { B.apply(this, arguments); };", "$jscomp.copyProperties(S, B);", "$jscomp.inherits(S, B);", "S.prototype.f=function() {", " B.prototype.f.call(this);", "}")); } public void testStaticThis() { test( "class F { static f() { return this; } }", LINE_JOINER.join( "/** @constructor @struct */ var F = function() {}", "/** @this {?} */ F.f = function() { return this; };")); } public void testStaticMethods() { test("class C { static foo() {} }", "/** @constructor @struct */ var C = function() {}; C.foo = function() {};"); test("class C { static foo() {}; foo() {} }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "", "C.foo = function() {};", "", "C.prototype.foo = function() {};")); test("class C { static foo() {}; bar() { C.foo(); } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "", "C.foo = function() {};", "", "C.prototype.bar = function() { C.foo(); };")); } public void testStaticInheritance() { compareJsDoc = false; test( LINE_JOINER.join( "class D {", " static f() {}", "}", "class C extends D { constructor() {} }", "C.f();"), LINE_JOINER.join( "/** @constructor @struct */", "var D = function() {};", "D.f = function () {};", "/** @constructor @struct @extends{D} */", "var C = function() {};", "$jscomp.copyProperties(C, D);", "$jscomp.inherits(C, D);", "C.f();")); test( LINE_JOINER.join( "class D {", " static f() {}", "}", "class C extends D {", " constructor() {}", " f() {}", "}", "C.f();"), LINE_JOINER.join( "/** @constructor @struct */", "var D = function() {};", "D.f = function() {};", "/** @constructor @struct @extends{D} */", "var C = function() { };", "$jscomp.copyProperties(C, D);", "$jscomp.inherits(C, D);", "C.prototype.f = function() {};", "C.f();")); test( LINE_JOINER.join( "class D {", " static f() {}", "}", "class C extends D {", " constructor() {}", " static f() {}", " g() {}", "}"), LINE_JOINER.join( "/** @constructor @struct */", "var D = function() {};", "D.f = function() {};", "/** @constructor @struct @extends{D} */", "var C = function() { };", "$jscomp.copyProperties(C, D);", "$jscomp.inherits(C, D);", "C.f = function() {};", "C.prototype.g = function() {};")); } public void testMockingInFunction() { // Classes cannot be reassigned in function scope. testError("function f() { class C {} C = function() {};}", Es6ToEs3Converter.CLASS_REASSIGNMENT); } // Make sure we don't crash on this code. // https://github.com/google/closure-compiler/issues/752 public void testGithub752() { testError("function f() { var a = b = class {};}", Es6ToEs3Converter.CANNOT_CONVERT); testError("var ns = {}; function f() { var self = ns.Child = class {};}", Es6ToEs3Converter.CANNOT_CONVERT); } public void testArrowInClass() { test( LINE_JOINER.join( "class C {", " constructor() {", " this.counter = 0;", " }", "", " init() {", " document.onclick = () => this.logClick();", " }", "", " logClick() {", " this.counter++;", " }", "}"), LINE_JOINER.join( "/**", " * @constructor", " * @struct", " */", "var C = function() { this.counter = 0; };", "", "C.prototype.init = function() {", " /** @const */ var $jscomp$this = this;", " document.onclick = function() { return $jscomp$this.logClick(); }", "};", "", "C.prototype.logClick = function() {", " this.counter++;", "}")); } public void testInvalidClassUse() { enableTypeCheck(CheckLevel.WARNING); compareJsDoc = false; test( EXTERNS_BASE, LINE_JOINER.join( "/** @constructor @struct */", "function Foo() {}", "Foo.prototype.f = function() {};", "class Sub extends Foo {}", "(new Sub).f();"), LINE_JOINER.join( "/** @constructor @struct */", "function Foo() {}", "Foo.prototype.f = function() {};", "/** @constructor @struct @extends {Foo} */", "var Sub=function(var_args) { Foo.apply(this, arguments); }", "$jscomp.copyProperties(Sub, Foo);", "$jscomp.inherits(Sub, Foo);", "(new Sub).f();"), null, null); test( EXTERNS_BASE, LINE_JOINER.join( "/** @constructor @struct */", "function Foo() {}", "Foo.f = function() {};", "class Sub extends Foo {}", "Sub.f();"), null, null, TypeCheck.INEXISTENT_PROPERTY); test( EXTERNS_BASE, LINE_JOINER.join( "/** @constructor */", "function Foo() {}", "Foo.f = function() {};", "class Sub extends Foo {}"), LINE_JOINER.join( "function Foo(){}Foo.f=function(){};", "var Sub=function(var_args){Foo.apply(this,arguments)};", "$jscomp.copyProperties(Sub,Foo);", "$jscomp.inherits(Sub,Foo)"), null, null); } /** * Getters and setters are supported, both in object literals and in classes, but only * if the output language is ES5. */ public void testEs5GettersAndSettersClasses() { languageOut = LanguageMode.ECMASCRIPT5; test( "class C { get value() { return 0; } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "/** @type {?} */", "C.prototype.value;", "Object.defineProperties(C.prototype, {", " value: {", " /** @this {C} */", " get: function() {", " return 0;", " }", " }", "});")); test( "class C { set value(val) { this.internalVal = val; } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "/** @type {?} */", "C.prototype.value;", "Object.defineProperties(C.prototype, {", " value: {", " /** @this {C} */", " set: function(val) {", " this.internalVal = val;", " }", " }", "});")); test( LINE_JOINER.join( "class C {", " set value(val) {", " this.internalVal = val;", " }", " get value() {", " return this.internalVal;", " }", "}"), LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "/** @type {?} */", "C.prototype.value;", "Object.defineProperties(C.prototype, {", " value: {", " /** @this {C} */", " set: function(val) {", " this.internalVal = val;", " },", " /** @this {C} */", " get: function() {", " return this.internalVal;", " }", " }", "});")); test( LINE_JOINER.join( "class C {", " get alwaysTwo() {", " return 2;", " }", "", " get alwaysThree() {", " return 3;", " }", "}"), LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "/** @type {?} */", "C.prototype.alwaysTwo;", "/** @type {?} */", "C.prototype.alwaysThree;", "Object.defineProperties(C.prototype, {", " alwaysTwo: {", " /** @this {C} */", " get: function() {", " return 2;", " }", " },", " alwaysThree: {", " /** @this {C} */", " get: function() {", " return 3;", " }", " },", "});")); } /** * Check that the types from the getter/setter are copied to the declaration on the prototype. */ public void testEs5GettersAndSettersClassesWithTypes() { languageOut = LanguageMode.ECMASCRIPT5; test( "class C { /** @return {number} */ get value() { return 0; } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "/** @type {number} */", "C.prototype.value;", "Object.defineProperties(C.prototype, {", " value: {", " /**", " * @return {number}", " * @this {C}", " */", " get: function() {", " return 0;", " }", " }", "});")); test( "class C { /** @param {string} v */ set value(v) { } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "/** @type {string} */", "C.prototype.value;", "Object.defineProperties(C.prototype, {", " value: {", " /**", " * @this {C}", " * @param {string} v", " */", " set: function(v) {}", " }", "});")); testError( LINE_JOINER.join( "class C {", " /** @return {string} */", " get value() { }", "", " /** @param {number} v */", " set value(v) { }", "}"), Es6ToEs3Converter.CONFLICTING_GETTER_SETTER_TYPE); } public void testClassEs5GetterSetterIncorrectTypes() { enableTypeCheck(CheckLevel.WARNING); languageOut = LanguageMode.ECMASCRIPT5; // Using @type instead of @return on a getter. test( EXTERNS_BASE, "class C { /** @type {string} */ get value() { } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "/** @type {?} */", "C.prototype.value;", "Object.defineProperties(C.prototype, {", " value: {", " /** @type {string} */", " get: function() {}", " }", "});"), null, TypeValidator.TYPE_MISMATCH_WARNING); // Using @type instead of @param on a setter. test( EXTERNS_BASE, "class C { /** @type {string} */ set value(v) { } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "/** @type {?} */", "C.prototype.value;", "Object.defineProperties(C.prototype, {", " value: {", " /** @type {string} */", " set: function(v) {}", " }", "});"), null, TypeValidator.TYPE_MISMATCH_WARNING); } /** * @bug 20536614 */ public void testStaticGetterSetter() { languageOut = LanguageMode.ECMASCRIPT5; testError("class C { static get foo() {} }", Es6ToEs3Converter.CANNOT_CONVERT_YET); testError("class C { static set foo(x) {} }", Es6ToEs3Converter.CANNOT_CONVERT_YET); } /** * Computed property getters and setters in classes are not supported. */ public void testClassComputedPropGetterSetter() { languageOut = LanguageMode.ECMASCRIPT5; testError("class C { get [foo]() {}}", Es6ToEs3Converter.CANNOT_CONVERT); testError("class C { set [foo](val) {}}", Es6ToEs3Converter.CANNOT_CONVERT); } /** * ES5 getters and setters should report an error if the languageOut is ES3. */ public void testEs5GettersAndSetters_es3() { testError("var x = { get y() {} };", Es6ToEs3Converter.CANNOT_CONVERT); testError("var x = { set y(value) {} };", Es6ToEs3Converter.CANNOT_CONVERT); } /** * ES5 getters and setters on object literals should be left alone if the languageOut is ES5. */ public void testEs5GettersAndSettersObjLit_es5() { languageOut = LanguageMode.ECMASCRIPT5; testSame("var x = { get y() {} };"); testSame("var x = { set y(value) {} };"); } public void testArrowFunction() { test("var f = x => { return x+1; };", "var f = function(x) { return x+1; };"); test("var odds = [1,2,3,4].filter((n) => n%2 == 1);", "var odds = [1,2,3,4].filter(function(n) { return n%2 == 1; });"); test("var f = x => x+1;", "var f = function(x) { return x+1; };"); test( "var f = () => this;", LINE_JOINER.join( "/** @const */ var $jscomp$this = this;", "var f = function() { return $jscomp$this; };")); test( "var f = x => { this.needsBinding(); return 0; };", LINE_JOINER.join( "/** @const */ var $jscomp$this = this;", "var f = function(x) {", " $jscomp$this.needsBinding();", " return 0;", "};")); test( "var f = x => { this.init(); this.doThings(); this.done(); };", LINE_JOINER.join( "/** @const */ var $jscomp$this = this;", "var f = function(x) {", " $jscomp$this.init();", " $jscomp$this.doThings();", " $jscomp$this.done();", "};")); test( "switch(a) { case b: (() => { this; })(); }", LINE_JOINER.join( "switch(a) {", " case b:", " /** @const */ var $jscomp$this = this;", " (function() { $jscomp$this; })();", "}")); } public void testMultipleArrowsInSameScope() { test( "var a1 = x => x+1; var a2 = x => x-1;", "var a1 = function(x) { return x+1; }; var a2 = function(x) { return x-1; };"); test( "function f() { var a1 = x => x+1; var a2 = x => x-1; }", LINE_JOINER.join( "function f() {", " var a1 = function(x) { return x+1; };", " var a2 = function(x) { return x-1; };", "}")); test( "function f() { var a1 = () => this.x; var a2 = () => this.y; }", LINE_JOINER.join( "function f() {", " /** @const */ var $jscomp$this = this;", " var a1 = function() { return $jscomp$this.x; };", " var a2 = function() { return $jscomp$this.y; };", "}")); test( "var a = [1,2,3,4]; var b = a.map(x => x+1).map(x => x*x);", LINE_JOINER.join( "var a = [1,2,3,4];", "var b = a.map(function(x) { return x+1; }).map(function(x) { return x*x; });")); test( LINE_JOINER.join( "function f() {", " var a = [1,2,3,4];", " var b = a.map(x => x+1).map(x => x*x);", "}"), LINE_JOINER.join( "function f() {", " var a = [1,2,3,4];", " var b = a.map(function(x) { return x+1; }).map(function(x) { return x*x; });", "}")); } public void testArrowNestedScope() { test( LINE_JOINER.join( "var outer = {", " f: function() {", " var a1 = () => this.x;", " var inner = {", " f: function() {", " var a2 = () => this.y;", " }", " };", " }", "}"), LINE_JOINER.join( "var outer = {", " f: function() {", " /** @const */ var $jscomp$this = this;", " var a1 = function() { return $jscomp$this.x; }", " var inner = {", " f: function() {", " /** @const */ var $jscomp$this = this;", " var a2 = function() { return $jscomp$this.y; }", " }", " };", " }", "}")); test( LINE_JOINER.join( "function f() {", " var setup = () => {", " function Foo() { this.x = 5; }", " this.f = new Foo;", " }", "}"), LINE_JOINER.join( "function f() {", " /** @const */ var $jscomp$this = this;", " var setup = function() {", " function Foo() { this.x = 5; }", " $jscomp$this.f = new Foo;", " }", "}")); } public void testArrowception() { test("var f = x => y => x+y;", "var f = function(x) {return function(y) { return x+y; }; };"); } public void testArrowceptionWithThis() { test( "var f = (x => { var g = (y => { this.foo(); }) });", LINE_JOINER.join( "/** @const */ var $jscomp$this = this;", "var f = function(x) {", " var g = function(y) {", " $jscomp$this.foo();", " }", "}")); } public void testDefaultParameters() { enableTypeCheck(CheckLevel.WARNING); test( "var x = true; function f(a=x) { var x = false; return a; }", LINE_JOINER.join( "var x = true;", "function f(a) {", " a = (a === undefined) ? x : a;", " var x$0 = false;", " return a;", "}")); test( "function f(zero, one = 1, two = 2) {}; f(1); f(1,2,3);", LINE_JOINER.join( "function f(zero, one, two) {", " one = (one === undefined) ? 1 : one;", " two = (two === undefined) ? 2 : two;", "};", "f(1); f(1,2,3);")); test( "function f(zero, one = 1, two = 2) {}; f();", LINE_JOINER.join( "function f(zero, one, two) {", " one = (one === undefined) ? 1 : one;", " two = (two === undefined) ? 2 : two;", "}; f();"), null, TypeCheck.WRONG_ARGUMENT_COUNT); } public void testDefaultUndefinedParameters() { enableTypeCheck(CheckLevel.WARNING); test("function f(zero, one=undefined) {}", "function f(zero, one) {}"); test("function f(zero, one=void 42) {}", "function f(zero, one) {}"); test("function f(zero, one=void(42)) {}", "function f(zero, one) {}"); test("function f(zero, one=void '\\x42') {}", "function f(zero, one) {}"); test( "function f(zero, one='undefined') {}", "function f(zero, one) { one = (one === undefined) ? 'undefined' : one; }"); test( "function f(zero, one=void g()) {}", "function f(zero, one) { one = (one === undefined) ? void g() : one; }"); } public void testRestParameter() { test( "function f(...zero) {}", "function f(zero) { zero = [].slice.call(arguments, 0); }"); test( "function f(zero, ...one) {}", "function f(zero, one) { one = [].slice.call(arguments, 1); }"); test( "function f(zero, one, ...two) {}", "function f(zero, one, two) { two = [].slice.call(arguments, 2); }"); } public void testDefaultAndRestParameters() { test( "function f(zero, one = 1, ...two) {}", LINE_JOINER.join( "function f(zero, one, two) {", " one = (one === undefined) ? 1 : one;", " two = [].slice.call(arguments, 2);", "}")); } public void testForOf() { compareJsDoc = false; // With array literal and declaring new bound variable. test( "for (var i of [1,2,3]) { console.log(i); }", LINE_JOINER.join( "for (var $jscomp$iter$0 = $jscomp.makeIterator([1,2,3]),", " $jscomp$key$i = $jscomp$iter$0.next();", " !$jscomp$key$i.done; $jscomp$key$i = $jscomp$iter$0.next()) {", " var i = $jscomp$key$i.value;", " console.log(i);", "}")); // With simple assign instead of var declaration in bound variable. test( "for (i of [1,2,3]) { console.log(i); }", LINE_JOINER.join( "for (var $jscomp$iter$0 = $jscomp.makeIterator([1,2,3]),", " $jscomp$key$i = $jscomp$iter$0.next();", " !$jscomp$key$i.done; $jscomp$key$i = $jscomp$iter$0.next()) {", " i = $jscomp$key$i.value;", " console.log(i);", "}")); // With name instead of array literal. test( "for (var i of arr) { console.log(i); }", LINE_JOINER.join( "for (var $jscomp$iter$0 = $jscomp.makeIterator(arr),", " $jscomp$key$i = $jscomp$iter$0.next();", " !$jscomp$key$i.done; $jscomp$key$i = $jscomp$iter$0.next()) {", " var i = $jscomp$key$i.value;", " console.log(i);", "}")); // With no block in for loop body. test( "for (var i of [1,2,3]) console.log(i);", LINE_JOINER.join( "for (var $jscomp$iter$0 = $jscomp.makeIterator([1,2,3]),", " $jscomp$key$i = $jscomp$iter$0.next();", " !$jscomp$key$i.done; $jscomp$key$i = $jscomp$iter$0.next()) {", " var i = $jscomp$key$i.value;", " console.log(i);", "}")); // Iteration var shadows an outer var () test( "var i = 'outer'; for (let i of [1, 2, 3]) { alert(i); } alert(i);", LINE_JOINER.join( "var i = 'outer';", "for (var $jscomp$iter$0 = $jscomp.makeIterator([1,2,3]),", " $jscomp$key$i = $jscomp$iter$0.next();", " !$jscomp$key$i.done; $jscomp$key$i = $jscomp$iter$0.next()) {", " var i$1 = $jscomp$key$i.value;", " alert(i$1);", "}", "alert(i);")); } public void testDestructuringForOf() { test( "for ({x} of y) { console.log(x); }", LINE_JOINER.join( "for (var $jscomp$iter$0 = $jscomp.makeIterator(y),", " $jscomp$key$$jscomp$destructuring$var0 = $jscomp$iter$0.next();", " !$jscomp$key$$jscomp$destructuring$var0.done;", " $jscomp$key$$jscomp$destructuring$var0 = $jscomp$iter$0.next()) {", " var $jscomp$destructuring$var0 = $jscomp$key$$jscomp$destructuring$var0.value;", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0;", " x = $jscomp$destructuring$var1.x", " console.log(x);", "}")); } public void testSpreadArray() { test("var arr = [1, 2, ...mid, 4, 5];", "var arr = [].concat([1, 2], mid, [4, 5]);"); test("var arr = [1, 2, ...mid(), 4, 5];", "var arr = [].concat([1, 2], mid(), [4, 5]);"); test("var arr = [1, 2, ...mid, ...mid2(), 4, 5];", "var arr = [].concat([1, 2], mid, mid2(), [4, 5]);"); test("var arr = [...mid()];", "var arr = [].concat(mid());"); test("f(1, [2, ...mid, 4], 5);", "f(1, [].concat([2], mid, [4]), 5);"); test("function f() { return [...arguments]; };", "function f() { return [].concat(arguments); };"); test("function f() { return [...arguments, 2]; };", "function f() { return [].concat(arguments, [2]); };"); } public void testSpreadCall() { test("f(...arr);", "f.apply(null, [].concat(arr));"); test("f(0, ...g());", "f.apply(null, [].concat([0], g()));"); test("f(...arr, 1);", "f.apply(null, [].concat(arr, [1]));"); test("f(0, ...g(), 2);", "f.apply(null, [].concat([0], g(), [2]));"); test("obj.m(...arr);", "obj.m.apply(obj, [].concat(arr));"); test("x.y.z.m(...arr);", "x.y.z.m.apply(x.y.z, [].concat(arr));"); test("f(a, ...b, c, ...d, e);", "f.apply(null, [].concat([a], b, [c], d, [e]));"); test("new F(...args);", "new Function.prototype.bind.apply(F, [].concat(args));"); test("Factory.create().m(...arr);", LINE_JOINER.join( "var $jscomp$spread$args0;", "($jscomp$spread$args0 = Factory.create()).m.apply($jscomp$spread$args0, [].concat(arr));" )); test("var x = b ? Factory.create().m(...arr) : null;", LINE_JOINER.join( "var $jscomp$spread$args0;", "var x = b ? ($jscomp$spread$args0 = Factory.create()).m.apply($jscomp$spread$args0, ", " [].concat(arr)) : null;")); test("getF()(...args);", "getF().apply(null, [].concat(args));"); test( "F.c().m(...a); G.d().n(...b);", LINE_JOINER.join( "var $jscomp$spread$args0;", "($jscomp$spread$args0 = F.c()).m.apply($jscomp$spread$args0,", " [].concat(a));", "var $jscomp$spread$args1;", "($jscomp$spread$args1 = G.d()).n.apply($jscomp$spread$args1,", " [].concat(b));")); enableTypeCheck(CheckLevel.WARNING); test( EXTERNS_BASE, LINE_JOINER.join( "class C {}", "class Factory {", " /** @return {C} */", " static create() {return new C()}", "}", "var arr = [1,2]", "Factory.create().m(...arr);"), null, null, TypeCheck.INEXISTENT_PROPERTY); test(EXTERNS_BASE, LINE_JOINER.join( "class C { m(a) {} }", "class Factory {", " /** @return {C} */", " static create() {return new C()}", "}", "var arr = [1,2]", "Factory.create().m(...arr);" ), LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C.prototype.m = function(a) {};", "/** @constructor @struct */", "var Factory = function() {};", "/** @return {C} */", "Factory.create = function() {return new C()};", "var arr = [1,2]", "var $jscomp$spread$args0;", "($jscomp$spread$args0 = Factory.create()).m.apply($jscomp$spread$args0, [].concat(arr));" ), null, null); } public void testArrowFunctionInObject() { test("var obj = { f: () => 'bar' };", "var obj = { f: function() { return 'bar'; } };"); } public void testMethodInObject() { test("var obj = { f() {alert(1); } };", "var obj = { f: function() {alert(1); } };"); test( "var obj = { f() { alert(1); }, x };", "var obj = { f: function() { alert(1); }, x: x };"); } public void testComputedPropertiesWithMethod() { test( "var obj = { ['f' + 1]: 1, m() {}, ['g' + 1]: 1, };", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "var obj = ($jscomp$compprop0['f' + 1] = 1,", " ($jscomp$compprop0.m = function() {}, ", " ($jscomp$compprop0['g' + 1] = 1, $jscomp$compprop0)));")); } public void testComputedProperties() { test( "var obj = { ['f' + 1] : 1, ['g' + 1] : 1 };", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "var obj = ($jscomp$compprop0['f' + 1] = 1,", " ($jscomp$compprop0['g' + 1] = 1, $jscomp$compprop0));")); test( "var obj = { ['f'] : 1};", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "var obj = ($jscomp$compprop0['f'] = 1,", " $jscomp$compprop0);")); test( "var o = { ['f'] : 1}; var p = { ['g'] : 1};", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "var o = ($jscomp$compprop0['f'] = 1,", " $jscomp$compprop0);", "var $jscomp$compprop1 = {};", "var p = ($jscomp$compprop1['g'] = 1,", " $jscomp$compprop1);")); test( "({['f' + 1] : 1})", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "($jscomp$compprop0['f' + 1] = 1,", " $jscomp$compprop0)")); test( "({'a' : 2, ['f' + 1] : 1})", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "($jscomp$compprop0['a'] = 2,", " ($jscomp$compprop0['f' + 1] = 1, $jscomp$compprop0));")); test( "({['f' + 1] : 1, 'a' : 2})", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "($jscomp$compprop0['f' + 1] = 1,", " ($jscomp$compprop0['a'] = 2, $jscomp$compprop0));")); test("({'a' : 1, ['f' + 1] : 1, 'b' : 1})", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "($jscomp$compprop0['a'] = 1,", " ($jscomp$compprop0['f' + 1] = 1, ($jscomp$compprop0['b'] = 1, $jscomp$compprop0)));" )); test( "({'a' : x++, ['f' + x++] : 1, 'b' : x++})", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "($jscomp$compprop0['a'] = x++, ($jscomp$compprop0['f' + x++] = 1,", " ($jscomp$compprop0['b'] = x++, $jscomp$compprop0)))")); test( "({a : x++, ['f' + x++] : 1, b : x++})", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "($jscomp$compprop0.a = x++, ($jscomp$compprop0['f' + x++] = 1,", " ($jscomp$compprop0.b = x++, $jscomp$compprop0)))")); test( "({a, ['f' + 1] : 1})", LINE_JOINER.join( "var $jscomp$compprop0 = {};", " ($jscomp$compprop0.a = a, ($jscomp$compprop0['f' + 1] = 1, $jscomp$compprop0))")); test( "({['f' + 1] : 1, a})", LINE_JOINER.join( "var $jscomp$compprop0 = {};", " ($jscomp$compprop0['f' + 1] = 1, ($jscomp$compprop0.a = a, $jscomp$compprop0))")); test( "var obj = { [foo]() {}}", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "var obj = ($jscomp$compprop0[foo] = function(){}, $jscomp$compprop0)")); test( "var obj = { *[foo]() {}}", LINE_JOINER.join( "var $jscomp$compprop0 = {};", "var obj = (", " $jscomp$compprop0[foo] = function*(){},", " $jscomp$compprop0)")); } public void testComputedPropGetterSetter() { languageOut = LanguageMode.ECMASCRIPT5; testSame("var obj = {get latest () {return undefined;}}"); testSame("var obj = {set latest (str) {}}"); test( "var obj = {'a' : 2, get l () {return null;}, ['f' + 1] : 1}", LINE_JOINER.join( "var $jscomp$compprop0 = {get l () {return null;}};", "var obj = ($jscomp$compprop0['a'] = 2,", " ($jscomp$compprop0['f' + 1] = 1, $jscomp$compprop0));")); test( "var obj = {['a' + 'b'] : 2, set l (str) {}}", LINE_JOINER.join( "var $jscomp$compprop0 = {set l (str) {}};", "var obj = ($jscomp$compprop0['a' + 'b'] = 2, $jscomp$compprop0);")); } public void testComputedPropClass() { test( "class C { [foo]() { alert(1); } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C.prototype[foo] = function() { alert(1); };")); test( "class C { static [foo]() { alert(2); } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C[foo] = function() { alert(2); };")); } public void testComputedPropGeneratorMethods() { test( "class C { *[foo]() { yield 1; } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C.prototype[foo] = function*() { yield 1; };")); test( "class C { static *[foo]() { yield 2; } }", LINE_JOINER.join( "/** @constructor @struct */", "var C = function() {};", "C[foo] = function*() { yield 2; };")); } public void testBlockScopedGeneratorFunction() { // Functions defined in a block get translated to a var test( "{ function *f() {yield 1;} }", "{ var f = function*() { yield 1; }; }"); } public void testComputedPropCannotConvert() { testError("var o = { get [foo]() {}}", Es6ToEs3Converter.CANNOT_CONVERT_YET); testError("var o = { set [foo](val) {}}", Es6ToEs3Converter.CANNOT_CONVERT_YET); } public void testNoComputedProperties() { testSame("({'a' : 1})"); testSame("({'a' : 1, f : 1, b : 1})"); } public void testArrayDestructuring() { test( "var [x,y] = z();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = z();", "var x = $jscomp$destructuring$var0[0];", "var y = $jscomp$destructuring$var0[1];")); test( "var x,y;\n" + "[x,y] = z();", LINE_JOINER.join( "var x,y;", "var $jscomp$destructuring$var0 = z();", "x = $jscomp$destructuring$var0[0];", "y = $jscomp$destructuring$var0[1];")); test( "var [a,b] = c();" + "var [x,y] = z();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = c();", "var a = $jscomp$destructuring$var0[0];", "var b = $jscomp$destructuring$var0[1];", "var $jscomp$destructuring$var1 = z();", "var x = $jscomp$destructuring$var1[0];", "var y = $jscomp$destructuring$var1[1];")); } public void testArrayDestructuringDefaultValues() { test( "var a; [a=1] = b();", LINE_JOINER.join( "var a;", "var $jscomp$destructuring$var0 = b()", "a = ($jscomp$destructuring$var0[0] === undefined) ?", " 1 :", " $jscomp$destructuring$var0[0];")); test( "var [a=1] = b();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = b()", "var a = ($jscomp$destructuring$var0[0] === undefined) ?", " 1 :", " $jscomp$destructuring$var0[0];")); test( "var [a, b=1, c] = d();", LINE_JOINER.join( "var $jscomp$destructuring$var0=d();", "var a = $jscomp$destructuring$var0[0];", "var b = ($jscomp$destructuring$var0[1] === undefined) ?", " 1 :", " $jscomp$destructuring$var0[1];", "var c=$jscomp$destructuring$var0[2]")); test( "var a; [[a] = ['b']] = [];", LINE_JOINER.join( "var a;", "var $jscomp$destructuring$var0 = [];", "var $jscomp$destructuring$var1 = ($jscomp$destructuring$var0[0] === undefined)", " ? ['b']", " : $jscomp$destructuring$var0[0];", "a = $jscomp$destructuring$var1[0]")); } public void testArrayDestructuringParam() { test( "function f([x,y]) { use(x); use(y); }", LINE_JOINER.join( "function f($jscomp$destructuring$var0) {", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0;", " var x = $jscomp$destructuring$var1[0];", " var y = $jscomp$destructuring$var1[1];", " use(x);", " use(y);", "}")); test( "function f([x, , y]) { use(x); use(y); }", LINE_JOINER.join( "function f($jscomp$destructuring$var0) {", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0;", " var x = $jscomp$destructuring$var1[0];", " var y = $jscomp$destructuring$var1[2];", " use(x);", " use(y);", "}")); } public void testArrayDestructuringRest() { test( "let [one, ...others] = f();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = f();", "var one = $jscomp$destructuring$var0[0];", "var others = [].slice.call($jscomp$destructuring$var0, 1);")); test( "function f([first, ...rest]) {}", LINE_JOINER.join( "function f($jscomp$destructuring$var0) {", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0;", " var first = $jscomp$destructuring$var1[0];", " var rest = [].slice.call($jscomp$destructuring$var1, 1);", "}")); } public void testObjectDestructuring() { test( "var {a: b, c: d} = foo();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = foo();", "var b = $jscomp$destructuring$var0.a;", "var d = $jscomp$destructuring$var0.c;")); test( "var {a,b} = foo();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = foo();", "var a = $jscomp$destructuring$var0.a;", "var b = $jscomp$destructuring$var0.b;")); test( "var x; ({a: x}) = foo();", LINE_JOINER.join( "var x;", "var $jscomp$destructuring$var0 = foo();", "x = $jscomp$destructuring$var0.a;")); } public void testObjectDestructuringWithInitializer() { test( "var {a : b = 'default'} = foo();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = foo();", "var b = ($jscomp$destructuring$var0.a === undefined) ?", " 'default' :", " $jscomp$destructuring$var0.a")); test( "var {a = 'default'} = foo();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = foo();", "var a = ($jscomp$destructuring$var0.a === undefined) ?", " 'default' :", " $jscomp$destructuring$var0.a")); } public void testObjectDestructuringNested() { test( "var {a: {b}} = foo();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = foo();", "var $jscomp$destructuring$var1 = $jscomp$destructuring$var0.a;", "var b = $jscomp$destructuring$var1.b")); } public void testObjectDestructuringComputedProps() { test( "var {[a]: b} = foo();", "var $jscomp$destructuring$var0 = foo(); var b = $jscomp$destructuring$var0[a];"); test( "({[a]: b}) = foo();", "var $jscomp$destructuring$var0 = foo(); b = $jscomp$destructuring$var0[a];"); test( "var {[foo()]: x = 5} = {};", LINE_JOINER.join( "var $jscomp$destructuring$var0 = {};", "var $jscomp$destructuring$var1 = $jscomp$destructuring$var0[foo()];", "var x = $jscomp$destructuring$var1 === undefined ?", " 5 : $jscomp$destructuring$var1")); test( "function f({['KEY']: x}) {}", LINE_JOINER.join( "function f($jscomp$destructuring$var0) {", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0", " var x = $jscomp$destructuring$var1['KEY']", "}")); } public void testObjectDestructuringStrangeProperties() { test( "var {5: b} = foo();", "var $jscomp$destructuring$var0 = foo(); var b = $jscomp$destructuring$var0['5']"); test( "var {0.1: b} = foo();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = foo();", "var b = $jscomp$destructuring$var0['0.1']")); test( "var {'str': b} = foo();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = foo();", "var b = $jscomp$destructuring$var0['str']")); } public void testObjectDestructuringFunction() { test( "function f({a: b}) {}", LINE_JOINER.join( "function f($jscomp$destructuring$var0) {", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0", " var b = $jscomp$destructuring$var1.a", "}")); test( "function f({a}) {}", LINE_JOINER.join( "function f($jscomp$destructuring$var0) {", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0", " var a = $jscomp$destructuring$var1.a", "}")); test( "function f({k: {subkey : a}}) {}", LINE_JOINER.join( "function f($jscomp$destructuring$var0) {", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0", " var $jscomp$destructuring$var2 = $jscomp$destructuring$var1.k;", " var a = $jscomp$destructuring$var2.subkey;", "}")); test( "function f({k: [x, y, z]}) {}", LINE_JOINER.join( "function f($jscomp$destructuring$var0) {", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0", " var $jscomp$destructuring$var2 = $jscomp$destructuring$var1.k;", " var x = $jscomp$destructuring$var2[0];", " var y = $jscomp$destructuring$var2[1];", " var z = $jscomp$destructuring$var2[2];", "}")); test( "function f({key: x = 5}) {}", LINE_JOINER.join( "function f($jscomp$destructuring$var0) {", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0", " var x = $jscomp$destructuring$var1.key === undefined ?", " 5 : $jscomp$destructuring$var1.key", "}")); test( "function f({[key]: x = 5}) {}", LINE_JOINER.join( "function f($jscomp$destructuring$var0) {", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0", " var $jscomp$destructuring$var2 = $jscomp$destructuring$var1[key]", " var x = $jscomp$destructuring$var2 === undefined ?", " 5 : $jscomp$destructuring$var2", "}")); test( "function f({x = 5}) {}", LINE_JOINER.join( "function f($jscomp$destructuring$var0) {", " var $jscomp$destructuring$var1 = $jscomp$destructuring$var0", " var x = $jscomp$destructuring$var1.x === undefined ?", " 5 : $jscomp$destructuring$var1.x", "}")); } public void testMixedDestructuring() { test( "var [a,{b,c}] = foo();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = foo();", "var a = $jscomp$destructuring$var0[0];", "var $jscomp$destructuring$var1 = $jscomp$destructuring$var0[1];", "var b=$jscomp$destructuring$var1.b;", "var c=$jscomp$destructuring$var1.c")); test( "var {a,b:[c,d]} = foo();", LINE_JOINER.join( "var $jscomp$destructuring$var0 = foo();", "var a = $jscomp$destructuring$var0.a;", "var $jscomp$destructuring$var1 = $jscomp$destructuring$var0.b;", "var c = $jscomp$destructuring$var1[0];", "var d = $jscomp$destructuring$var1[1]")); } public void testUntaggedTemplateLiteral() { test("``", "''"); test("`\"`", "'\\\"'"); test("`'`", "\"'\""); test("`\\``", "'`'"); test("`\\\"`", "'\\\"'"); test("`\\\\\"`", "'\\\\\\\"'"); test("`\"\\\\`", "'\"\\\\'"); test("`$$`", "'$$'"); test("`$$$`", "'$$$'"); test("`\\$$$`", "'$$$'"); test("`hello`", "'hello'"); test("`hello\nworld`", "'hello\\nworld'"); test("`hello\rworld`", "'hello\\nworld'"); test("`hello\r\nworld`", "'hello\\nworld'"); test("`hello\n\nworld`", "'hello\\n\\nworld'"); test("`hello\\r\\nworld`", "'hello\\r\\nworld'"); test("`${world}`", "'' + world"); test("`hello ${world}`", "'hello ' + world"); test("`${hello} world`", "hello + ' world'"); test("`${hello}${world}`", "'' + hello + world"); test("`${a} b ${c} d ${e}`", "a + ' b ' + c + ' d ' + e"); test("`hello ${a + b}`", "'hello ' + (a + b)"); test("`hello ${a, b, c}`", "'hello ' + (a, b, c)"); test("`hello ${a ? b : c}${a * b}`", "'hello ' + (a ? b : c) + (a * b)"); } public void testTaggedTemplateLiteral() { test( "tag``", LINE_JOINER.join( "var $jscomp$templatelit$0 = [''];", "$jscomp$templatelit$0['raw'] = [''];", "tag($jscomp$templatelit$0);")); test( "tag`${hello} world`", LINE_JOINER.join( "var $jscomp$templatelit$0 = ['', ' world'];", "$jscomp$templatelit$0['raw'] = ['', ' world'];", "tag($jscomp$templatelit$0, hello);")); test( "tag`${hello} ${world}`", LINE_JOINER.join( "var $jscomp$templatelit$0 = ['', ' ', ''];", "$jscomp$templatelit$0['raw'] = ['', ' ', ''];", "tag($jscomp$templatelit$0, hello, world);")); test( "tag`\"`", LINE_JOINER.join( "var $jscomp$templatelit$0 = ['\\\"'];", "$jscomp$templatelit$0['raw'] = ['\\\"'];", "tag($jscomp$templatelit$0);")); // The cooked string and the raw string are different. test( "tag`a\tb`", LINE_JOINER.join( "var $jscomp$templatelit$0 = ['a\tb'];", "$jscomp$templatelit$0['raw'] = ['a\\tb'];", "tag($jscomp$templatelit$0);")); test( "tag()`${hello} world`", LINE_JOINER.join( "var $jscomp$templatelit$0 = ['', ' world'];", "$jscomp$templatelit$0['raw'] = ['', ' world'];", "tag()($jscomp$templatelit$0, hello);")); test( "a.b`${hello} world`", LINE_JOINER.join( "var $jscomp$templatelit$0 = ['', ' world'];", "$jscomp$templatelit$0['raw'] = ['', ' world'];", "a.b($jscomp$templatelit$0, hello);")); } public void testUnicodeEscapes() { test("var \\u{73} = \'\\u{2603}\'", "var s = \'\u2603\'"); // ☃ test("var \\u{63} = \'\\u{1f42a}\'", "var c = \'\uD83D\uDC2A\'"); // 🐪 } }
apache-2.0
globalbus/blueprint-gradle-plugin
src/test/java/info/globalbus/blueprint/plugin/bad/BadBean1.java
1101
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 info.globalbus.blueprint.plugin.bad; import info.globalbus.blueprint.plugin.test.ParentBean; import javax.annotation.PostConstruct; import javax.inject.Singleton; @Singleton public class BadBean1 extends ParentBean { @PostConstruct public void secondInit() { } }
apache-2.0
endian675/ignite
modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
150901
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal; import java.io.BufferedReader; import java.io.Externalizable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.InvalidObjectException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.lang.reflect.Constructor; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.cache.CacheException; import javax.management.JMException; import javax.management.ObjectName; import org.apache.ignite.DataRegionMetrics; import org.apache.ignite.DataRegionMetricsAdapter; import org.apache.ignite.DataStorageMetrics; import org.apache.ignite.DataStorageMetricsAdapter; import org.apache.ignite.IgniteAtomicLong; import org.apache.ignite.IgniteAtomicReference; import org.apache.ignite.IgniteAtomicSequence; import org.apache.ignite.IgniteAtomicStamped; import org.apache.ignite.IgniteBinary; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteClientDisconnectedException; import org.apache.ignite.IgniteCompute; import org.apache.ignite.IgniteCountDownLatch; import org.apache.ignite.IgniteDataStreamer; import org.apache.ignite.IgniteEvents; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteFileSystem; import org.apache.ignite.IgniteLock; import org.apache.ignite.IgniteLogger; import org.apache.ignite.IgniteMessaging; import org.apache.ignite.IgniteQueue; import org.apache.ignite.IgniteScheduler; import org.apache.ignite.IgniteSemaphore; import org.apache.ignite.IgniteServices; import org.apache.ignite.IgniteSet; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.IgniteTransactions; import org.apache.ignite.Ignition; import org.apache.ignite.MemoryMetrics; import org.apache.ignite.PersistenceMetrics; import org.apache.ignite.cache.affinity.Affinity; import org.apache.ignite.cluster.BaselineNode; import org.apache.ignite.cluster.ClusterGroup; import org.apache.ignite.cluster.ClusterMetrics; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.AtomicConfiguration; import org.apache.ignite.configuration.BinaryConfiguration; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.CollectionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.MemoryConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.events.EventType; import org.apache.ignite.internal.binary.BinaryEnumCache; import org.apache.ignite.internal.binary.BinaryMarshaller; import org.apache.ignite.internal.binary.BinaryUtils; import org.apache.ignite.internal.cluster.ClusterGroupAdapter; import org.apache.ignite.internal.cluster.IgniteClusterEx; import org.apache.ignite.internal.processors.failure.FailureProcessor; import org.apache.ignite.internal.managers.GridManager; import org.apache.ignite.internal.managers.checkpoint.GridCheckpointManager; import org.apache.ignite.internal.managers.collision.GridCollisionManager; import org.apache.ignite.internal.managers.communication.GridIoManager; import org.apache.ignite.internal.managers.deployment.GridDeploymentManager; import org.apache.ignite.internal.managers.discovery.DiscoveryLocalJoinData; import org.apache.ignite.internal.managers.discovery.GridDiscoveryManager; import org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager; import org.apache.ignite.internal.managers.failover.GridFailoverManager; import org.apache.ignite.internal.managers.indexing.GridIndexingManager; import org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerManager; import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller; import org.apache.ignite.internal.processors.GridProcessor; import org.apache.ignite.internal.processors.affinity.GridAffinityProcessor; import org.apache.ignite.internal.processors.authentication.IgniteAuthenticationProcessor; import org.apache.ignite.internal.processors.cache.CacheConfigurationOverride; import org.apache.ignite.internal.processors.cache.GridCacheAdapter; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.GridCacheProcessor; import org.apache.ignite.internal.processors.cache.GridCacheUtilityKey; import org.apache.ignite.internal.processors.cache.IgniteCacheProxy; import org.apache.ignite.internal.processors.cache.IgniteInternalCache; import org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl; import org.apache.ignite.internal.processors.cache.persistence.DataRegion; import org.apache.ignite.internal.processors.cache.persistence.filename.PdsConsistentIdProcessor; import org.apache.ignite.internal.processors.cacheobject.IgniteCacheObjectProcessor; import org.apache.ignite.internal.processors.closure.GridClosureProcessor; import org.apache.ignite.internal.processors.cluster.ClusterProcessor; import org.apache.ignite.internal.processors.cluster.GridClusterStateProcessor; import org.apache.ignite.internal.processors.cluster.IGridClusterStateProcessor; import org.apache.ignite.internal.processors.continuous.GridContinuousProcessor; import org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor; import org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor; import org.apache.ignite.internal.processors.hadoop.Hadoop; import org.apache.ignite.internal.processors.hadoop.HadoopProcessorAdapter; import org.apache.ignite.internal.processors.job.GridJobProcessor; import org.apache.ignite.internal.processors.jobmetrics.GridJobMetricsProcessor; import org.apache.ignite.internal.processors.marshaller.GridMarshallerMappingProcessor; import org.apache.ignite.internal.processors.nodevalidation.DiscoveryNodeValidationProcessor; import org.apache.ignite.internal.processors.nodevalidation.OsDiscoveryNodeValidationProcessor; import org.apache.ignite.internal.processors.odbc.ClientListenerProcessor; import org.apache.ignite.internal.processors.platform.PlatformNoopProcessor; import org.apache.ignite.internal.processors.platform.PlatformProcessor; import org.apache.ignite.internal.processors.platform.plugin.PlatformPluginProcessor; import org.apache.ignite.internal.processors.plugin.IgnitePluginProcessor; import org.apache.ignite.internal.processors.pool.PoolProcessor; import org.apache.ignite.internal.processors.port.GridPortProcessor; import org.apache.ignite.internal.processors.port.GridPortRecord; import org.apache.ignite.internal.processors.query.GridQueryProcessor; import org.apache.ignite.internal.processors.resource.GridResourceProcessor; import org.apache.ignite.internal.processors.resource.GridSpringResourceContext; import org.apache.ignite.internal.processors.rest.GridRestProcessor; import org.apache.ignite.internal.processors.security.GridSecurityProcessor; import org.apache.ignite.internal.processors.segmentation.GridSegmentationProcessor; import org.apache.ignite.internal.processors.service.GridServiceProcessor; import org.apache.ignite.internal.processors.session.GridTaskSessionProcessor; import org.apache.ignite.internal.processors.subscription.GridInternalSubscriptionProcessor; import org.apache.ignite.internal.processors.task.GridTaskProcessor; import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor; import org.apache.ignite.internal.suggestions.GridPerformanceSuggestions; import org.apache.ignite.internal.suggestions.JvmConfigurationSuggestions; import org.apache.ignite.internal.suggestions.OsConfigurationSuggestions; import org.apache.ignite.internal.util.StripedExecutor; import org.apache.ignite.internal.util.future.GridCompoundFuture; import org.apache.ignite.internal.util.future.GridFinishedFuture; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.future.IgniteFutureImpl; import org.apache.ignite.internal.util.lang.GridAbsClosure; import org.apache.ignite.internal.util.tostring.GridToStringExclude; import org.apache.ignite.internal.util.typedef.C1; import org.apache.ignite.internal.util.typedef.CI1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.A; import org.apache.ignite.internal.util.typedef.internal.CU; import org.apache.ignite.internal.util.typedef.internal.LT; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.SB; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.worker.WorkersControlMXBeanImpl; import org.apache.ignite.internal.worker.WorkersRegistry; import org.apache.ignite.lang.IgniteBiTuple; import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lang.IgniteProductVersion; import org.apache.ignite.lifecycle.LifecycleAware; import org.apache.ignite.lifecycle.LifecycleBean; import org.apache.ignite.lifecycle.LifecycleEventType; import org.apache.ignite.marshaller.MarshallerExclusions; import org.apache.ignite.marshaller.jdk.JdkMarshaller; import org.apache.ignite.mxbean.ClusterMetricsMXBean; import org.apache.ignite.mxbean.IgniteMXBean; import org.apache.ignite.mxbean.StripedExecutorMXBean; import org.apache.ignite.mxbean.WorkersControlMXBean; import org.apache.ignite.mxbean.ThreadPoolMXBean; import org.apache.ignite.mxbean.TransactionsMXBean; import org.apache.ignite.mxbean.TransactionMetricsMxBean; import org.apache.ignite.plugin.IgnitePlugin; import org.apache.ignite.plugin.PluginNotFoundException; import org.apache.ignite.plugin.PluginProvider; import org.apache.ignite.spi.IgniteSpi; import org.apache.ignite.spi.IgniteSpiVersionCheckException; import org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode; import org.apache.ignite.thread.IgniteStripedThreadPoolExecutor; import org.jetbrains.annotations.Nullable; import static org.apache.ignite.IgniteSystemProperties.IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2; import static org.apache.ignite.IgniteSystemProperties.IGNITE_CONFIG_URL; import static org.apache.ignite.IgniteSystemProperties.IGNITE_DAEMON; import static org.apache.ignite.IgniteSystemProperties.IGNITE_NO_ASCII; import static org.apache.ignite.IgniteSystemProperties.IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID; import static org.apache.ignite.IgniteSystemProperties.IGNITE_REST_START_ON_CLIENT; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK; import static org.apache.ignite.IgniteSystemProperties.IGNITE_STARVATION_CHECK_INTERVAL; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SUCCESS_FILE; import static org.apache.ignite.IgniteSystemProperties.getBoolean; import static org.apache.ignite.IgniteSystemProperties.snapshot; import static org.apache.ignite.internal.GridKernalState.DISCONNECTED; import static org.apache.ignite.internal.GridKernalState.STARTED; import static org.apache.ignite.internal.GridKernalState.STARTING; import static org.apache.ignite.internal.GridKernalState.STOPPED; import static org.apache.ignite.internal.GridKernalState.STOPPING; import static org.apache.ignite.internal.IgniteComponentType.HADOOP_HELPER; import static org.apache.ignite.internal.IgniteComponentType.IGFS; import static org.apache.ignite.internal.IgniteComponentType.IGFS_HELPER; import static org.apache.ignite.internal.IgniteComponentType.SCHEDULE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_DATE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_VER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CLIENT_MODE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CONSISTENCY_CHECK_SKIPPED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DAEMON; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DATA_STORAGE_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DATA_STREAMER_POOL_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DEPLOYMENT_MODE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IGNITE_INSTANCE_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IPS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JIT_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JMX_PORT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_ARGS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_PID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LANG_RUNTIME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LATE_AFFINITY_ASSIGNMENT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_COMPACT_FOOTER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_DFLT_SUID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MEMORY_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_NODE_CONSISTENT_ID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_OFFHEAP_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PEER_CLASSLOADING; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PHY_RAM; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PREFIX; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_RESTART_ENABLED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_PORT_RANGE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_SPI_CLASS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_TX_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_USER_NAME; import static org.apache.ignite.internal.IgniteVersionUtils.ACK_VER_STR; import static org.apache.ignite.internal.IgniteVersionUtils.BUILD_TSTAMP_STR; import static org.apache.ignite.internal.IgniteVersionUtils.COPYRIGHT; import static org.apache.ignite.internal.IgniteVersionUtils.REV_HASH_STR; import static org.apache.ignite.internal.IgniteVersionUtils.VER; import static org.apache.ignite.internal.IgniteVersionUtils.VER_STR; import static org.apache.ignite.lifecycle.LifecycleEventType.AFTER_NODE_START; import static org.apache.ignite.lifecycle.LifecycleEventType.BEFORE_NODE_START; import static org.apache.ignite.marshaller.MarshallerUtils.CLS_NAMES_FILE; import static org.apache.ignite.marshaller.MarshallerUtils.JDK_CLS_NAMES_FILE; /** * Ignite kernal. * <p/> * See <a href="http://en.wikipedia.org/wiki/Kernal">http://en.wikipedia.org/wiki/Kernal</a> for information on the * misspelling. */ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable { /** */ private static final long serialVersionUID = 0L; /** Ignite site that is shown in log messages. */ public static final String SITE = "ignite.apache.org"; /** System line separator. */ private static final String NL = U.nl(); /** Periodic starvation check interval. */ private static final long PERIODIC_STARVATION_CHECK_FREQ = 1000 * 30; /** Force complete reconnect future. */ private static final Object STOP_RECONNECT = new Object(); static { LongJVMPauseDetector.start(); } /** */ @GridToStringExclude private GridKernalContextImpl ctx; /** Helper that registers MBeans */ @GridToStringExclude private final MBeansManager mBeansMgr = new MBeansManager(); /** Configuration. */ private IgniteConfiguration cfg; /** */ @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) @GridToStringExclude private GridLoggerProxy log; /** */ private String igniteInstanceName; /** Kernal start timestamp. */ private long startTime = U.currentTimeMillis(); /** Spring context, potentially {@code null}. */ private GridSpringResourceContext rsrcCtx; /** */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask starveTask; /** */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask metricsLogTask; /** */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask longOpDumpTask; /** Indicate error on grid stop. */ @GridToStringExclude private boolean errOnStop; /** Scheduler. */ @GridToStringExclude private IgniteScheduler scheduler; /** Kernal gateway. */ @GridToStringExclude private final AtomicReference<GridKernalGateway> gw = new AtomicReference<>(); /** Stop guard. */ @GridToStringExclude private final AtomicBoolean stopGuard = new AtomicBoolean(); /** */ private final ReconnectState reconnectState = new ReconnectState(); /** * No-arg constructor is required by externalization. */ public IgniteKernal() { this(null); } /** * @param rsrcCtx Optional Spring application context. */ public IgniteKernal(@Nullable GridSpringResourceContext rsrcCtx) { this.rsrcCtx = rsrcCtx; } /** {@inheritDoc} */ @Override public IgniteClusterEx cluster() { return ctx.cluster().get(); } /** {@inheritDoc} */ @Override public ClusterNode localNode() { return ctx.cluster().get().localNode(); } /** {@inheritDoc} */ @Override public IgniteCompute compute() { return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).compute(); } /** {@inheritDoc} */ @Override public IgniteMessaging message() { return ctx.cluster().get().message(); } /** {@inheritDoc} */ @Override public IgniteEvents events() { return ctx.cluster().get().events(); } /** {@inheritDoc} */ @Override public IgniteServices services() { checkClusterState(); return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).services(); } /** {@inheritDoc} */ @Override public ExecutorService executorService() { return ctx.cluster().get().executorService(); } /** {@inheritDoc} */ @Override public final IgniteCompute compute(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).compute(); } /** {@inheritDoc} */ @Override public final IgniteMessaging message(ClusterGroup prj) { return ((ClusterGroupAdapter)prj).message(); } /** {@inheritDoc} */ @Override public final IgniteEvents events(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).events(); } /** {@inheritDoc} */ @Override public IgniteServices services(ClusterGroup grp) { checkClusterState(); return ((ClusterGroupAdapter)grp).services(); } /** {@inheritDoc} */ @Override public ExecutorService executorService(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).executorService(); } /** {@inheritDoc} */ @Override public String name() { return igniteInstanceName; } /** {@inheritDoc} */ @Override public String getCopyright() { return COPYRIGHT; } /** {@inheritDoc} */ @Override public long getStartTimestamp() { return startTime; } /** {@inheritDoc} */ @Override public String getStartTimestampFormatted() { return DateFormat.getDateTimeInstance().format(new Date(startTime)); } /** {@inheritDoc} */ @Override public boolean isRebalanceEnabled() { return ctx.cache().context().isRebalanceEnabled(); } /** {@inheritDoc} */ @Override public void rebalanceEnabled(boolean rebalanceEnabled) { ctx.cache().context().rebalanceEnabled(rebalanceEnabled); } /** {@inheritDoc} */ @Override public long getUpTime() { return U.currentTimeMillis() - startTime; } /** {@inheritDoc} */ @Override public long getLongJVMPausesCount() { return LongJVMPauseDetector.longPausesCount(); } /** {@inheritDoc} */ @Override public long getLongJVMPausesTotalDuration() { return LongJVMPauseDetector.longPausesTotalDuration(); } /** {@inheritDoc} */ @Override public Map<Long, Long> getLongJVMPauseLastEvents() { return LongJVMPauseDetector.longPauseEvents(); } /** {@inheritDoc} */ @Override public String getUpTimeFormatted() { return X.timeSpan2HMSM(U.currentTimeMillis() - startTime); } /** {@inheritDoc} */ @Override public String getFullVersion() { return VER_STR + '-' + BUILD_TSTAMP_STR; } /** {@inheritDoc} */ @Override public String getCheckpointSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getCheckpointSpi()); } /** {@inheritDoc} */ @Override public String getCommunicationSpiFormatted() { assert cfg != null; return cfg.getCommunicationSpi().toString(); } /** {@inheritDoc} */ @Override public String getDeploymentSpiFormatted() { assert cfg != null; return cfg.getDeploymentSpi().toString(); } /** {@inheritDoc} */ @Override public String getDiscoverySpiFormatted() { assert cfg != null; return cfg.getDiscoverySpi().toString(); } /** {@inheritDoc} */ @Override public String getEventStorageSpiFormatted() { assert cfg != null; return cfg.getEventStorageSpi().toString(); } /** {@inheritDoc} */ @Override public String getCollisionSpiFormatted() { assert cfg != null; return cfg.getCollisionSpi().toString(); } /** {@inheritDoc} */ @Override public String getFailoverSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getFailoverSpi()); } /** {@inheritDoc} */ @Override public String getLoadBalancingSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getLoadBalancingSpi()); } /** {@inheritDoc} */ @Override public String getOsInformation() { return U.osString(); } /** {@inheritDoc} */ @Override public String getJdkInformation() { return U.jdkString(); } /** {@inheritDoc} */ @Override public String getOsUser() { return System.getProperty("user.name"); } /** {@inheritDoc} */ @Override public void printLastErrors() { ctx.exceptionRegistry().printErrors(log); } /** {@inheritDoc} */ @Override public String getVmName() { return ManagementFactory.getRuntimeMXBean().getName(); } /** {@inheritDoc} */ @Override public String getInstanceName() { return igniteInstanceName; } /** {@inheritDoc} */ @Override public String getExecutorServiceFormatted() { assert cfg != null; return String.valueOf(cfg.getPublicThreadPoolSize()); } /** {@inheritDoc} */ @Override public String getIgniteHome() { assert cfg != null; return cfg.getIgniteHome(); } /** {@inheritDoc} */ @Override public String getGridLoggerFormatted() { assert cfg != null; return cfg.getGridLogger().toString(); } /** {@inheritDoc} */ @Override public String getMBeanServerFormatted() { assert cfg != null; return cfg.getMBeanServer().toString(); } /** {@inheritDoc} */ @Override public UUID getLocalNodeId() { assert cfg != null; return cfg.getNodeId(); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<String> getUserAttributesFormatted() { assert cfg != null; return (List<String>)F.transform(cfg.getUserAttributes().entrySet(), new C1<Map.Entry<String, ?>, String>() { @Override public String apply(Map.Entry<String, ?> e) { return e.getKey() + ", " + e.getValue().toString(); } }); } /** {@inheritDoc} */ @Override public boolean isPeerClassLoadingEnabled() { assert cfg != null; return cfg.isPeerClassLoadingEnabled(); } /** {@inheritDoc} */ @Override public List<String> getLifecycleBeansFormatted() { LifecycleBean[] beans = cfg.getLifecycleBeans(); if (F.isEmpty(beans)) return Collections.emptyList(); else { List<String> res = new ArrayList<>(beans.length); for (LifecycleBean bean : beans) res.add(String.valueOf(bean)); return res; } } /** * @param name New attribute name. * @param val New attribute value. * @throws IgniteCheckedException If duplicated SPI name found. */ private void add(String name, @Nullable Serializable val) throws IgniteCheckedException { assert name != null; if (ctx.addNodeAttribute(name, val) != null) { if (name.endsWith(ATTR_SPI_CLASS)) // User defined duplicated names for the different SPIs. throw new IgniteCheckedException("Failed to set SPI attribute. Duplicated SPI name found: " + name.substring(0, name.length() - ATTR_SPI_CLASS.length())); // Otherwise it's a mistake of setting up duplicated attribute. assert false : "Duplicate attribute: " + name; } } /** * Notifies life-cycle beans of grid event. * * @param evt Grid event. * @throws IgniteCheckedException If user threw exception during start. */ @SuppressWarnings({"CatchGenericClass"}) private void notifyLifecycleBeans(LifecycleEventType evt) throws IgniteCheckedException { if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) { for (LifecycleBean bean : cfg.getLifecycleBeans()) if (bean != null) { try { bean.onLifecycleEvent(evt); } catch (Exception e) { throw new IgniteCheckedException(e); } } } } /** * Notifies life-cycle beans of grid event. * * @param evt Grid event. */ @SuppressWarnings({"CatchGenericClass"}) private void notifyLifecycleBeansEx(LifecycleEventType evt) { try { notifyLifecycleBeans(evt); } // Catch generic throwable to secure against user assertions. catch (Throwable e) { U.error(log, "Failed to notify lifecycle bean (safely ignored) [evt=" + evt + (igniteInstanceName == null ? "" : ", igniteInstanceName=" + igniteInstanceName) + ']', e); if (e instanceof Error) throw (Error)e; } } /** * @param cfg Configuration to use. * @param utilityCachePool Utility cache pool. * @param execSvc Executor service. * @param sysExecSvc System executor service. * @param stripedExecSvc Striped executor. * @param p2pExecSvc P2P executor service. * @param mgmtExecSvc Management executor service. * @param igfsExecSvc IGFS executor service. * @param dataStreamExecSvc data stream executor service. * @param restExecSvc Reset executor service. * @param affExecSvc Affinity executor service. * @param idxExecSvc Indexing executor service. * @param callbackExecSvc Callback executor service. * @param qryExecSvc Query executor service. * @param schemaExecSvc Schema executor service. * @param customExecSvcs Custom named executors. * @param errHnd Error handler to use for notification about startup problems. * @throws IgniteCheckedException Thrown in case of any errors. */ @SuppressWarnings({"CatchGenericClass", "unchecked"}) public void start( final IgniteConfiguration cfg, ExecutorService utilityCachePool, final ExecutorService execSvc, final ExecutorService svcExecSvc, final ExecutorService sysExecSvc, final StripedExecutor stripedExecSvc, ExecutorService p2pExecSvc, ExecutorService mgmtExecSvc, ExecutorService igfsExecSvc, StripedExecutor dataStreamExecSvc, ExecutorService restExecSvc, ExecutorService affExecSvc, @Nullable ExecutorService idxExecSvc, IgniteStripedThreadPoolExecutor callbackExecSvc, ExecutorService qryExecSvc, ExecutorService schemaExecSvc, @Nullable final Map<String, ? extends ExecutorService> customExecSvcs, GridAbsClosure errHnd ) throws IgniteCheckedException { gw.compareAndSet(null, new GridKernalGatewayImpl(cfg.getIgniteInstanceName())); GridKernalGateway gw = this.gw.get(); gw.writeLock(); try { switch (gw.getState()) { case STARTED: { U.warn(log, "Grid has already been started (ignored)."); return; } case STARTING: { U.warn(log, "Grid is already in process of being started (ignored)."); return; } case STOPPING: { throw new IgniteCheckedException("Grid is in process of being stopped"); } case STOPPED: { break; } } gw.setState(STARTING); } finally { gw.writeUnlock(); } assert cfg != null; // Make sure we got proper configuration. validateCommon(cfg); igniteInstanceName = cfg.getIgniteInstanceName(); this.cfg = cfg; log = (GridLoggerProxy)cfg.getGridLogger().getLogger( getClass().getName() + (igniteInstanceName != null ? '%' + igniteInstanceName : "")); RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean(); // Ack various information. ackAsciiLogo(); ackConfigUrl(); ackConfiguration(cfg); ackDaemon(); ackOsInfo(); ackLanguageRuntime(); ackRemoteManagement(); ackLogger(); ackVmArguments(rtBean); ackClassPaths(rtBean); ackSystemProperties(); ackEnvironmentVariables(); ackMemoryConfiguration(); ackCacheConfiguration(); ackP2pConfiguration(); ackRebalanceConfiguration(); // Run background network diagnostics. GridDiagnostic.runBackgroundCheck(igniteInstanceName, execSvc, log); // Ack 3-rd party licenses location. if (log.isInfoEnabled() && cfg.getIgniteHome() != null) log.info("3-rd party licenses can be found at: " + cfg.getIgniteHome() + File.separatorChar + "libs" + File.separatorChar + "licenses"); // Check that user attributes are not conflicting // with internally reserved names. for (String name : cfg.getUserAttributes().keySet()) if (name.startsWith(ATTR_PREFIX)) throw new IgniteCheckedException("User attribute has illegal name: '" + name + "'. Note that all names " + "starting with '" + ATTR_PREFIX + "' are reserved for internal use."); // Ack local node user attributes. logNodeUserAttributes(); // Ack configuration. ackSpis(); List<PluginProvider> plugins = U.allPluginProviders(); // Spin out SPIs & managers. try { ctx = new GridKernalContextImpl(log, this, cfg, gw, utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, igfsExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, customExecSvcs, plugins, classNameFilter() ); cfg.getMarshaller().setContext(ctx.marshallerContext()); GridInternalSubscriptionProcessor subscriptionProc = new GridInternalSubscriptionProcessor(ctx); startProcessor(subscriptionProc); ClusterProcessor clusterProc = new ClusterProcessor(ctx); startProcessor(clusterProc); U.onGridStart(); // Start and configure resource processor first as it contains resources used // by all other managers and processors. GridResourceProcessor rsrcProc = new GridResourceProcessor(ctx); rsrcProc.setSpringContext(rsrcCtx); scheduler = new IgniteSchedulerImpl(ctx); startProcessor(rsrcProc); // Inject resources into lifecycle beans. if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) { for (LifecycleBean bean : cfg.getLifecycleBeans()) { if (bean != null) rsrcProc.inject(bean); } } // Lifecycle notification. notifyLifecycleBeans(BEFORE_NODE_START); // Starts lifecycle aware components. U.startLifecycleAware(lifecycleAwares(cfg)); addHelper(IGFS_HELPER.create(F.isEmpty(cfg.getFileSystemConfiguration()))); addHelper(HADOOP_HELPER.createIfInClassPath(ctx, false)); startProcessor(new IgnitePluginProcessor(ctx, cfg, plugins)); startProcessor(new FailureProcessor(ctx)); startProcessor(new PoolProcessor(ctx)); // Closure processor should be started before all others // (except for resource processor), as many components can depend on it. startProcessor(new GridClosureProcessor(ctx)); // Start some other processors (order & place is important). startProcessor(new GridPortProcessor(ctx)); startProcessor(new GridJobMetricsProcessor(ctx)); // Timeout processor needs to be started before managers, // as managers may depend on it. startProcessor(new GridTimeoutProcessor(ctx)); // Start security processors. startProcessor(createComponent(GridSecurityProcessor.class, ctx)); // Start SPI managers. // NOTE: that order matters as there are dependencies between managers. startManager(new GridIoManager(ctx)); startManager(new GridCheckpointManager(ctx)); startManager(new GridEventStorageManager(ctx)); startManager(new GridDeploymentManager(ctx)); startManager(new GridLoadBalancerManager(ctx)); startManager(new GridFailoverManager(ctx)); startManager(new GridCollisionManager(ctx)); startManager(new GridIndexingManager(ctx)); ackSecurity(); // Assign discovery manager to context before other processors start so they // are able to register custom event listener. final GridManager discoMgr = new GridDiscoveryManager(ctx); ctx.add(discoMgr, false); // Start processors before discovery manager, so they will // be able to start receiving messages once discovery completes. try { startProcessor(new PdsConsistentIdProcessor(ctx)); startProcessor(createComponent(DiscoveryNodeValidationProcessor.class, ctx)); startProcessor(new GridAffinityProcessor(ctx)); startProcessor(createComponent(GridSegmentationProcessor.class, ctx)); startProcessor(createComponent(IgniteCacheObjectProcessor.class, ctx)); startProcessor(createComponent(IGridClusterStateProcessor.class, ctx)); startProcessor(new IgniteAuthenticationProcessor(ctx)); startProcessor(new GridCacheProcessor(ctx)); startProcessor(new GridQueryProcessor(ctx)); startProcessor(new ClientListenerProcessor(ctx)); startProcessor(new GridServiceProcessor(ctx)); startProcessor(new GridTaskSessionProcessor(ctx)); startProcessor(new GridJobProcessor(ctx)); startProcessor(new GridTaskProcessor(ctx)); startProcessor((GridProcessor)SCHEDULE.createOptional(ctx)); startProcessor(new GridRestProcessor(ctx)); startProcessor(new DataStreamProcessor(ctx)); startProcessor((GridProcessor)IGFS.create(ctx, F.isEmpty(cfg.getFileSystemConfiguration()))); startProcessor(new GridContinuousProcessor(ctx)); startProcessor(createHadoopComponent()); startProcessor(new DataStructuresProcessor(ctx)); startProcessor(createComponent(PlatformProcessor.class, ctx)); startProcessor(new GridMarshallerMappingProcessor(ctx)); // Start plugins. for (PluginProvider provider : ctx.plugins().allProviders()) { ctx.add(new GridPluginComponent(provider)); provider.start(ctx.plugins().pluginContextForProvider(provider)); } // Start platform plugins. if (ctx.config().getPlatformConfiguration() != null) startProcessor(new PlatformPluginProcessor(ctx)); ctx.cluster().initDiagnosticListeners(); fillNodeAttributes(clusterProc.updateNotifierEnabled()); } catch (Throwable e) { U.error( log, "Exception during start processors, node will be stopped and close connections", e); // Stop discovery spi to close tcp socket. ctx.discovery().stop(true); throw e; } gw.writeLock(); try { gw.setState(STARTED); // Start discovery manager last to make sure that grid is fully initialized. startManager(discoMgr); } finally { gw.writeUnlock(); } // Check whether physical RAM is not exceeded. checkPhysicalRam(); // Suggest configuration optimizations. suggestOptimizations(cfg); // Suggest JVM optimizations. ctx.performance().addAll(JvmConfigurationSuggestions.getSuggestions()); // Suggest Operation System optimizations. ctx.performance().addAll(OsConfigurationSuggestions.getSuggestions()); DiscoveryLocalJoinData joinData = ctx.discovery().localJoin(); IgniteInternalFuture<Boolean> transitionWaitFut = joinData.transitionWaitFuture(); boolean active; if (transitionWaitFut != null) { if (log.isInfoEnabled()) { log.info("Join cluster while cluster state transition is in progress, " + "waiting when transition finish."); } active = transitionWaitFut.get(); } else active = joinData.active(); // Notify discovery manager the first to make sure that topology is discovered. ctx.discovery().onKernalStart(active); // Notify IO manager the second so further components can send and receive messages. ctx.io().onKernalStart(active); boolean recon = false; // Callbacks. for (GridComponent comp : ctx) { // Skip discovery manager. if (comp instanceof GridDiscoveryManager) continue; // Skip IO manager. if (comp instanceof GridIoManager) continue; if (comp instanceof GridPluginComponent) continue; if (!skipDaemon(comp)) { try { comp.onKernalStart(active); } catch (IgniteNeedReconnectException e) { assert ctx.discovery().reconnectSupported(); if (log.isDebugEnabled()) log.debug("Failed to start node components on node start, will wait for reconnect: " + e); recon = true; } } } // Start plugins. for (PluginProvider provider : ctx.plugins().allProviders()) provider.onIgniteStart(); if (recon) reconnectState.waitFirstReconnect(); // Register MBeans. mBeansMgr.registerAllMBeans(utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, igfsExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, customExecSvcs, ctx.workersRegistry()); // Lifecycle bean notifications. notifyLifecycleBeans(AFTER_NODE_START); } catch (Throwable e) { IgniteSpiVersionCheckException verCheckErr = X.cause(e, IgniteSpiVersionCheckException.class); if (verCheckErr != null) U.error(log, verCheckErr.getMessage()); else if (X.hasCause(e, InterruptedException.class, IgniteInterruptedCheckedException.class)) U.warn(log, "Grid startup routine has been interrupted (will rollback)."); else U.error(log, "Got exception while starting (will rollback startup routine).", e); errHnd.apply(); stop(true); if (e instanceof Error) throw e; else if (e instanceof IgniteCheckedException) throw (IgniteCheckedException)e; else throw new IgniteCheckedException(e); } // Mark start timestamp. startTime = U.currentTimeMillis(); String intervalStr = IgniteSystemProperties.getString(IGNITE_STARVATION_CHECK_INTERVAL); // Start starvation checker if enabled. boolean starveCheck = !isDaemon() && !"0".equals(intervalStr); if (starveCheck) { final long interval = F.isEmpty(intervalStr) ? PERIODIC_STARVATION_CHECK_FREQ : Long.parseLong(intervalStr); starveTask = ctx.timeout().schedule(new Runnable() { /** Last completed task count. */ private long lastCompletedCntPub; /** Last completed task count. */ private long lastCompletedCntSys; @Override public void run() { if (execSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc; lastCompletedCntPub = checkPoolStarvation(exec, lastCompletedCntPub, "public"); } if (sysExecSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)sysExecSvc; lastCompletedCntSys = checkPoolStarvation(exec, lastCompletedCntSys, "system"); } if (stripedExecSvc != null) stripedExecSvc.checkStarvation(); } /** * @param exec Thread pool executor to check. * @param lastCompletedCnt Last completed tasks count. * @param pool Pool name for message. * @return Current completed tasks count. */ private long checkPoolStarvation( ThreadPoolExecutor exec, long lastCompletedCnt, String pool ) { long completedCnt = exec.getCompletedTaskCount(); // If all threads are active and no task has completed since last time and there is // at least one waiting request, then it is possible starvation. if (exec.getPoolSize() == exec.getActiveCount() && completedCnt == lastCompletedCnt && !exec.getQueue().isEmpty()) LT.warn( log, "Possible thread pool starvation detected (no task completed in last " + interval + "ms, is " + pool + " thread pool size large enough?)"); return completedCnt; } }, interval, interval); } long metricsLogFreq = cfg.getMetricsLogFrequency(); if (metricsLogFreq > 0) { metricsLogTask = ctx.timeout().schedule(new Runnable() { private final DecimalFormat dblFmt = new DecimalFormat("#.##"); @Override public void run() { if (log.isInfoEnabled()) { try { ClusterMetrics m = cluster().localNode().metrics(); double cpuLoadPct = m.getCurrentCpuLoad() * 100; double avgCpuLoadPct = m.getAverageCpuLoad() * 100; double gcPct = m.getCurrentGcCpuLoad() * 100; //Heap params long heapUsed = m.getHeapMemoryUsed(); long heapMax = m.getHeapMemoryMaximum(); long heapUsedInMBytes = heapUsed / 1024 / 1024; long heapCommInMBytes = m.getHeapMemoryCommitted() / 1024 / 1024; double freeHeapPct = heapMax > 0 ? ((double)((heapMax - heapUsed) * 100)) / heapMax : -1; //Non heap params long nonHeapUsed = m.getNonHeapMemoryUsed(); long nonHeapMax = m.getNonHeapMemoryMaximum(); long nonHeapUsedInMBytes = nonHeapUsed / 1024 / 1024; long nonHeapCommInMBytes = m.getNonHeapMemoryCommitted() / 1024 / 1024; double freeNonHeapPct = nonHeapMax > 0 ? ((double)((nonHeapMax - nonHeapUsed) * 100)) / nonHeapMax : -1; int hosts = 0; int nodes = 0; int cpus = 0; try { ClusterMetrics metrics = cluster().metrics(); Collection<ClusterNode> nodes0 = cluster().nodes(); hosts = U.neighborhood(nodes0).size(); nodes = metrics.getTotalNodes(); cpus = metrics.getTotalCpus(); } catch (IgniteException ignore) { // No-op. } int loadedPages = 0; Collection<DataRegion> policies = ctx.cache().context().database().dataRegions(); if (!F.isEmpty(policies)) { for (DataRegion memPlc : policies) loadedPages += memPlc.pageMemory().loadedPages(); } String id = U.id8(localNode().id()); String msg = NL + "Metrics for local node (to disable set 'metricsLogFrequency' to 0)" + NL + " ^-- Node [id=" + id + (name() != null ? ", name=" + name() : "") + ", uptime=" + getUpTimeFormatted() + "]" + NL + " ^-- H/N/C [hosts=" + hosts + ", nodes=" + nodes + ", CPUs=" + cpus + "]" + NL + " ^-- CPU [cur=" + dblFmt.format(cpuLoadPct) + "%, avg=" + dblFmt.format(avgCpuLoadPct) + "%, GC=" + dblFmt.format(gcPct) + "%]" + NL + " ^-- PageMemory [pages=" + loadedPages + "]" + NL + " ^-- Heap [used=" + dblFmt.format(heapUsedInMBytes) + "MB, free=" + dblFmt.format(freeHeapPct) + "%, comm=" + dblFmt.format(heapCommInMBytes) + "MB]" + NL + " ^-- Non heap [used=" + dblFmt.format(nonHeapUsedInMBytes) + "MB, free=" + dblFmt.format(freeNonHeapPct) + "%, comm=" + dblFmt.format(nonHeapCommInMBytes) + "MB]" + NL + " ^-- Outbound messages queue [size=" + m.getOutboundMessagesQueueSize() + "]" + NL + " ^-- " + createExecutorDescription("Public thread pool", execSvc) + NL + " ^-- " + createExecutorDescription("System thread pool", sysExecSvc); if (customExecSvcs != null) { StringBuilder customSvcsMsg = new StringBuilder(); for (Map.Entry<String, ? extends ExecutorService> entry : customExecSvcs.entrySet()) { customSvcsMsg.append(NL).append(" ^-- ") .append(createExecutorDescription(entry.getKey(), entry.getValue())); } msg = msg + customSvcsMsg; } if (log.isInfoEnabled()) log.info(msg); ctx.cache().context().database().dumpStatistics(log); } catch (IgniteClientDisconnectedException ignore) { // No-op. } } } }, metricsLogFreq, metricsLogFreq); } final long longOpDumpTimeout = IgniteSystemProperties.getLong(IgniteSystemProperties.IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT, 60_000); if (longOpDumpTimeout > 0) { longOpDumpTask = ctx.timeout().schedule(new Runnable() { @Override public void run() { GridKernalContext ctx = IgniteKernal.this.ctx; if (ctx != null) ctx.cache().context().exchange().dumpLongRunningOperations(longOpDumpTimeout); } }, longOpDumpTimeout, longOpDumpTimeout); } ctx.performance().add("Disable assertions (remove '-ea' from JVM options)", !U.assertionsEnabled()); ctx.performance().logSuggestions(log, igniteInstanceName); U.quietAndInfo(log, "To start Console Management & Monitoring run ignitevisorcmd.{sh|bat}"); ackStart(rtBean); if (!isDaemon()) ctx.discovery().ackTopology(ctx.discovery().localJoin().joinTopologyVersion().topologyVersion(), EventType.EVT_NODE_JOINED, localNode()); } /** * Create description of an executor service for logging. * * @param execSvcName name of the service * @param execSvc service to create a description for */ private String createExecutorDescription(String execSvcName, ExecutorService execSvc) { int poolActiveThreads = 0; int poolIdleThreads = 0; int poolQSize = 0; if (execSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc; int poolSize = exec.getPoolSize(); poolActiveThreads = Math.min(poolSize, exec.getActiveCount()); poolIdleThreads = poolSize - poolActiveThreads; poolQSize = exec.getQueue().size(); } return execSvcName + " [active=" + poolActiveThreads + ", idle=" + poolIdleThreads + ", qSize=" + poolQSize + "]"; } /** * Create Hadoop component. * * @return Non-null Hadoop component: workable or no-op. * @throws IgniteCheckedException If the component is mandatory and cannot be initialized. */ private HadoopProcessorAdapter createHadoopComponent() throws IgniteCheckedException { boolean mandatory = cfg.getHadoopConfiguration() != null; if (mandatory) { if (cfg.isPeerClassLoadingEnabled()) throw new IgniteCheckedException("Hadoop module cannot be used with peer class loading enabled " + "(set IgniteConfiguration.peerClassLoadingEnabled to \"false\")."); HadoopProcessorAdapter res = IgniteComponentType.HADOOP.createIfInClassPath(ctx, true); res.validateEnvironment(); return res; } else { HadoopProcessorAdapter cmp = null; if (!ctx.hadoopHelper().isNoOp() && cfg.isPeerClassLoadingEnabled()) { U.warn(log, "Hadoop module is found in classpath, but will not be started because peer class " + "loading is enabled (set IgniteConfiguration.peerClassLoadingEnabled to \"false\" if you want " + "to use Hadoop module)."); } else { cmp = IgniteComponentType.HADOOP.createIfInClassPath(ctx, false); try { cmp.validateEnvironment(); } catch (IgniteException | IgniteCheckedException e) { U.quietAndWarn(log, "Hadoop module will not start due to exception: " + e.getMessage()); cmp = null; } } if (cmp == null) cmp = IgniteComponentType.HADOOP.create(ctx, true); return cmp; } } /** * Validates common configuration parameters. * * @param cfg Configuration. */ private void validateCommon(IgniteConfiguration cfg) { A.notNull(cfg.getNodeId(), "cfg.getNodeId()"); A.notNull(cfg.getMBeanServer(), "cfg.getMBeanServer()"); A.notNull(cfg.getGridLogger(), "cfg.getGridLogger()"); A.notNull(cfg.getMarshaller(), "cfg.getMarshaller()"); A.notNull(cfg.getUserAttributes(), "cfg.getUserAttributes()"); // All SPIs should be non-null. A.notNull(cfg.getCheckpointSpi(), "cfg.getCheckpointSpi()"); A.notNull(cfg.getCommunicationSpi(), "cfg.getCommunicationSpi()"); A.notNull(cfg.getDeploymentSpi(), "cfg.getDeploymentSpi()"); A.notNull(cfg.getDiscoverySpi(), "cfg.getDiscoverySpi()"); A.notNull(cfg.getEventStorageSpi(), "cfg.getEventStorageSpi()"); A.notNull(cfg.getCollisionSpi(), "cfg.getCollisionSpi()"); A.notNull(cfg.getFailoverSpi(), "cfg.getFailoverSpi()"); A.notNull(cfg.getLoadBalancingSpi(), "cfg.getLoadBalancingSpi()"); A.notNull(cfg.getIndexingSpi(), "cfg.getIndexingSpi()"); A.ensure(cfg.getNetworkTimeout() > 0, "cfg.getNetworkTimeout() > 0"); A.ensure(cfg.getNetworkSendRetryDelay() > 0, "cfg.getNetworkSendRetryDelay() > 0"); A.ensure(cfg.getNetworkSendRetryCount() > 0, "cfg.getNetworkSendRetryCount() > 0"); } /** * Checks whether physical RAM is not exceeded. */ @SuppressWarnings("ConstantConditions") private void checkPhysicalRam() { long ram = ctx.discovery().localNode().attribute(ATTR_PHY_RAM); if (ram != -1) { String macs = ctx.discovery().localNode().attribute(ATTR_MACS); long totalHeap = 0; long totalOffheap = 0; for (ClusterNode node : ctx.discovery().allNodes()) { if (macs.equals(node.attribute(ATTR_MACS))) { long heap = node.metrics().getHeapMemoryMaximum(); Long offheap = node.<Long>attribute(ATTR_OFFHEAP_SIZE); if (heap != -1) totalHeap += heap; if (offheap != null) totalOffheap += offheap; } } long total = totalHeap + totalOffheap; if (total < 0) total = Long.MAX_VALUE; // 4GB or 20% of available memory is expected to be used by OS and user applications long safeToUse = ram - Math.max(4L << 30, (long)(ram * 0.2)); if (total > safeToUse) { U.quietAndWarn(log, "Nodes started on local machine require more than 80% of physical RAM what can " + "lead to significant slowdown due to swapping (please decrease JVM heap size, data region " + "size or checkpoint buffer size) [required=" + (total >> 20) + "MB, available=" + (ram >> 20) + "MB]"); } } } /** * @param cfg Configuration to check for possible performance issues. */ private void suggestOptimizations(IgniteConfiguration cfg) { GridPerformanceSuggestions perf = ctx.performance(); if (ctx.collision().enabled()) perf.add("Disable collision resolution (remove 'collisionSpi' from configuration)"); if (ctx.checkpoint().enabled()) perf.add("Disable checkpoints (remove 'checkpointSpi' from configuration)"); if (cfg.isMarshalLocalJobs()) perf.add("Disable local jobs marshalling (set 'marshalLocalJobs' to false)"); if (cfg.getIncludeEventTypes() != null && cfg.getIncludeEventTypes().length != 0) perf.add("Disable grid events (remove 'includeEventTypes' from configuration)"); if (BinaryMarshaller.available() && (cfg.getMarshaller() != null && !(cfg.getMarshaller() instanceof BinaryMarshaller))) perf.add("Use default binary marshaller (do not set 'marshaller' explicitly)"); } /** * Creates attributes map and fills it in. * * @param notifyEnabled Update notifier flag. * @throws IgniteCheckedException thrown if was unable to set up attribute. */ @SuppressWarnings({"SuspiciousMethodCalls", "unchecked", "TypeMayBeWeakened"}) private void fillNodeAttributes(boolean notifyEnabled) throws IgniteCheckedException { ctx.addNodeAttribute(ATTR_DATA_STREAMER_POOL_SIZE, configuration().getDataStreamerThreadPoolSize()); final String[] incProps = cfg.getIncludeProperties(); try { // Stick all environment settings into node attributes. for (Map.Entry<String, String> sysEntry : System.getenv().entrySet()) { String name = sysEntry.getKey(); if (incProps == null || U.containsStringArray(incProps, name, true) || U.isVisorNodeStartProperty(name) || U.isVisorRequiredProperty(name)) ctx.addNodeAttribute(name, sysEntry.getValue()); } if (log.isDebugEnabled()) log.debug("Added environment properties to node attributes."); } catch (SecurityException e) { throw new IgniteCheckedException("Failed to add environment properties to node attributes due to " + "security violation: " + e.getMessage()); } try { // Stick all system properties into node's attributes overwriting any // identical names from environment properties. for (Map.Entry<Object, Object> e : snapshot().entrySet()) { String key = (String)e.getKey(); if (incProps == null || U.containsStringArray(incProps, key, true) || U.isVisorRequiredProperty(key)) { Object val = ctx.nodeAttribute(key); if (val != null && !val.equals(e.getValue())) U.warn(log, "System property will override environment variable with the same name: " + key); ctx.addNodeAttribute(key, e.getValue()); } } ctx.addNodeAttribute(IgniteNodeAttributes.ATTR_UPDATE_NOTIFIER_ENABLED, notifyEnabled); if (log.isDebugEnabled()) log.debug("Added system properties to node attributes."); } catch (SecurityException e) { throw new IgniteCheckedException("Failed to add system properties to node attributes due to security " + "violation: " + e.getMessage()); } // Add local network IPs and MACs. String ips = F.concat(U.allLocalIps(), ", "); // Exclude loopbacks. String macs = F.concat(U.allLocalMACs(), ", "); // Only enabled network interfaces. // Ack network context. if (log.isInfoEnabled()) { log.info("Non-loopback local IPs: " + (F.isEmpty(ips) ? "N/A" : ips)); log.info("Enabled local MACs: " + (F.isEmpty(macs) ? "N/A" : macs)); } // Warn about loopback. if (ips.isEmpty() && macs.isEmpty()) U.warn(log, "Ignite is starting on loopback address... Only nodes on the same physical " + "computer can participate in topology.", "Ignite is starting on loopback address..."); // Stick in network context into attributes. add(ATTR_IPS, (ips.isEmpty() ? "" : ips)); add(ATTR_MACS, (macs.isEmpty() ? "" : macs)); // Stick in some system level attributes add(ATTR_JIT_NAME, U.getCompilerMx() == null ? "" : U.getCompilerMx().getName()); add(ATTR_BUILD_VER, VER_STR); add(ATTR_BUILD_DATE, BUILD_TSTAMP_STR); add(ATTR_MARSHALLER, cfg.getMarshaller().getClass().getName()); add(ATTR_MARSHALLER_USE_DFLT_SUID, getBoolean(IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID, OptimizedMarshaller.USE_DFLT_SUID)); add(ATTR_LATE_AFFINITY_ASSIGNMENT, cfg.isLateAffinityAssignment()); if (cfg.getMarshaller() instanceof BinaryMarshaller) { add(ATTR_MARSHALLER_COMPACT_FOOTER, cfg.getBinaryConfiguration() == null ? BinaryConfiguration.DFLT_COMPACT_FOOTER : cfg.getBinaryConfiguration().isCompactFooter()); add(ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2, getBoolean(IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2, BinaryUtils.USE_STR_SERIALIZATION_VER_2)); } add(ATTR_USER_NAME, System.getProperty("user.name")); add(ATTR_IGNITE_INSTANCE_NAME, igniteInstanceName); add(ATTR_PEER_CLASSLOADING, cfg.isPeerClassLoadingEnabled()); add(ATTR_DEPLOYMENT_MODE, cfg.getDeploymentMode()); add(ATTR_LANG_RUNTIME, getLanguage()); add(ATTR_JVM_PID, U.jvmPid()); add(ATTR_CLIENT_MODE, cfg.isClientMode()); add(ATTR_CONSISTENCY_CHECK_SKIPPED, getBoolean(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK)); if (cfg.getConsistentId() != null) add(ATTR_NODE_CONSISTENT_ID, cfg.getConsistentId()); // Build a string from JVM arguments, because parameters with spaces are split. SB jvmArgs = new SB(512); for (String arg : U.jvmArgs()) { if (arg.startsWith("-")) jvmArgs.a("@@@"); else jvmArgs.a(' '); jvmArgs.a(arg); } // Add it to attributes. add(ATTR_JVM_ARGS, jvmArgs.toString()); // Check daemon system property and override configuration if it's set. if (isDaemon()) add(ATTR_DAEMON, "true"); // In case of the parsing error, JMX remote disabled or port not being set // node attribute won't be set. if (isJmxRemoteEnabled()) { String portStr = System.getProperty("com.sun.management.jmxremote.port"); if (portStr != null) try { add(ATTR_JMX_PORT, Integer.parseInt(portStr)); } catch (NumberFormatException ignore) { // No-op. } } // Whether restart is enabled and stick the attribute. add(ATTR_RESTART_ENABLED, Boolean.toString(isRestartEnabled())); // Save port range, port numbers will be stored by rest processor at runtime. if (cfg.getConnectorConfiguration() != null) add(ATTR_REST_PORT_RANGE, cfg.getConnectorConfiguration().getPortRange()); // Save data storage configuration. addDataStorageConfigurationAttributes(); // Save transactions configuration. add(ATTR_TX_CONFIG, cfg.getTransactionConfiguration()); // Stick in SPI versions and classes attributes. addSpiAttributes(cfg.getCollisionSpi()); addSpiAttributes(cfg.getDiscoverySpi()); addSpiAttributes(cfg.getFailoverSpi()); addSpiAttributes(cfg.getCommunicationSpi()); addSpiAttributes(cfg.getEventStorageSpi()); addSpiAttributes(cfg.getCheckpointSpi()); addSpiAttributes(cfg.getLoadBalancingSpi()); addSpiAttributes(cfg.getDeploymentSpi()); // Set user attributes for this node. if (cfg.getUserAttributes() != null) { for (Map.Entry<String, ?> e : cfg.getUserAttributes().entrySet()) { if (ctx.hasNodeAttribute(e.getKey())) U.warn(log, "User or internal attribute has the same name as environment or system " + "property and will take precedence: " + e.getKey()); ctx.addNodeAttribute(e.getKey(), e.getValue()); } } } /** * */ private void addDataStorageConfigurationAttributes() throws IgniteCheckedException { MemoryConfiguration memCfg = cfg.getMemoryConfiguration(); // Save legacy memory configuration if it's present. if (memCfg != null) { // Page size initialization is suspended, see IgniteCacheDatabaseSharedManager#checkPageSize. // We should copy initialized value from new configuration. memCfg.setPageSize(cfg.getDataStorageConfiguration().getPageSize()); add(ATTR_MEMORY_CONFIG, memCfg); } // Save data storage configuration. add(ATTR_DATA_STORAGE_CONFIG, new JdkMarshaller().marshal(cfg.getDataStorageConfiguration())); } /** * Add SPI version and class attributes into node attributes. * * @param spiList Collection of SPIs to get attributes from. * @throws IgniteCheckedException Thrown if was unable to set up attribute. */ private void addSpiAttributes(IgniteSpi... spiList) throws IgniteCheckedException { for (IgniteSpi spi : spiList) { Class<? extends IgniteSpi> spiCls = spi.getClass(); add(U.spiAttribute(spi, ATTR_SPI_CLASS), spiCls.getName()); } } /** * @param mgr Manager to start. * @throws IgniteCheckedException Throw in case of any errors. */ private void startManager(GridManager mgr) throws IgniteCheckedException { // Add manager to registry before it starts to avoid cases when manager is started // but registry does not have it yet. ctx.add(mgr); try { if (!skipDaemon(mgr)) mgr.start(); } catch (IgniteCheckedException e) { U.error(log, "Failed to start manager: " + mgr, e); throw new IgniteCheckedException("Failed to start manager: " + mgr, e); } } /** * @param proc Processor to start. * @throws IgniteCheckedException Thrown in case of any error. */ private void startProcessor(GridProcessor proc) throws IgniteCheckedException { ctx.add(proc); try { if (!skipDaemon(proc)) proc.start(); } catch (IgniteCheckedException e) { throw new IgniteCheckedException("Failed to start processor: " + proc, e); } } /** * Returns class name filter for marshaller. * * @return Class name filter for marshaller. */ private IgnitePredicate<String> classNameFilter() throws IgniteCheckedException { ClassSet whiteList = classWhiteList(); ClassSet blackList = classBlackList(); return new IgnitePredicate<String>() { @Override public boolean apply(String s) { // Allows all primitive arrays and checks arrays' type. if ((blackList != null || whiteList != null) && s.charAt(0) == '[') { if (s.charAt(1) == 'L' && s.length() > 2) s = s.substring(2, s.length() - 1); else return true; } return (blackList == null || !blackList.contains(s)) && (whiteList == null || whiteList.contains(s)); } }; } /** * @return White list of classes. */ private ClassSet classWhiteList() throws IgniteCheckedException { ClassSet clsSet = null; String fileName = IgniteSystemProperties.getString(IgniteSystemProperties.IGNITE_MARSHALLER_WHITELIST); if (fileName != null) { clsSet = new ClassSet(); addClassNames(JDK_CLS_NAMES_FILE, clsSet); addClassNames(CLS_NAMES_FILE, clsSet); addClassNames(fileName, clsSet); } return clsSet; } /** * @return Black list of classes. */ private ClassSet classBlackList() throws IgniteCheckedException { ClassSet clsSet = null; String blackListFileName = IgniteSystemProperties.getString(IgniteSystemProperties.IGNITE_MARSHALLER_BLACKLIST); if (blackListFileName != null) addClassNames(blackListFileName, clsSet = new ClassSet()); return clsSet; } /** * Reads class names from resource referred by given system property name and returns set of classes. * * @param fileName File name containing list of classes. * @param clsSet Class set for update. * @return Set of classes. */ private void addClassNames(String fileName, ClassSet clsSet) throws IgniteCheckedException { InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName); if (is == null) { try { is = new FileInputStream(new File(fileName)); } catch (FileNotFoundException e) { throw new IgniteCheckedException("File " + fileName + " not found."); } } try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { String line; for (int i = 1; (line = reader.readLine()) != null; i++) { String s = line.trim(); if (!s.isEmpty() && s.charAt(0) != '#' && s.charAt(0) != '[') { try { clsSet.add(s); } catch (IllegalArgumentException e) { throw new IgniteCheckedException("Exception occurred while reading list of classes" + "[path=" + fileName + ", row=" + i + ", line=" + s + ']', e); } } } } catch (IOException e) { throw new IgniteCheckedException("Exception occurred while reading and creating list of classes " + "[path=" + fileName + ']', e); } } /** * Add helper. * * @param helper Helper. */ private void addHelper(Object helper) { ctx.addHelper(helper); } /** * Gets "on" or "off" string for given boolean value. * * @param b Boolean value to convert. * @return Result string. */ private String onOff(boolean b) { return b ? "on" : "off"; } /** * @return Whether or not REST is enabled. */ private boolean isRestEnabled() { assert cfg != null; return cfg.getConnectorConfiguration() != null && // By default rest processor doesn't start on client nodes. (!isClientNode() || (isClientNode() && IgniteSystemProperties.getBoolean(IGNITE_REST_START_ON_CLIENT))); } /** * @return {@code True} if node client or daemon otherwise {@code false}. */ private boolean isClientNode() { return cfg.isClientMode() || cfg.isDaemon(); } /** * Acks remote management. */ private void ackRemoteManagement() { assert log != null; if (!log.isInfoEnabled()) return; SB sb = new SB(); sb.a("Remote Management ["); boolean on = isJmxRemoteEnabled(); sb.a("restart: ").a(onOff(isRestartEnabled())).a(", "); sb.a("REST: ").a(onOff(isRestEnabled())).a(", "); sb.a("JMX ("); sb.a("remote: ").a(onOff(on)); if (on) { sb.a(", "); sb.a("port: ").a(System.getProperty("com.sun.management.jmxremote.port", "<n/a>")).a(", "); sb.a("auth: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.authenticate"))).a(", "); // By default SSL is enabled, that's why additional check for null is needed. // See http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html sb.a("ssl: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.ssl") || System.getProperty("com.sun.management.jmxremote.ssl") == null)); } sb.a(")"); sb.a(']'); log.info(sb.toString()); } /** * Acks configuration URL. */ private void ackConfigUrl() { assert log != null; if (log.isInfoEnabled()) log.info("Config URL: " + System.getProperty(IGNITE_CONFIG_URL, "n/a")); } /** * Acks configuration. */ private void ackConfiguration(IgniteConfiguration cfg) { assert log != null; if (log.isInfoEnabled()) log.info(cfg.toString()); } /** * Acks Logger configuration. */ private void ackLogger() { assert log != null; if (log.isInfoEnabled()) log.info("Logger: " + log.getLoggerInfo()); } /** * Acks ASCII-logo. Thanks to http://patorjk.com/software/taag */ private void ackAsciiLogo() { assert log != null; if (System.getProperty(IGNITE_NO_ASCII) == null) { String ver = "ver. " + ACK_VER_STR; // Big thanks to: http://patorjk.com/software/taag // Font name "Small Slant" if (log.isInfoEnabled()) { log.info(NL + NL + ">>> __________ ________________ " + NL + ">>> / _/ ___/ |/ / _/_ __/ __/ " + NL + ">>> _/ // (7 7 // / / / / _/ " + NL + ">>> /___/\\___/_/|_/___/ /_/ /___/ " + NL + ">>> " + NL + ">>> " + ver + NL + ">>> " + COPYRIGHT + NL + ">>> " + NL + ">>> Ignite documentation: " + "http://" + SITE + NL ); } if (log.isQuiet()) { U.quiet(false, " __________ ________________ ", " / _/ ___/ |/ / _/_ __/ __/ ", " _/ // (7 7 // / / / / _/ ", "/___/\\___/_/|_/___/ /_/ /___/ ", "", ver, COPYRIGHT, "", "Ignite documentation: " + "http://" + SITE, "", "Quiet mode."); String fileName = log.fileName(); if (fileName != null) U.quiet(false, " ^-- Logging to file '" + fileName + '\''); U.quiet(false, " ^-- Logging by '" + log.getLoggerInfo() + '\''); U.quiet(false, " ^-- To see **FULL** console log here add -DIGNITE_QUIET=false or \"-v\" to ignite.{sh|bat}", ""); } } } /** * Prints start info. * * @param rtBean Java runtime bean. */ private void ackStart(RuntimeMXBean rtBean) { ClusterNode locNode = localNode(); if (log.isQuiet()) { U.quiet(false, ""); U.quiet(false, "Ignite node started OK (id=" + U.id8(locNode.id()) + (F.isEmpty(igniteInstanceName) ? "" : ", instance name=" + igniteInstanceName) + ')'); } if (log.isInfoEnabled()) { log.info(""); String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR; String dash = U.dash(ack.length()); SB sb = new SB(); for (GridPortRecord rec : ctx.ports().records()) sb.a(rec.protocol()).a(":").a(rec.port()).a(" "); String str = NL + NL + ">>> " + dash + NL + ">>> " + ack + NL + ">>> " + dash + NL + ">>> OS name: " + U.osString() + NL + ">>> CPU(s): " + locNode.metrics().getTotalCpus() + NL + ">>> Heap: " + U.heapSize(locNode, 2) + "GB" + NL + ">>> VM name: " + rtBean.getName() + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Local node [" + "ID=" + locNode.id().toString().toUpperCase() + ", order=" + locNode.order() + ", clientMode=" + ctx.clientNode() + "]" + NL + ">>> Local node addresses: " + U.addressesAsString(locNode) + NL + ">>> Local ports: " + sb + NL; log.info(str); } if (!cluster().active()) { U.quietAndInfo(log, ">>> Ignite cluster is not active (limited functionality available). " + "Use control.(sh|bat) script or IgniteCluster interface to activate."); } } /** * Logs out OS information. */ private void ackOsInfo() { assert log != null; if (log.isQuiet()) U.quiet(false, "OS: " + U.osString()); if (log.isInfoEnabled()) { log.info("OS: " + U.osString()); log.info("OS user: " + System.getProperty("user.name")); int jvmPid = U.jvmPid(); log.info("PID: " + (jvmPid == -1 ? "N/A" : jvmPid)); } } /** * Logs out language runtime. */ private void ackLanguageRuntime() { assert log != null; if (log.isQuiet()) U.quiet(false, "VM information: " + U.jdkString()); if (log.isInfoEnabled()) { log.info("Language runtime: " + getLanguage()); log.info("VM information: " + U.jdkString()); log.info("VM total memory: " + U.heapSize(2) + "GB"); } } /** * @return Language runtime. */ @SuppressWarnings("ThrowableInstanceNeverThrown") private String getLanguage() { boolean scala = false; boolean groovy = false; boolean clojure = false; for (StackTraceElement elem : Thread.currentThread().getStackTrace()) { String s = elem.getClassName().toLowerCase(); if (s.contains("scala")) { scala = true; break; } else if (s.contains("groovy")) { groovy = true; break; } else if (s.contains("clojure")) { clojure = true; break; } } if (scala) { try (InputStream in = getClass().getResourceAsStream("/library.properties")) { Properties props = new Properties(); if (in != null) props.load(in); return "Scala ver. " + props.getProperty("version.number", "<unknown>"); } catch (Exception ignore) { return "Scala ver. <unknown>"; } } // How to get Groovy and Clojure version at runtime?!? return groovy ? "Groovy" : clojure ? "Clojure" : U.jdkName() + " ver. " + U.jdkVersion(); } /** * Stops grid instance. * * @param cancel Whether or not to cancel running jobs. */ public void stop(boolean cancel) { // Make sure that thread stopping grid is not interrupted. boolean interrupted = Thread.interrupted(); try { stop0(cancel); } finally { if (interrupted) Thread.currentThread().interrupt(); } } /** * @return {@code True} if node started shutdown sequence. */ public boolean isStopping() { return stopGuard.get(); } /** * @param cancel Whether or not to cancel running jobs. */ private void stop0(boolean cancel) { gw.compareAndSet(null, new GridKernalGatewayImpl(igniteInstanceName)); GridKernalGateway gw = this.gw.get(); if (stopGuard.compareAndSet(false, true)) { // Only one thread is allowed to perform stop sequence. boolean firstStop = false; GridKernalState state = gw.getState(); if (state == STARTED || state == DISCONNECTED) firstStop = true; else if (state == STARTING) U.warn(log, "Attempt to stop starting grid. This operation " + "cannot be guaranteed to be successful."); if (firstStop) { // Notify lifecycle beans. if (log.isDebugEnabled()) log.debug("Notifying lifecycle beans."); notifyLifecycleBeansEx(LifecycleEventType.BEFORE_NODE_STOP); } List<GridComponent> comps = ctx.components(); // Callback component in reverse order while kernal is still functional // if called in the same thread, at least. for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) comp.onKernalStop(cancel); } catch (Throwable e) { errOnStop = true; U.error(log, "Failed to pre-stop processor: " + comp, e); if (e instanceof Error) throw e; } } if (starveTask != null) starveTask.close(); if (metricsLogTask != null) metricsLogTask.close(); if (longOpDumpTask != null) longOpDumpTask.close(); boolean interrupted = false; while (true) { try { if (gw.tryWriteLock(10)) break; } catch (InterruptedException ignored) { // Preserve interrupt status & ignore. // Note that interrupted flag is cleared. interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); try { assert gw.getState() == STARTED || gw.getState() == STARTING || gw.getState() == DISCONNECTED; // No more kernal calls from this point on. gw.setState(STOPPING); ctx.cluster().get().clearNodeMap(); if (log.isDebugEnabled()) log.debug("Grid " + (igniteInstanceName == null ? "" : '\'' + igniteInstanceName + "' ") + "is stopping."); } finally { gw.writeUnlock(); } // Stopping cache operations. GridCacheProcessor cache = ctx.cache(); if (cache != null) cache.blockGateways(); // Unregister MBeans. if (!mBeansMgr.unregisterAllMBeans()) errOnStop = true; // Stop components in reverse order. for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) { comp.stop(cancel); if (log.isDebugEnabled()) log.debug("Component stopped: " + comp); } } catch (Throwable e) { errOnStop = true; U.error(log, "Failed to stop component (ignoring): " + comp, e); if (e instanceof Error) throw (Error)e; } } // Stops lifecycle aware components. U.stopLifecycleAware(log, lifecycleAwares(cfg)); // Lifecycle notification. notifyLifecycleBeansEx(LifecycleEventType.AFTER_NODE_STOP); // Clean internal class/classloader caches to avoid stopped contexts held in memory. U.clearClassCache(); MarshallerExclusions.clearCache(); BinaryEnumCache.clear(); gw.writeLock(); try { gw.setState(STOPPED); } finally { gw.writeUnlock(); } // Ack stop. if (log.isQuiet()) { String nodeName = igniteInstanceName == null ? "" : "name=" + igniteInstanceName + ", "; if (!errOnStop) U.quiet(false, "Ignite node stopped OK [" + nodeName + "uptime=" + X.timeSpan2HMSM(U.currentTimeMillis() - startTime) + ']'); else U.quiet(true, "Ignite node stopped wih ERRORS [" + nodeName + "uptime=" + X.timeSpan2HMSM(U.currentTimeMillis() - startTime) + ']'); } if (log.isInfoEnabled()) if (!errOnStop) { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR + " stopped OK"; String dash = U.dash(ack.length()); log.info(NL + NL + ">>> " + dash + NL + ">>> " + ack + NL + ">>> " + dash + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Grid uptime: " + X.timeSpan2HMSM(U.currentTimeMillis() - startTime) + NL + NL); } else { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR + " stopped with ERRORS"; String dash = U.dash(ack.length()); log.info(NL + NL + ">>> " + ack + NL + ">>> " + dash + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Grid uptime: " + X.timeSpan2HMSM(U.currentTimeMillis() - startTime) + NL + ">>> See log above for detailed error message." + NL + ">>> Note that some errors during stop can prevent grid from" + NL + ">>> maintaining correct topology since this node may have" + NL + ">>> not exited grid properly." + NL + NL); } try { U.onGridStop(); } catch (InterruptedException ignored) { // Preserve interrupt status. Thread.currentThread().interrupt(); } } else { // Proper notification. if (log.isDebugEnabled()) { if (gw.getState() == STOPPED) log.debug("Grid is already stopped. Nothing to do."); else log.debug("Grid is being stopped by another thread. Aborting this stop sequence " + "allowing other thread to finish."); } } } /** * USED ONLY FOR TESTING. * * @param name Cache name. * @param <K> Key type. * @param <V> Value type. * @return Internal cache instance. */ /*@java.test.only*/ public <K, V> GridCacheAdapter<K, V> internalCache(String name) { CU.validateCacheName(name); checkClusterState(); return ctx.cache().internalCache(name); } /** * It's intended for use by internal marshalling implementation only. * * @return Kernal context. */ @Override public GridKernalContext context() { return ctx; } /** * Prints all system properties in debug mode. */ private void ackSystemProperties() { assert log != null; if (log.isDebugEnabled() && S.INCLUDE_SENSITIVE) for (Map.Entry<Object, Object> entry : snapshot().entrySet()) log.debug("System property [" + entry.getKey() + '=' + entry.getValue() + ']'); } /** * Prints all user attributes in info mode. */ private void logNodeUserAttributes() { assert log != null; if (log.isInfoEnabled()) for (Map.Entry<?, ?> attr : cfg.getUserAttributes().entrySet()) log.info("Local node user attribute [" + attr.getKey() + '=' + attr.getValue() + ']'); } /** * Prints all environment variables in debug mode. */ private void ackEnvironmentVariables() { assert log != null; if (log.isDebugEnabled()) for (Map.Entry<?, ?> envVar : System.getenv().entrySet()) log.debug("Environment variable [" + envVar.getKey() + '=' + envVar.getValue() + ']'); } /** * Acks daemon mode status. */ private void ackDaemon() { assert log != null; if (log.isInfoEnabled()) log.info("Daemon mode: " + (isDaemon() ? "on" : "off")); } /** * @return {@code True} is this node is daemon. */ private boolean isDaemon() { assert cfg != null; return cfg.isDaemon() || IgniteSystemProperties.getBoolean(IGNITE_DAEMON); } /** * Whether or not remote JMX management is enabled for this node. Remote JMX management is enabled when the * following system property is set: <ul> <li>{@code com.sun.management.jmxremote}</li> </ul> * * @return {@code True} if remote JMX management is enabled - {@code false} otherwise. */ @Override public boolean isJmxRemoteEnabled() { return System.getProperty("com.sun.management.jmxremote") != null; } /** * Whether or not node restart is enabled. Node restart us supported when this node was started with {@code * bin/ignite.{sh|bat}} script using {@code -r} argument. Node can be programmatically restarted using {@link * Ignition#restart(boolean)}} method. * * @return {@code True} if restart mode is enabled, {@code false} otherwise. * @see Ignition#restart(boolean) */ @Override public boolean isRestartEnabled() { return System.getProperty(IGNITE_SUCCESS_FILE) != null; } /** * Prints all configuration properties in info mode and SPIs in debug mode. */ private void ackSpis() { assert log != null; if (log.isDebugEnabled()) { log.debug("+-------------+"); log.debug("START SPI LIST:"); log.debug("+-------------+"); log.debug("Grid checkpoint SPI : " + Arrays.toString(cfg.getCheckpointSpi())); log.debug("Grid collision SPI : " + cfg.getCollisionSpi()); log.debug("Grid communication SPI : " + cfg.getCommunicationSpi()); log.debug("Grid deployment SPI : " + cfg.getDeploymentSpi()); log.debug("Grid discovery SPI : " + cfg.getDiscoverySpi()); log.debug("Grid event storage SPI : " + cfg.getEventStorageSpi()); log.debug("Grid failover SPI : " + Arrays.toString(cfg.getFailoverSpi())); log.debug("Grid load balancing SPI : " + Arrays.toString(cfg.getLoadBalancingSpi())); } } /** * */ private void ackRebalanceConfiguration() throws IgniteCheckedException { if (cfg.getSystemThreadPoolSize() <= cfg.getRebalanceThreadPoolSize()) throw new IgniteCheckedException("Rebalance thread pool size exceed or equals System thread pool size. " + "Change IgniteConfiguration.rebalanceThreadPoolSize property before next start."); if (cfg.getRebalanceThreadPoolSize() < 1) throw new IgniteCheckedException("Rebalance thread pool size minimal allowed value is 1. " + "Change IgniteConfiguration.rebalanceThreadPoolSize property before next start."); for (CacheConfiguration ccfg : cfg.getCacheConfiguration()) { if (ccfg.getRebalanceBatchesPrefetchCount() < 1) throw new IgniteCheckedException("Rebalance batches prefetch count minimal allowed value is 1. " + "Change CacheConfiguration.rebalanceBatchesPrefetchCount property before next start. " + "[cache=" + ccfg.getName() + "]"); } } /** * */ private void ackMemoryConfiguration() { DataStorageConfiguration memCfg = cfg.getDataStorageConfiguration(); if (memCfg == null) return; U.log(log, "System cache's DataRegion size is configured to " + (memCfg.getSystemRegionInitialSize() / (1024 * 1024)) + " MB. " + "Use DataStorageConfiguration.systemCacheMemorySize property to change the setting."); } /** * */ private void ackCacheConfiguration() { CacheConfiguration[] cacheCfgs = cfg.getCacheConfiguration(); if (cacheCfgs == null || cacheCfgs.length == 0) U.warn(log, "Cache is not configured - in-memory data grid is off."); else { SB sb = new SB(); HashMap<String, ArrayList<String>> memPlcNamesMapping = new HashMap<>(); for (CacheConfiguration c : cacheCfgs) { String cacheName = U.maskName(c.getName()); String memPlcName = c.getDataRegionName(); if (CU.isSystemCache(cacheName)) memPlcName = "sysMemPlc"; else if (memPlcName == null && cfg.getDataStorageConfiguration() != null) memPlcName = cfg.getDataStorageConfiguration().getDefaultDataRegionConfiguration().getName(); if (!memPlcNamesMapping.containsKey(memPlcName)) memPlcNamesMapping.put(memPlcName, new ArrayList<String>()); ArrayList<String> cacheNames = memPlcNamesMapping.get(memPlcName); cacheNames.add(cacheName); } for (Map.Entry<String, ArrayList<String>> e : memPlcNamesMapping.entrySet()) { sb.a("in '").a(e.getKey()).a("' dataRegion: ["); for (String s : e.getValue()) sb.a("'").a(s).a("', "); sb.d(sb.length() - 2, sb.length()).a("], "); } U.log(log, "Configured caches [" + sb.d(sb.length() - 2, sb.length()).toString() + ']'); } } /** * */ private void ackP2pConfiguration() { assert cfg != null; if (cfg.isPeerClassLoadingEnabled()) U.warn( log, "Peer class loading is enabled (disable it in production for performance and " + "deployment consistency reasons)", "Peer class loading is enabled (disable it for better performance)" ); } /** * Prints security status. */ private void ackSecurity() { assert log != null; U.quietAndInfo(log, "Security status [authentication=" + onOff(ctx.security().enabled()) + ", tls/ssl=" + onOff(ctx.config().getSslContextFactory() != null) + ']'); } /** * Prints out VM arguments and IGNITE_HOME in info mode. * * @param rtBean Java runtime bean. */ private void ackVmArguments(RuntimeMXBean rtBean) { assert log != null; // Ack IGNITE_HOME and VM arguments. if (log.isInfoEnabled() && S.INCLUDE_SENSITIVE) { log.info("IGNITE_HOME=" + cfg.getIgniteHome()); log.info("VM arguments: " + rtBean.getInputArguments()); } } /** * Prints out class paths in debug mode. * * @param rtBean Java runtime bean. */ private void ackClassPaths(RuntimeMXBean rtBean) { assert log != null; // Ack all class paths. if (log.isDebugEnabled()) { try { log.debug("Boot class path: " + rtBean.getBootClassPath()); log.debug("Class path: " + rtBean.getClassPath()); log.debug("Library path: " + rtBean.getLibraryPath()); } catch (Exception ignore) { // No-op: ignore for Java 9+ and non-standard JVMs. } } } /** * @param cfg Grid configuration. * @return Components provided in configuration which can implement {@link LifecycleAware} interface. */ private Iterable<Object> lifecycleAwares(IgniteConfiguration cfg) { Collection<Object> objs = new ArrayList<>(); if (cfg.getLifecycleBeans() != null) Collections.addAll(objs, cfg.getLifecycleBeans()); if (cfg.getSegmentationResolvers() != null) Collections.addAll(objs, cfg.getSegmentationResolvers()); if (cfg.getConnectorConfiguration() != null) { objs.add(cfg.getConnectorConfiguration().getMessageInterceptor()); objs.add(cfg.getConnectorConfiguration().getSslContextFactory()); } objs.add(cfg.getMarshaller()); objs.add(cfg.getGridLogger()); objs.add(cfg.getMBeanServer()); if (cfg.getCommunicationFailureResolver() != null) objs.add(cfg.getCommunicationFailureResolver()); return objs; } /** {@inheritDoc} */ @Override public IgniteConfiguration configuration() { return cfg; } /** {@inheritDoc} */ @Override public IgniteLogger log() { return cfg.getGridLogger(); } /** {@inheritDoc} */ @Override public boolean removeCheckpoint(String key) { A.notNull(key, "key"); guard(); try { checkClusterState(); return ctx.checkpoint().removeCheckpoint(key); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean pingNode(String nodeId) { A.notNull(nodeId, "nodeId"); return cluster().pingNode(UUID.fromString(nodeId)); } /** {@inheritDoc} */ @Override public void undeployTaskFromGrid(String taskName) throws JMException { A.notNull(taskName, "taskName"); try { compute().undeployTask(taskName); } catch (IgniteException e) { throw U.jmException(e); } } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public String executeTask(String taskName, String arg) throws JMException { try { return compute().execute(taskName, arg); } catch (IgniteException e) { throw U.jmException(e); } } /** {@inheritDoc} */ @Override public boolean pingNodeByAddress(String host) { guard(); try { for (ClusterNode n : cluster().nodes()) if (n.addresses().contains(host)) return ctx.discovery().pingNode(n.id()); return false; } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean eventUserRecordable(int type) { guard(); try { return ctx.event().isUserRecordable(type); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean allEventsUserRecordable(int[] types) { A.notNull(types, "types"); guard(); try { return ctx.event().isAllUserRecordable(types); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteTransactions transactions() { guard(); try { checkClusterState(); return ctx.cache().transactions(); } finally { unguard(); } } /** * @param name Cache name. * @return Cache. */ public <K, V> IgniteInternalCache<K, V> getCache(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().publicCache(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> cache(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().publicJCache(name, false, true); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache(CacheConfiguration<K, V> cacheCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateCacheName(cacheCfg.getName()); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), null, true, true, true).get(); return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteCache> createCaches(Collection<CacheConfiguration> cacheCfgs) { A.notNull(cacheCfgs, "cacheCfgs"); CU.validateConfigurationCacheNames(cacheCfgs); guard(); try { checkClusterState(); ctx.cache().dynamicStartCaches(cacheCfgs, true, true, false).get(); List<IgniteCache> createdCaches = new ArrayList<>(cacheCfgs.size()); for (CacheConfiguration cacheCfg : cacheCfgs) createdCaches.add(ctx.cache().publicJCache(cacheCfg.getName())); return createdCaches; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache(String cacheName) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); ctx.cache().createFromTemplate(cacheName).get(); return ctx.cache().publicJCache(cacheName); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg) { return getOrCreateCache0(cacheCfg, false).get1(); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public <K, V> IgniteBiTuple<IgniteCache<K, V>, Boolean> getOrCreateCache0( CacheConfiguration<K, V> cacheCfg, boolean sql) { A.notNull(cacheCfg, "cacheCfg"); CU.validateCacheName(cacheCfg.getName()); guard(); try { checkClusterState(); Boolean res = false; if (ctx.cache().cache(cacheCfg.getName()) == null) { res = sql ? ctx.cache().dynamicStartSqlCache(cacheCfg).get() : ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), null, false, true, true).get(); } return new IgniteBiTuple<>((IgniteCache<K, V>)ctx.cache().publicJCache(cacheCfg.getName()), res); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteCache> getOrCreateCaches(Collection<CacheConfiguration> cacheCfgs) { A.notNull(cacheCfgs, "cacheCfgs"); CU.validateConfigurationCacheNames(cacheCfgs); guard(); try { checkClusterState(); ctx.cache().dynamicStartCaches(cacheCfgs, false, true, false).get(); List<IgniteCache> createdCaches = new ArrayList<>(cacheCfgs.size()); for (CacheConfiguration cacheCfg : cacheCfgs) createdCaches.add(ctx.cache().publicJCache(cacheCfg.getName())); return createdCaches; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache( CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg ) { A.notNull(cacheCfg, "cacheCfg"); CU.validateCacheName(cacheCfg.getName()); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, true, true, true).get(); return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateCacheName(cacheCfg.getName()); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); IgniteInternalCache<Object, Object> cache = ctx.cache().cache(cacheCfg.getName()); if (cache == null) { ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true, true).get(); } else { if (cache.configuration().getNearConfiguration() == null) { ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true, true).get(); } } return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) { CU.validateCacheName(cacheName); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(null, cacheName, nearCfg, true, true, true).get(); IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName); checkNearCacheStarted(cache); return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) { CU.validateCacheName(cacheName); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); IgniteInternalCache<Object, Object> internalCache = ctx.cache().cache(cacheName); if (internalCache == null) { ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true, true).get(); } else { if (internalCache.configuration().getNearConfiguration() == null) { ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true, true).get(); } } IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName); checkNearCacheStarted(cache); return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @param cache Cache. * @throws IgniteCheckedException If cache without near cache was already started. */ private void checkNearCacheStarted(IgniteCacheProxy<?, ?> cache) throws IgniteCheckedException { if (!cache.context().isNear()) throw new IgniteCheckedException("Failed to start near cache " + "(a cache with the same name without near cache is already started)"); } /** {@inheritDoc} */ @Override public void destroyCache(String cacheName) { destroyCache0(cacheName, false); } /** {@inheritDoc} */ @Override public boolean destroyCache0(String cacheName, boolean sql) throws CacheException { CU.validateCacheName(cacheName); IgniteInternalFuture<Boolean> stopFut = destroyCacheAsync(cacheName, sql, true); try { return stopFut.get(); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } } /** {@inheritDoc} */ @Override public void destroyCaches(Collection<String> cacheNames) { CU.validateCacheNames(cacheNames); IgniteInternalFuture stopFut = destroyCachesAsync(cacheNames, true); try { stopFut.get(); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } } /** * @param cacheName Cache name. * @param sql If the cache needs to be destroyed only if it was created by SQL {@code CREATE TABLE} command. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Ignite future. */ public IgniteInternalFuture<Boolean> destroyCacheAsync(String cacheName, boolean sql, boolean checkThreadTx) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); return ctx.cache().dynamicDestroyCache(cacheName, sql, checkThreadTx, false); } finally { unguard(); } } /** * @param cacheNames Collection of cache names. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Ignite future. */ public IgniteInternalFuture<?> destroyCachesAsync(Collection<String> cacheNames, boolean checkThreadTx) { CU.validateCacheNames(cacheNames); guard(); try { checkClusterState(); return ctx.cache().dynamicDestroyCaches(cacheNames, checkThreadTx, false); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(String cacheName) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); if (ctx.cache().cache(cacheName) == null) ctx.cache().getOrCreateFromTemplate(cacheName, true).get(); return ctx.cache().publicJCache(cacheName); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @param cacheName Cache name. * @param templateName Template name. * @param cfgOverride Cache config properties to override. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when cache is deployed. */ public IgniteInternalFuture<?> getOrCreateCacheAsync(String cacheName, String templateName, CacheConfigurationOverride cfgOverride, boolean checkThreadTx) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); if (ctx.cache().cache(cacheName) == null) return ctx.cache().getOrCreateFromTemplate(cacheName, templateName, cfgOverride, checkThreadTx); return new GridFinishedFuture<>(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> void addCacheConfiguration(CacheConfiguration<K, V> cacheCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateCacheName(cacheCfg.getName()); guard(); try { checkClusterState(); ctx.cache().addCacheConfiguration(cacheCfg); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @return Public caches. */ public Collection<IgniteCacheProxy<?, ?>> caches() { guard(); try { checkClusterState(); return ctx.cache().publicCaches(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<String> cacheNames() { guard(); try { checkClusterState(); return ctx.cache().publicCacheNames(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K extends GridCacheUtilityKey, V> IgniteInternalCache<K, V> utilityCache() { guard(); try { checkClusterState(); return ctx.cache().utilityCache(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteInternalCache<K, V> cachex(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().cache(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteInternalCache<?, ?>> cachesx( IgnitePredicate<? super IgniteInternalCache<?, ?>>[] p) { guard(); try { checkClusterState(); return F.retain(ctx.cache().caches(), true, p); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteDataStreamer<K, V> dataStreamer(String cacheName) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); return ctx.<K, V>dataStream().dataStreamer(cacheName); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteFileSystem fileSystem(String name) { if (name == null) throw new IllegalArgumentException("IGFS name cannot be null"); guard(); try { checkClusterState(); IgniteFileSystem fs = ctx.igfs().igfs(name); if (fs == null) throw new IllegalArgumentException("IGFS is not configured: " + name); return fs; } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteFileSystem igfsx(String name) { if (name == null) throw new IllegalArgumentException("IGFS name cannot be null"); guard(); try { checkClusterState(); return ctx.igfs().igfs(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteFileSystem> fileSystems() { guard(); try { checkClusterState(); return ctx.igfs().igfss(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Hadoop hadoop() { guard(); try { checkClusterState(); return ctx.hadoop().hadoop(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <T extends IgnitePlugin> T plugin(String name) throws PluginNotFoundException { guard(); try { checkClusterState(); return (T)ctx.pluginProvider(name).plugin(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteBinary binary() { checkClusterState(); IgniteCacheObjectProcessor objProc = ctx.cacheObjects(); return objProc.binary(); } /** {@inheritDoc} */ @Override public IgniteProductVersion version() { return VER; } /** {@inheritDoc} */ @Override public String latestVersion() { ctx.gateway().readLock(); try { return ctx.cluster().latestVersion(); } finally { ctx.gateway().readUnlock(); } } /** {@inheritDoc} */ @Override public IgniteScheduler scheduler() { return scheduler; } /** {@inheritDoc} */ @Override public void close() throws IgniteException { Ignition.stop(igniteInstanceName, true); } @Override public <K> Affinity<K> affinity(String cacheName) { CU.validateCacheName(cacheName); checkClusterState(); GridCacheAdapter<K, ?> cache = ctx.cache().internalCache(cacheName); if (cache != null) return cache.affinity(); return ctx.affinity().affinityProxy(cacheName); } /** {@inheritDoc} */ @Override public boolean active() { guard(); try { return context().state().publicApiActiveState(true); } finally { unguard(); } } /** {@inheritDoc} */ @Override public void active(boolean active) { cluster().active(active); } /** */ private Collection<BaselineNode> baselineNodes() { Collection<ClusterNode> srvNodes = cluster().forServers().nodes(); ArrayList baselineNodes = new ArrayList(srvNodes.size()); for (ClusterNode clN : srvNodes) baselineNodes.add(clN); return baselineNodes; } /** {@inheritDoc} */ @Override public void resetLostPartitions(Collection<String> cacheNames) { CU.validateCacheNames(cacheNames); guard(); try { ctx.cache().resetCacheState(cacheNames).get(); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<DataRegionMetrics> dataRegionMetrics() { guard(); try { return ctx.cache().context().database().memoryMetrics(); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public DataRegionMetrics dataRegionMetrics(String memPlcName) { guard(); try { return ctx.cache().context().database().memoryMetrics(memPlcName); } finally { unguard(); } } /** {@inheritDoc} */ @Override public DataStorageMetrics dataStorageMetrics() { guard(); try { return ctx.cache().context().database().persistentStoreMetrics(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<MemoryMetrics> memoryMetrics() { return DataRegionMetricsAdapter.collectionOf(dataRegionMetrics()); } /** {@inheritDoc} */ @Nullable @Override public MemoryMetrics memoryMetrics(String memPlcName) { return DataRegionMetricsAdapter.valueOf(dataRegionMetrics(memPlcName)); } /** {@inheritDoc} */ @Override public PersistenceMetrics persistentStoreMetrics() { return DataStorageMetricsAdapter.valueOf(dataStorageMetrics()); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicSequence atomicSequence(String name, long initVal, boolean create) { return atomicSequence(name, null, initVal, create); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicSequence atomicSequence(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().sequence(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicLong atomicLong(String name, long initVal, boolean create) { return atomicLong(name, null, initVal, create); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicLong atomicLong(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicLong(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteAtomicReference<T> atomicReference( String name, @Nullable T initVal, boolean create ) { return atomicReference(name, null, initVal, create); } /** {@inheritDoc} */ @Override public <T> IgniteAtomicReference<T> atomicReference(String name, AtomicConfiguration cfg, @Nullable T initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicReference(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, @Nullable T initVal, @Nullable S initStamp, boolean create) { return atomicStamped(name, null, initVal, initStamp, create); } /** {@inheritDoc} */ @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, AtomicConfiguration cfg, @Nullable T initVal, @Nullable S initStamp, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicStamped(name, cfg, initVal, initStamp, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteCountDownLatch countDownLatch(String name, int cnt, boolean autoDel, boolean create) { guard(); try { checkClusterState(); return ctx.dataStructures().countDownLatch(name, null, cnt, autoDel, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteSemaphore semaphore( String name, int cnt, boolean failoverSafe, boolean create ) { guard(); try { checkClusterState(); return ctx.dataStructures().semaphore(name, null, cnt, failoverSafe, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteLock reentrantLock( String name, boolean failoverSafe, boolean fair, boolean create ) { guard(); try { checkClusterState(); return ctx.dataStructures().reentrantLock(name, null, failoverSafe, fair, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteQueue<T> queue(String name, int cap, CollectionConfiguration cfg) { guard(); try { checkClusterState(); return ctx.dataStructures().queue(name, null, cap, cfg); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteSet<T> set(String name, CollectionConfiguration cfg) { guard(); try { checkClusterState(); return ctx.dataStructures().set(name, null, cfg); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** * <tt>ctx.gateway().readLock()</tt> */ private void guard() { assert ctx != null; ctx.gateway().readLock(); } /** * <tt>ctx.gateway().readUnlock()</tt> */ private void unguard() { assert ctx != null; ctx.gateway().readUnlock(); } /** * Validate operation on cluster. Check current cluster state. * * @throws IgniteException if cluster in inActive state */ private void checkClusterState() throws IgniteException { if (!ctx.state().publicApiActiveState(true)) { throw new IgniteException("Can not perform the operation because the cluster is inactive. Note, that " + "the cluster is considered inactive by default if Ignite Persistent Store is used to let all the nodes " + "join the cluster. To activate the cluster call Ignite.active(true)."); } } /** * */ public void onDisconnected() { Throwable err = null; reconnectState.waitPreviousReconnect(); GridFutureAdapter<?> reconnectFut = ctx.gateway().onDisconnected(); if (reconnectFut == null) { assert ctx.gateway().getState() != STARTED : ctx.gateway().getState(); return; } IgniteFutureImpl<?> curFut = (IgniteFutureImpl<?>)ctx.cluster().get().clientReconnectFuture(); IgniteFuture<?> userFut; // In case of previous reconnect did not finish keep reconnect future. if (curFut != null && curFut.internalFuture() == reconnectFut) userFut = curFut; else { userFut = new IgniteFutureImpl<>(reconnectFut); ctx.cluster().get().clientReconnectFuture(userFut); } ctx.disconnected(true); List<GridComponent> comps = ctx.components(); for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) comp.onDisconnected(userFut); } catch (IgniteCheckedException e) { err = e; } catch (Throwable e) { err = e; if (e instanceof Error) throw e; } } for (GridCacheContext cctx : ctx.cache().context().cacheContexts()) { cctx.gate().writeLock(); cctx.gate().writeUnlock(); } ctx.gateway().writeLock(); ctx.gateway().writeUnlock(); if (err != null) { reconnectFut.onDone(err); U.error(log, "Failed to reconnect, will stop node", err); close(); } } /** * @param clusterRestarted {@code True} if all cluster nodes restarted while client was disconnected. */ @SuppressWarnings("unchecked") public void onReconnected(final boolean clusterRestarted) { Throwable err = null; try { ctx.disconnected(false); GridCompoundFuture curReconnectFut = reconnectState.curReconnectFut = new GridCompoundFuture<>(); reconnectState.reconnectDone = new GridFutureAdapter<>(); for (GridComponent comp : ctx.components()) { IgniteInternalFuture<?> fut = comp.onReconnected(clusterRestarted); if (fut != null) curReconnectFut.add(fut); } curReconnectFut.add(ctx.cache().context().exchange().reconnectExchangeFuture()); curReconnectFut.markInitialized(); final GridFutureAdapter reconnectDone = reconnectState.reconnectDone; curReconnectFut.listen(new CI1<IgniteInternalFuture<?>>() { @Override public void apply(IgniteInternalFuture<?> fut) { try { Object res = fut.get(); if (res == STOP_RECONNECT) return; ctx.gateway().onReconnected(); reconnectState.firstReconnectFut.onDone(); } catch (IgniteCheckedException e) { if (!X.hasCause(e, IgniteNeedReconnectException.class, IgniteClientDisconnectedCheckedException.class)) { U.error(log, "Failed to reconnect, will stop node.", e); reconnectState.firstReconnectFut.onDone(e); close(); } else { assert ctx.discovery().reconnectSupported(); U.error(log, "Failed to finish reconnect, will retry [locNodeId=" + ctx.localNodeId() + ", err=" + e.getMessage() + ']'); } } finally { reconnectDone.onDone(); } } }); } catch (IgniteCheckedException e) { err = e; } catch (Throwable e) { err = e; if (e instanceof Error) throw e; } if (err != null) { U.error(log, "Failed to reconnect, will stop node", err); close(); } } /** * Creates optional component. * * @param cls Component interface. * @param ctx Kernal context. * @return Created component. * @throws IgniteCheckedException If failed to create component. */ private static <T extends GridComponent> T createComponent(Class<T> cls, GridKernalContext ctx) throws IgniteCheckedException { assert cls.isInterface() : cls; T comp = ctx.plugins().createComponent(cls); if (comp != null) return comp; if (cls.equals(IgniteCacheObjectProcessor.class)) return (T)new CacheObjectBinaryProcessorImpl(ctx); if (cls.equals(DiscoveryNodeValidationProcessor.class)) return (T)new OsDiscoveryNodeValidationProcessor(ctx); if (cls.equals(IGridClusterStateProcessor.class)) return (T)new GridClusterStateProcessor(ctx); Class<T> implCls = null; try { String clsName; // Handle special case for PlatformProcessor if (cls.equals(PlatformProcessor.class)) clsName = ctx.config().getPlatformConfiguration() == null ? PlatformNoopProcessor.class.getName() : cls.getName() + "Impl"; else clsName = componentClassName(cls); implCls = (Class<T>)Class.forName(clsName); } catch (ClassNotFoundException ignore) { // No-op. } if (implCls == null) throw new IgniteCheckedException("Failed to find component implementation: " + cls.getName()); if (!cls.isAssignableFrom(implCls)) throw new IgniteCheckedException("Component implementation does not implement component interface " + "[component=" + cls.getName() + ", implementation=" + implCls.getName() + ']'); Constructor<T> constructor; try { constructor = implCls.getConstructor(GridKernalContext.class); } catch (NoSuchMethodException e) { throw new IgniteCheckedException("Component does not have expected constructor: " + implCls.getName(), e); } try { return constructor.newInstance(ctx); } catch (ReflectiveOperationException e) { throw new IgniteCheckedException("Failed to create component [component=" + cls.getName() + ", implementation=" + implCls.getName() + ']', e); } } /** * @param cls Component interface. * @return Name of component implementation class for open source edition. */ private static String componentClassName(Class<?> cls) { return cls.getPackage().getName() + ".os." + cls.getSimpleName().replace("Grid", "GridOs"); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igniteInstanceName = U.readString(in); } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igniteInstanceName); } /** * @return IgniteKernal instance. * @throws ObjectStreamException If failed. */ protected Object readResolve() throws ObjectStreamException { try { return IgnitionEx.localIgnite(); } catch (IllegalStateException e) { throw U.withCause(new InvalidObjectException(e.getMessage()), e); } } /** * @param comp Grid component. * @return {@code true} if node running in daemon mode and component marked by {@code SkipDaemon} annotation. */ private boolean skipDaemon(GridComponent comp) { return ctx.isDaemon() && U.hasAnnotation(comp.getClass(), SkipDaemon.class); } /** {@inheritDoc} */ @Override public void dumpDebugInfo() { try { GridKernalContextImpl ctx = this.ctx; GridDiscoveryManager discoMrg = ctx != null ? ctx.discovery() : null; ClusterNode locNode = discoMrg != null ? discoMrg.localNode() : null; if (ctx != null && discoMrg != null && locNode != null) { boolean client = ctx.clientNode(); UUID routerId = locNode instanceof TcpDiscoveryNode ? ((TcpDiscoveryNode)locNode).clientRouterNodeId() : null; U.warn(ctx.cluster().diagnosticLog(), "Dumping debug info for node [id=" + locNode.id() + ", name=" + ctx.igniteInstanceName() + ", order=" + locNode.order() + ", topVer=" + discoMrg.topologyVersion() + ", client=" + client + (client && routerId != null ? ", routerId=" + routerId : "") + ']'); ctx.cache().context().exchange().dumpDebugInfo(null); } else U.warn(log, "Dumping debug info for node, context is not initialized [name=" + igniteInstanceName + ']'); } catch (Exception e) { U.error(log, "Failed to dump debug info for node: " + e, e); } } /** * @param node Node. * @param payload Message payload. * @param procFromNioThread If {@code true} message is processed from NIO thread. * @return Response future. */ public IgniteInternalFuture sendIoTest(ClusterNode node, byte[] payload, boolean procFromNioThread) { return ctx.io().sendIoTest(node, payload, procFromNioThread); } /** * @param nodes Nodes. * @param payload Message payload. * @param procFromNioThread If {@code true} message is processed from NIO thread. * @return Response future. */ public IgniteInternalFuture sendIoTest(List<ClusterNode> nodes, byte[] payload, boolean procFromNioThread) { return ctx.io().sendIoTest(nodes, payload, procFromNioThread); } /** * */ private class ReconnectState { /** */ private final GridFutureAdapter firstReconnectFut = new GridFutureAdapter(); /** */ private GridCompoundFuture<?, Object> curReconnectFut; /** */ private GridFutureAdapter<?> reconnectDone; /** * @throws IgniteCheckedException If failed. */ void waitFirstReconnect() throws IgniteCheckedException { firstReconnectFut.get(); } /** * */ void waitPreviousReconnect() { if (curReconnectFut != null && !curReconnectFut.isDone()) { assert reconnectDone != null; curReconnectFut.onDone(STOP_RECONNECT); try { reconnectDone.get(); } catch (IgniteCheckedException ignote) { // No-op. } } } } /** * Class that registers and unregisters MBeans for kernal. */ private class MBeansManager { /** MBean names stored to be unregistered later. */ private final Set<ObjectName> mBeanNames = new HashSet<>(); /** * Registers all kernal MBeans (for kernal, metrics, thread pools). * * @param utilityCachePool Utility cache pool * @param execSvc Executor service * @param sysExecSvc System executor service * @param stripedExecSvc Striped executor * @param p2pExecSvc P2P executor service * @param mgmtExecSvc Management executor service * @param igfsExecSvc IGFS executor service * @param dataStreamExecSvc data stream executor service * @param restExecSvc Reset executor service * @param affExecSvc Affinity executor service * @param idxExecSvc Indexing executor service * @param callbackExecSvc Callback executor service * @param qryExecSvc Query executor service * @param schemaExecSvc Schema executor service * @param customExecSvcs Custom named executors * @throws IgniteCheckedException if fails to register any of the MBeans */ private void registerAllMBeans( ExecutorService utilityCachePool, final ExecutorService execSvc, final ExecutorService svcExecSvc, final ExecutorService sysExecSvc, final StripedExecutor stripedExecSvc, ExecutorService p2pExecSvc, ExecutorService mgmtExecSvc, ExecutorService igfsExecSvc, StripedExecutor dataStreamExecSvc, ExecutorService restExecSvc, ExecutorService affExecSvc, @Nullable ExecutorService idxExecSvc, IgniteStripedThreadPoolExecutor callbackExecSvc, ExecutorService qryExecSvc, ExecutorService schemaExecSvc, @Nullable final Map<String, ? extends ExecutorService> customExecSvcs, WorkersRegistry workersRegistry ) throws IgniteCheckedException { if (U.IGNITE_MBEANS_DISABLED) return; // Kernal registerMBean("Kernal", IgniteKernal.class.getSimpleName(), IgniteKernal.this, IgniteMXBean.class); // Metrics ClusterMetricsMXBean locMetricsBean = new ClusterLocalNodeMetricsMXBeanImpl(ctx.discovery()); registerMBean("Kernal", locMetricsBean.getClass().getSimpleName(), locMetricsBean, ClusterMetricsMXBean.class); ClusterMetricsMXBean metricsBean = new ClusterMetricsMXBeanImpl(cluster()); registerMBean("Kernal", metricsBean.getClass().getSimpleName(), metricsBean, ClusterMetricsMXBean.class); // Transaction metrics TransactionMetricsMxBean txMetricsMXBean = new TransactionMetricsMxBeanImpl(ctx.cache().transactions().metrics()); registerMBean("TransactionMetrics", txMetricsMXBean.getClass().getSimpleName(), txMetricsMXBean, TransactionMetricsMxBean.class); // Transactions TransactionsMXBean txMXBean = new TransactionsMXBeanImpl(ctx); registerMBean("Transactions", txMXBean.getClass().getSimpleName(), txMXBean, TransactionsMXBean.class); // Executors registerExecutorMBean("GridUtilityCacheExecutor", utilityCachePool); registerExecutorMBean("GridExecutionExecutor", execSvc); registerExecutorMBean("GridServicesExecutor", svcExecSvc); registerExecutorMBean("GridSystemExecutor", sysExecSvc); registerExecutorMBean("GridClassLoadingExecutor", p2pExecSvc); registerExecutorMBean("GridManagementExecutor", mgmtExecSvc); registerExecutorMBean("GridIgfsExecutor", igfsExecSvc); registerExecutorMBean("GridDataStreamExecutor", dataStreamExecSvc); registerExecutorMBean("GridAffinityExecutor", affExecSvc); registerExecutorMBean("GridCallbackExecutor", callbackExecSvc); registerExecutorMBean("GridQueryExecutor", qryExecSvc); registerExecutorMBean("GridSchemaExecutor", schemaExecSvc); if (idxExecSvc != null) registerExecutorMBean("GridIndexingExecutor", idxExecSvc); if (cfg.getConnectorConfiguration() != null) registerExecutorMBean("GridRestExecutor", restExecSvc); if (stripedExecSvc != null) { // striped executor uses a custom adapter registerMBean("Thread Pools", "StripedExecutor", new StripedExecutorMXBeanAdapter(stripedExecSvc), StripedExecutorMXBean.class); } if (customExecSvcs != null) { for (Map.Entry<String, ? extends ExecutorService> entry : customExecSvcs.entrySet()) registerExecutorMBean(entry.getKey(), entry.getValue()); } if (U.IGNITE_TEST_FEATURES_ENABLED) { WorkersControlMXBean workerCtrlMXBean = new WorkersControlMXBeanImpl(workersRegistry); registerMBean("Kernal", workerCtrlMXBean.getClass().getSimpleName(), workerCtrlMXBean, WorkersControlMXBean.class); } } /** * Registers a {@link ThreadPoolMXBean} for an executor. * * @param name name of the bean to register * @param exec executor to register a bean for * @throws IgniteCheckedException if registration fails. */ private void registerExecutorMBean(String name, ExecutorService exec) throws IgniteCheckedException { registerMBean("Thread Pools", name, new ThreadPoolMXBeanAdapter(exec), ThreadPoolMXBean.class); } /** * Register an Ignite MBean. * * @param grp bean group name * @param name bean name * @param impl bean implementation * @param itf bean interface * @param <T> bean type * @throws IgniteCheckedException if registration fails */ private <T> void registerMBean(String grp, String name, T impl, Class<T> itf) throws IgniteCheckedException { assert !U.IGNITE_MBEANS_DISABLED; try { ObjectName objName = U.registerMBean( cfg.getMBeanServer(), cfg.getIgniteInstanceName(), grp, name, impl, itf); if (log.isDebugEnabled()) log.debug("Registered MBean: " + objName); mBeanNames.add(objName); } catch (JMException e) { throw new IgniteCheckedException("Failed to register MBean " + name, e); } } /** * Unregisters all previously registered MBeans. * * @return {@code true} if all mbeans were unregistered successfully; {@code false} otherwise. */ private boolean unregisterAllMBeans() { boolean success = true; for (ObjectName name : mBeanNames) success = success && unregisterMBean(name); return success; } /** * Unregisters given MBean. * * @param mbean MBean to unregister. * @return {@code true} if successfully unregistered, {@code false} otherwise. */ private boolean unregisterMBean(ObjectName mbean) { assert !U.IGNITE_MBEANS_DISABLED; try { cfg.getMBeanServer().unregisterMBean(mbean); if (log.isDebugEnabled()) log.debug("Unregistered MBean: " + mbean); return true; } catch (JMException e) { U.error(log, "Failed to unregister MBean.", e); return false; } } } /** {@inheritDoc} */ @Override public void runIoTest( long warmup, long duration, int threads, long maxLatency, int rangesCnt, int payLoadSize, boolean procFromNioThread ) { ctx.io().runIoTest(warmup, duration, threads, maxLatency, rangesCnt, payLoadSize, procFromNioThread, new ArrayList(ctx.cluster().get().forServers().forRemotes().nodes())); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(IgniteKernal.class, this); } }
apache-2.0
qibin0506/MVPro
mvpro/src/main/java/org/loader/view/ViewImpl.java
973
package org.loader.view; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.loader.presenter.IPresenter; /** * View层的基类 * Created by qibin on 2015/11/15. */ public abstract class ViewImpl implements IView { /** * create方法生成的view */ protected View mRootView; /** * 绑定的presenter */ protected IPresenter mPresenter; @Override public View create(LayoutInflater inflater, ViewGroup container) { mRootView = inflater.inflate(getLayoutId(), container, false); created(); return mRootView; } @Override public <V extends View> V findViewById(int id) { return (V) mRootView.findViewById(id); } @Override public void created() { } @Override public void bindPresenter(IPresenter presenter) { mPresenter = presenter; } @Override public void bindEvent() { } }
apache-2.0
awsdocs/aws-doc-sdk-examples
java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesLoadData.java
3071
// snippet-sourcedescription:[ ] // snippet-service:[dynamodb] // snippet-keyword:[Java] // snippet-sourcesyntax:[java] // snippet-keyword:[Amazon DynamoDB] // snippet-keyword:[Code Sample] // snippet-keyword:[ ] // snippet-sourcetype:[full-example] // snippet-sourcedate:[ ] // snippet-sourceauthor:[AWS] // snippet-start:[dynamodb.java.codeexample.MoviesLoadData] /** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is 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/ * * 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.codesamples.gsg; import java.io.File; import java.util.Iterator; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.Table; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; public class MoviesLoadData { public static void main(String[] args) throws Exception { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) .build(); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("Movies"); JsonParser parser = new JsonFactory().createParser(new File("moviedata.json")); JsonNode rootNode = new ObjectMapper().readTree(parser); Iterator<JsonNode> iter = rootNode.iterator(); ObjectNode currentNode; while (iter.hasNext()) { currentNode = (ObjectNode) iter.next(); int year = currentNode.path("year").asInt(); String title = currentNode.path("title").asText(); try { table.putItem(new Item().withPrimaryKey("year", year, "title", title).withJSON("info", currentNode.path("info").toString())); System.out.println("PutItem succeeded: " + year + " " + title); } catch (Exception e) { System.err.println("Unable to add movie: " + year + " " + title); System.err.println(e.getMessage()); break; } } parser.close(); } } // snippet-end:[dynamodb.java.codeexample.MoviesLoadData]
apache-2.0
talsma-ict/umldoclet
src/plantuml-asl/src/net/sourceforge/plantuml/argon2/Validation.java
4298
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ /* This file is taken from https://github.com/andreas1327250/argon2-java Original Author: Andreas Gadermaier <up.gadermaier@gmail.com> */ package net.sourceforge.plantuml.argon2; import static net.sourceforge.plantuml.argon2.Constants.Constraints.MAX_AD_LENGTH; import static net.sourceforge.plantuml.argon2.Constants.Constraints.MAX_ITERATIONS; import static net.sourceforge.plantuml.argon2.Constants.Constraints.MAX_PARALLELISM; import static net.sourceforge.plantuml.argon2.Constants.Constraints.MAX_PWD_LENGTH; import static net.sourceforge.plantuml.argon2.Constants.Constraints.MAX_SALT_LENGTH; import static net.sourceforge.plantuml.argon2.Constants.Constraints.MAX_SECRET_LENGTH; import static net.sourceforge.plantuml.argon2.Constants.Constraints.MIN_ITERATIONS; import static net.sourceforge.plantuml.argon2.Constants.Constraints.MIN_PARALLELISM; import static net.sourceforge.plantuml.argon2.Constants.Constraints.MIN_PWD_LENGTH; import static net.sourceforge.plantuml.argon2.Constants.Constraints.MIN_SALT_LENGTH; import static net.sourceforge.plantuml.argon2.Constants.Messages.ADDITIONAL_MAX_MSG; import static net.sourceforge.plantuml.argon2.Constants.Messages.M_MIN_MSG; import static net.sourceforge.plantuml.argon2.Constants.Messages.PWD_MAX_MSG; import static net.sourceforge.plantuml.argon2.Constants.Messages.PWD_MIN_MSG; import static net.sourceforge.plantuml.argon2.Constants.Messages.P_MAX_MSG; import static net.sourceforge.plantuml.argon2.Constants.Messages.P_MIN_MSG; import static net.sourceforge.plantuml.argon2.Constants.Messages.SALT_MAX_MSG; import static net.sourceforge.plantuml.argon2.Constants.Messages.SALT_MIN_MSG; import static net.sourceforge.plantuml.argon2.Constants.Messages.SECRET_MAX_MSG; import static net.sourceforge.plantuml.argon2.Constants.Messages.T_MAX_MSG; import static net.sourceforge.plantuml.argon2.Constants.Messages.T_MIN_MSG; import net.sourceforge.plantuml.argon2.exception.Argon2InvalidParameterException; class Validation { static void validateInput(Argon2 argon2){ String message = null; if (argon2.getLanes() < MIN_PARALLELISM) message = P_MIN_MSG; else if (argon2.getLanes() > MAX_PARALLELISM) message = P_MAX_MSG; else if(argon2.getMemory() < 2 * argon2.getLanes()) message = M_MIN_MSG; else if(argon2.getIterations() < MIN_ITERATIONS) message = T_MIN_MSG; else if(argon2.getIterations() > MAX_ITERATIONS) message = T_MAX_MSG; else if(argon2.getPasswordLength() < MIN_PWD_LENGTH) message = PWD_MIN_MSG; else if(argon2.getPasswordLength() > MAX_PWD_LENGTH) message = PWD_MAX_MSG; else if(argon2.getSaltLength() < MIN_SALT_LENGTH) message = SALT_MIN_MSG; else if(argon2.getSaltLength() > MAX_SALT_LENGTH) message = SALT_MAX_MSG; else if(argon2.getSecretLength() > MAX_SECRET_LENGTH) message = SECRET_MAX_MSG; else if(argon2.getAdditionalLength() > MAX_AD_LENGTH) message = ADDITIONAL_MAX_MSG; if(message != null) throw new Argon2InvalidParameterException(message); } }
apache-2.0
bcopeland/hbase-thrift
src/main/java/org/apache/hadoop/hbase/HRegionInfo.java
23939
/** * Copyright 2007 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.KeyValue.KVComparator; import org.apache.hadoop.hbase.migration.HRegionInfo090x; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.FSTableDescriptors; import org.apache.hadoop.hbase.util.JenkinsHash; import org.apache.hadoop.hbase.util.MD5Hash; import org.apache.hadoop.io.VersionedWritable; import org.apache.hadoop.io.WritableComparable; /** * HRegion information. * Contains HRegion id, start and end keys, a reference to this * HRegions' table descriptor, etc. */ public class HRegionInfo extends VersionedWritable implements WritableComparable<HRegionInfo>{ private static final byte VERSION = 0; private static final Log LOG = LogFactory.getLog(HRegionInfo.class); /** * The new format for a region name contains its encodedName at the end. * The encoded name also serves as the directory name for the region * in the filesystem. * * New region name format: * &lt;tablename>,,&lt;startkey>,&lt;regionIdTimestamp>.&lt;encodedName>. * where, * &lt;encodedName> is a hex version of the MD5 hash of * &lt;tablename>,&lt;startkey>,&lt;regionIdTimestamp> * * The old region name format: * &lt;tablename>,&lt;startkey>,&lt;regionIdTimestamp> * For region names in the old format, the encoded name is a 32-bit * JenkinsHash integer value (in its decimal notation, string form). *<p> * **NOTE** * * ROOT, the first META region, and regions created by an older * version of HBase (0.20 or prior) will continue to use the * old region name format. */ /** Separator used to demarcate the encodedName in a region name * in the new format. See description on new format above. */ private static final int ENC_SEPARATOR = '.'; public static final int MD5_HEX_LENGTH = 32; /** * Does region name contain its encoded name? * @param regionName region name * @return boolean indicating if this a new format region * name which contains its encoded name. */ private static boolean hasEncodedName(final byte[] regionName) { // check if region name ends in ENC_SEPARATOR if ((regionName.length >= 1) && (regionName[regionName.length - 1] == ENC_SEPARATOR)) { // region name is new format. it contains the encoded name. return true; } return false; } /** * @param regionName * @return the encodedName */ public static String encodeRegionName(final byte [] regionName) { String encodedName; if (hasEncodedName(regionName)) { // region is in new format: // <tableName>,<startKey>,<regionIdTimeStamp>/encodedName/ encodedName = Bytes.toString(regionName, regionName.length - MD5_HEX_LENGTH - 1, MD5_HEX_LENGTH); } else { // old format region name. ROOT and first META region also // use this format.EncodedName is the JenkinsHash value. int hashVal = Math.abs(JenkinsHash.getInstance().hash(regionName, regionName.length, 0)); encodedName = String.valueOf(hashVal); } return encodedName; } /** * Use logging. * @param encodedRegionName The encoded regionname. * @return <code>-ROOT-</code> if passed <code>70236052</code> or * <code>.META.</code> if passed </code>1028785192</code> else returns * <code>encodedRegionName</code> */ public static String prettyPrint(final String encodedRegionName) { if (encodedRegionName.equals("70236052")) { return encodedRegionName + "/-ROOT-"; } else if (encodedRegionName.equals("1028785192")) { return encodedRegionName + "/.META."; } return encodedRegionName; } /** delimiter used between portions of a region name */ public static final int DELIMITER = ','; /** HRegionInfo for root region */ public static final HRegionInfo ROOT_REGIONINFO = new HRegionInfo(0L, Bytes.toBytes("-ROOT-")); /** HRegionInfo for first meta region */ public static final HRegionInfo FIRST_META_REGIONINFO = new HRegionInfo(1L, Bytes.toBytes(".META.")); private byte [] endKey = HConstants.EMPTY_BYTE_ARRAY; // This flag is in the parent of a split while the parent is still referenced // by daughter regions. We USED to set this flag when we disabled a table // but now table state is kept up in zookeeper as of 0.90.0 HBase. private boolean offLine = false; private long regionId = -1; private transient byte [] regionName = HConstants.EMPTY_BYTE_ARRAY; private String regionNameStr = ""; private boolean split = false; private byte [] startKey = HConstants.EMPTY_BYTE_ARRAY; private int hashCode = -1; //TODO: Move NO_HASH to HStoreFile which is really the only place it is used. public static final String NO_HASH = null; private volatile String encodedName = NO_HASH; private byte [] encodedNameAsBytes = null; // Current TableName private byte[] tableName = null; private String tableNameAsString = null; private void setHashCode() { int result = Arrays.hashCode(this.regionName); result ^= this.regionId; result ^= Arrays.hashCode(this.startKey); result ^= Arrays.hashCode(this.endKey); result ^= Boolean.valueOf(this.offLine).hashCode(); result ^= Arrays.hashCode(this.tableName); this.hashCode = result; } /** * Private constructor used constructing HRegionInfo for the catalog root and * first meta regions */ private HRegionInfo(long regionId, byte[] tableName) { super(); this.regionId = regionId; this.tableName = tableName.clone(); // Note: Root & First Meta regions names are still in old format this.regionName = createRegionName(tableName, null, regionId, false); this.regionNameStr = Bytes.toStringBinary(this.regionName); setHashCode(); } /** Default constructor - creates empty object */ public HRegionInfo() { super(); } /** * Used only for migration * @param other HRegionInfoForMigration */ public HRegionInfo(HRegionInfo090x other) { super(); this.endKey = other.getEndKey(); this.offLine = other.isOffline(); this.regionId = other.getRegionId(); this.regionName = other.getRegionName(); this.regionNameStr = Bytes.toStringBinary(this.regionName); this.split = other.isSplit(); this.startKey = other.getStartKey(); this.hashCode = other.hashCode(); this.encodedName = other.getEncodedName(); this.tableName = other.getTableDesc().getName(); } public HRegionInfo(final byte[] tableName) { this(tableName, null, null); } /** * Construct HRegionInfo with explicit parameters * * @param tableName the table name * @param startKey first key in region * @param endKey end of key range * @throws IllegalArgumentException */ public HRegionInfo(final byte[] tableName, final byte[] startKey, final byte[] endKey) throws IllegalArgumentException { this(tableName, startKey, endKey, false); } /** * Construct HRegionInfo with explicit parameters * * @param tableName the table descriptor * @param startKey first key in region * @param endKey end of key range * @param split true if this region has split and we have daughter regions * regions that may or may not hold references to this region. * @throws IllegalArgumentException */ public HRegionInfo(final byte[] tableName, final byte[] startKey, final byte[] endKey, final boolean split) throws IllegalArgumentException { this(tableName, startKey, endKey, split, System.currentTimeMillis()); } /** * Construct HRegionInfo with explicit parameters * * @param tableName the table descriptor * @param startKey first key in region * @param endKey end of key range * @param split true if this region has split and we have daughter regions * regions that may or may not hold references to this region. * @param regionid Region id to use. * @throws IllegalArgumentException */ public HRegionInfo(final byte[] tableName, final byte[] startKey, final byte[] endKey, final boolean split, final long regionid) throws IllegalArgumentException { super(); if (tableName == null) { throw new IllegalArgumentException("tableName cannot be null"); } this.tableName = tableName.clone(); this.offLine = false; this.regionId = regionid; this.regionName = createRegionName(this.tableName, startKey, regionId, true); this.regionNameStr = Bytes.toStringBinary(this.regionName); this.split = split; this.endKey = endKey == null? HConstants.EMPTY_END_ROW: endKey.clone(); this.startKey = startKey == null? HConstants.EMPTY_START_ROW: startKey.clone(); this.tableName = tableName.clone(); setHashCode(); } /** * Costruct a copy of another HRegionInfo * * @param other */ public HRegionInfo(HRegionInfo other) { super(); this.endKey = other.getEndKey(); this.offLine = other.isOffline(); this.regionId = other.getRegionId(); this.regionName = other.getRegionName(); this.regionNameStr = Bytes.toStringBinary(this.regionName); this.split = other.isSplit(); this.startKey = other.getStartKey(); this.hashCode = other.hashCode(); this.encodedName = other.getEncodedName(); this.tableName = other.tableName; } /** * Make a region name of passed parameters. * @param tableName * @param startKey Can be null * @param regionid Region id (Usually timestamp from when region was created). * @param newFormat should we create the region name in the new format * (such that it contains its encoded name?). * @return Region name made of passed tableName, startKey and id */ public static byte [] createRegionName(final byte [] tableName, final byte [] startKey, final long regionid, boolean newFormat) { return createRegionName(tableName, startKey, Long.toString(regionid), newFormat); } /** * Make a region name of passed parameters. * @param tableName * @param startKey Can be null * @param id Region id (Usually timestamp from when region was created). * @param newFormat should we create the region name in the new format * (such that it contains its encoded name?). * @return Region name made of passed tableName, startKey and id */ public static byte [] createRegionName(final byte [] tableName, final byte [] startKey, final String id, boolean newFormat) { return createRegionName(tableName, startKey, Bytes.toBytes(id), newFormat); } /** * Make a region name of passed parameters. * @param tableName * @param startKey Can be null * @param id Region id (Usually timestamp from when region was created). * @param newFormat should we create the region name in the new format * (such that it contains its encoded name?). * @return Region name made of passed tableName, startKey and id */ public static byte [] createRegionName(final byte [] tableName, final byte [] startKey, final byte [] id, boolean newFormat) { byte [] b = new byte [tableName.length + 2 + id.length + (startKey == null? 0: startKey.length) + (newFormat ? (MD5_HEX_LENGTH + 2) : 0)]; int offset = tableName.length; System.arraycopy(tableName, 0, b, 0, offset); b[offset++] = DELIMITER; if (startKey != null && startKey.length > 0) { System.arraycopy(startKey, 0, b, offset, startKey.length); offset += startKey.length; } b[offset++] = DELIMITER; System.arraycopy(id, 0, b, offset, id.length); offset += id.length; if (newFormat) { // // Encoded name should be built into the region name. // // Use the region name thus far (namely, <tablename>,<startKey>,<id>) // to compute a MD5 hash to be used as the encoded name, and append // it to the byte buffer. // String md5Hash = MD5Hash.getMD5AsHex(b, 0, offset); byte [] md5HashBytes = Bytes.toBytes(md5Hash); if (md5HashBytes.length != MD5_HEX_LENGTH) { LOG.error("MD5-hash length mismatch: Expected=" + MD5_HEX_LENGTH + "; Got=" + md5HashBytes.length); } // now append the bytes '.<encodedName>.' to the end b[offset++] = ENC_SEPARATOR; System.arraycopy(md5HashBytes, 0, b, offset, MD5_HEX_LENGTH); offset += MD5_HEX_LENGTH; b[offset++] = ENC_SEPARATOR; } return b; } /** * Gets the table name from the specified region name. * @param regionName * @return Table name. */ public static byte [] getTableName(byte [] regionName) { int offset = -1; for (int i = 0; i < regionName.length; i++) { if (regionName[i] == DELIMITER) { offset = i; break; } } byte [] tableName = new byte[offset]; System.arraycopy(regionName, 0, tableName, 0, offset); return tableName; } /** * Separate elements of a regionName. * @param regionName * @return Array of byte[] containing tableName, startKey and id * @throws IOException */ public static byte [][] parseRegionName(final byte [] regionName) throws IOException { int offset = -1; for (int i = 0; i < regionName.length; i++) { if (regionName[i] == DELIMITER) { offset = i; break; } } if(offset == -1) throw new IOException("Invalid regionName format"); byte [] tableName = new byte[offset]; System.arraycopy(regionName, 0, tableName, 0, offset); offset = -1; for (int i = regionName.length - 1; i > 0; i--) { if(regionName[i] == DELIMITER) { offset = i; break; } } if(offset == -1) throw new IOException("Invalid regionName format"); byte [] startKey = HConstants.EMPTY_BYTE_ARRAY; if(offset != tableName.length + 1) { startKey = new byte[offset - tableName.length - 1]; System.arraycopy(regionName, tableName.length + 1, startKey, 0, offset - tableName.length - 1); } byte [] id = new byte[regionName.length - offset - 1]; System.arraycopy(regionName, offset + 1, id, 0, regionName.length - offset - 1); byte [][] elements = new byte[3][]; elements[0] = tableName; elements[1] = startKey; elements[2] = id; return elements; } /** @return the regionId */ public long getRegionId(){ return regionId; } /** * @return the regionName as an array of bytes. * @see #getRegionNameAsString() */ public byte [] getRegionName(){ return regionName; } /** * @return Region name as a String for use in logging, etc. */ public String getRegionNameAsString() { if (hasEncodedName(this.regionName)) { // new format region names already have their encoded name. return this.regionNameStr; } // old format. regionNameStr doesn't have the region name. // // return this.regionNameStr + "." + this.getEncodedName(); } /** @return the encoded region name */ public synchronized String getEncodedName() { if (this.encodedName == NO_HASH) { this.encodedName = encodeRegionName(this.regionName); } return this.encodedName; } public synchronized byte [] getEncodedNameAsBytes() { if (this.encodedNameAsBytes == null) { this.encodedNameAsBytes = Bytes.toBytes(getEncodedName()); } return this.encodedNameAsBytes; } /** @return the startKey */ public byte [] getStartKey(){ return startKey; } /** @return the endKey */ public byte [] getEndKey(){ return endKey; } /** * Get current table name of the region * @return byte array of table name */ public byte[] getTableName() { return tableName; } /** * Get current table name as string * @return string representation of current table */ public String getTableNameAsString() { return Bytes.toString(tableName); } /** * Returns true if the given inclusive range of rows is fully contained * by this region. For example, if the region is foo,a,g and this is * passed ["b","c"] or ["a","c"] it will return true, but if this is passed * ["b","z"] it will return false. * @throws IllegalArgumentException if the range passed is invalid (ie end < start) */ public boolean containsRange(byte[] rangeStartKey, byte[] rangeEndKey) { if (Bytes.compareTo(rangeStartKey, rangeEndKey) > 0) { throw new IllegalArgumentException( "Invalid range: " + Bytes.toStringBinary(rangeStartKey) + " > " + Bytes.toStringBinary(rangeEndKey)); } boolean firstKeyInRange = Bytes.compareTo(rangeStartKey, startKey) >= 0; boolean lastKeyInRange = Bytes.compareTo(rangeEndKey, endKey) < 0 || Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY); return firstKeyInRange && lastKeyInRange; } /** * Return true if the given row falls in this region. */ public boolean containsRow(byte[] row) { return Bytes.compareTo(row, startKey) >= 0 && (Bytes.compareTo(row, endKey) < 0 || Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY)); } /** * @return the tableDesc * @deprecated Do not use; expensive call * use HRegionInfo.getTableNameAsString() in place of * HRegionInfo.getTableDesc().getNameAsString() */ @Deprecated public HTableDescriptor getTableDesc() { Configuration c = HBaseConfiguration.create(); FileSystem fs; try { fs = FileSystem.get(c); } catch (IOException e) { throw new RuntimeException(e); } FSTableDescriptors fstd = new FSTableDescriptors(fs, new Path(c.get(HConstants.HBASE_DIR))); try { return fstd.get(this.tableName); } catch (IOException e) { throw new RuntimeException(e); } } /** * @param newDesc new table descriptor to use * @deprecated Do not use; expensive call */ @Deprecated public void setTableDesc(HTableDescriptor newDesc) { Configuration c = HBaseConfiguration.create(); FileSystem fs; try { fs = FileSystem.get(c); } catch (IOException e) { throw new RuntimeException(e); } FSTableDescriptors fstd = new FSTableDescriptors(fs, new Path(c.get(HConstants.HBASE_DIR))); try { fstd.add(newDesc); } catch (IOException e) { throw new RuntimeException(e); } } /** @return true if this is the root region */ public boolean isRootRegion() { return Bytes.equals(tableName, HRegionInfo.ROOT_REGIONINFO.getTableName()); } /** @return true if this region is from a table that is a meta table, * either <code>.META.</code> or <code>-ROOT-</code> */ public boolean isMetaTable() { return Bytes.equals(tableName, HRegionInfo.FIRST_META_REGIONINFO.getTableName()); } /** @return true if this region is a meta region */ public boolean isMetaRegion() { return isMetaTable(); } /** * @return True if has been split and has daughters. */ public boolean isSplit() { return this.split; } /** * @param split set split status */ public void setSplit(boolean split) { this.split = split; } /** * @return True if this region is offline. */ public boolean isOffline() { return this.offLine; } /** * The parent of a region split is offline while split daughters hold * references to the parent. Offlined regions are closed. * @param offLine Set online/offline status. */ public void setOffline(boolean offLine) { this.offLine = offLine; } /** * @return True if this is a split parent region. */ public boolean isSplitParent() { if (!isSplit()) return false; if (!isOffline()) { LOG.warn("Region is split but NOT offline: " + getRegionNameAsString()); } return true; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "REGION => {" + HConstants.NAME + " => '" + this.regionNameStr + "', TableName => '" + Bytes.toStringBinary(this.tableName) + "', STARTKEY => '" + Bytes.toStringBinary(this.startKey) + "', ENDKEY => '" + Bytes.toStringBinary(this.endKey) + "', ENCODED => " + getEncodedName() + "," + (isOffline()? " OFFLINE => true,": "") + (isSplit()? " SPLIT => true,": "") + "}"; } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (!(o instanceof HRegionInfo)) { return false; } return this.compareTo((HRegionInfo)o) == 0; } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.hashCode; } /** @return the object version number */ @Override public byte getVersion() { return VERSION; } // // Writable // @Override public void write(DataOutput out) throws IOException { super.write(out); Bytes.writeByteArray(out, endKey); out.writeBoolean(offLine); out.writeLong(regionId); Bytes.writeByteArray(out, regionName); out.writeBoolean(split); Bytes.writeByteArray(out, startKey); Bytes.writeByteArray(out, tableName); out.writeInt(hashCode); } @Override public void readFields(DataInput in) throws IOException { super.readFields(in); this.endKey = Bytes.readByteArray(in); this.offLine = in.readBoolean(); this.regionId = in.readLong(); this.regionName = Bytes.readByteArray(in); this.regionNameStr = Bytes.toStringBinary(this.regionName); this.split = in.readBoolean(); this.startKey = Bytes.readByteArray(in); this.tableName = Bytes.readByteArray(in); this.hashCode = in.readInt(); } // // Comparable // public int compareTo(HRegionInfo o) { if (o == null) { return 1; } // Are regions of same table? int result = Bytes.compareTo(this.tableName, o.tableName); if (result != 0) { return result; } // Compare start keys. result = Bytes.compareTo(this.startKey, o.startKey); if (result != 0) { return result; } // Compare end keys. result = Bytes.compareTo(this.endKey, o.endKey); if (result != 0) { return result; } if (this.offLine == o.offLine) return 0; if (this.offLine == true) return -1; return 1; } /** * @return Comparator to use comparing {@link KeyValue}s. */ public KVComparator getComparator() { return isRootRegion()? KeyValue.ROOT_COMPARATOR: isMetaRegion()? KeyValue.META_COMPARATOR: KeyValue.COMPARATOR; } }
apache-2.0
Gridtec/lambda4j
lambda4j/src-gen/main/java/at/gridtec/lambda4j/function/tri/obj/ObjBiByteToFloatFunction.java
39959
/* * Copyright (c) 2016 Gridtec. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package at.gridtec.lambda4j.function.tri.obj; import at.gridtec.lambda4j.Lambda; import at.gridtec.lambda4j.consumer.FloatConsumer; import at.gridtec.lambda4j.consumer.tri.obj.ObjBiByteConsumer; import at.gridtec.lambda4j.function.BooleanFunction; import at.gridtec.lambda4j.function.ByteFunction; import at.gridtec.lambda4j.function.CharFunction; import at.gridtec.lambda4j.function.FloatFunction; import at.gridtec.lambda4j.function.ShortFunction; import at.gridtec.lambda4j.function.bi.conversion.BiByteToFloatFunction; import at.gridtec.lambda4j.function.bi.obj.ObjByteToFloatFunction; import at.gridtec.lambda4j.function.conversion.BooleanToByteFunction; import at.gridtec.lambda4j.function.conversion.ByteToFloatFunction; import at.gridtec.lambda4j.function.conversion.CharToByteFunction; import at.gridtec.lambda4j.function.conversion.DoubleToByteFunction; import at.gridtec.lambda4j.function.conversion.FloatToByteFunction; import at.gridtec.lambda4j.function.conversion.FloatToCharFunction; import at.gridtec.lambda4j.function.conversion.FloatToDoubleFunction; import at.gridtec.lambda4j.function.conversion.FloatToIntFunction; import at.gridtec.lambda4j.function.conversion.FloatToLongFunction; import at.gridtec.lambda4j.function.conversion.FloatToShortFunction; import at.gridtec.lambda4j.function.conversion.IntToByteFunction; import at.gridtec.lambda4j.function.conversion.LongToByteFunction; import at.gridtec.lambda4j.function.conversion.ShortToByteFunction; import at.gridtec.lambda4j.function.to.ToByteFunction; import at.gridtec.lambda4j.function.to.ToFloatFunction; import at.gridtec.lambda4j.function.tri.TriFunction; import at.gridtec.lambda4j.function.tri.conversion.TriBooleanToFloatFunction; import at.gridtec.lambda4j.function.tri.conversion.TriByteToFloatFunction; import at.gridtec.lambda4j.function.tri.conversion.TriCharToFloatFunction; import at.gridtec.lambda4j.function.tri.conversion.TriDoubleToFloatFunction; import at.gridtec.lambda4j.function.tri.conversion.TriIntToFloatFunction; import at.gridtec.lambda4j.function.tri.conversion.TriLongToFloatFunction; import at.gridtec.lambda4j.function.tri.conversion.TriShortToFloatFunction; import at.gridtec.lambda4j.function.tri.to.ToFloatTriFunction; import at.gridtec.lambda4j.operator.ternary.FloatTernaryOperator; import at.gridtec.lambda4j.operator.unary.ByteUnaryOperator; import at.gridtec.lambda4j.operator.unary.FloatUnaryOperator; import at.gridtec.lambda4j.predicate.FloatPredicate; import at.gridtec.lambda4j.predicate.tri.obj.ObjBiBytePredicate; import org.apache.commons.lang3.tuple.Triple; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.function.DoubleFunction; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.LongFunction; /** * Represents an operation that accepts one object-valued and two {@code byte}-valued input arguments and produces a * {@code float}-valued result. * This is a (reference, byte, byte) specialization of {@link TriFunction}. * <p> * This is a {@link FunctionalInterface} whose functional method is {@link #applyAsFloat(Object, byte, byte)}. * * @param <T> The type of the first argument to the function * @see TriFunction */ @SuppressWarnings("unused") @FunctionalInterface public interface ObjBiByteToFloatFunction<T> extends Lambda { /** * Constructs a {@link ObjBiByteToFloatFunction} based on a lambda expression or a method reference. Thereby the * given lambda expression or method reference is returned on an as-is basis to implicitly transform it to the * desired type. With this method, it is possible to ensure that correct type is used from lambda expression or * method reference. * * @param <T> The type of the first argument to the function * @param expression A lambda expression or (typically) a method reference, e.g. {@code this::method} * @return A {@code ObjBiByteToFloatFunction} from given lambda expression or method reference. * @implNote This implementation allows the given argument to be {@code null}, but only if {@code null} given, * {@code null} will be returned. * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax">Lambda * Expression</a> * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html">Method Reference</a> */ static <T> ObjBiByteToFloatFunction<T> of(@Nullable final ObjBiByteToFloatFunction<T> expression) { return expression; } /** * Calls the given {@link ObjBiByteToFloatFunction} with the given arguments and returns its result. * * @param <T> The type of the first argument to the function * @param function The function to be called * @param t The first argument to the function * @param value1 The second argument to the function * @param value2 The third argument to the function * @return The result from the given {@code ObjBiByteToFloatFunction}. * @throws NullPointerException If given argument is {@code null} */ static <T> float call(@Nonnull final ObjBiByteToFloatFunction<? super T> function, T t, byte value1, byte value2) { Objects.requireNonNull(function); return function.applyAsFloat(t, value1, value2); } /** * Creates a {@link ObjBiByteToFloatFunction} which uses the {@code first} parameter of this one as argument for the * given {@link ToFloatFunction}. * * @param <T> The type of the first argument to the function * @param function The function which accepts the {@code first} parameter of this one * @return Creates a {@code ObjBiByteToFloatFunction} which uses the {@code first} parameter of this one as argument * for the given {@code ToFloatFunction}. * @throws NullPointerException If given argument is {@code null} */ @Nonnull static <T> ObjBiByteToFloatFunction<T> onlyFirst(@Nonnull final ToFloatFunction<? super T> function) { Objects.requireNonNull(function); return (t, value1, value2) -> function.applyAsFloat(t); } /** * Creates a {@link ObjBiByteToFloatFunction} which uses the {@code second} parameter of this one as argument for * the given {@link ByteToFloatFunction}. * * @param <T> The type of the first argument to the function * @param function The function which accepts the {@code second} parameter of this one * @return Creates a {@code ObjBiByteToFloatFunction} which uses the {@code second} parameter of this one as * argument for the given {@code ByteToFloatFunction}. * @throws NullPointerException If given argument is {@code null} */ @Nonnull static <T> ObjBiByteToFloatFunction<T> onlySecond(@Nonnull final ByteToFloatFunction function) { Objects.requireNonNull(function); return (t, value1, value2) -> function.applyAsFloat(value1); } /** * Creates a {@link ObjBiByteToFloatFunction} which uses the {@code third} parameter of this one as argument for the * given {@link ByteToFloatFunction}. * * @param <T> The type of the first argument to the function * @param function The function which accepts the {@code third} parameter of this one * @return Creates a {@code ObjBiByteToFloatFunction} which uses the {@code third} parameter of this one as argument * for the given {@code ByteToFloatFunction}. * @throws NullPointerException If given argument is {@code null} */ @Nonnull static <T> ObjBiByteToFloatFunction<T> onlyThird(@Nonnull final ByteToFloatFunction function) { Objects.requireNonNull(function); return (t, value1, value2) -> function.applyAsFloat(value2); } /** * Creates a {@link ObjBiByteToFloatFunction} which always returns a given value. * * @param <T> The type of the first argument to the function * @param ret The return value for the constant * @return A {@code ObjBiByteToFloatFunction} which always returns a given value. */ @Nonnull static <T> ObjBiByteToFloatFunction<T> constant(float ret) { return (t, value1, value2) -> ret; } /** * Applies this function to the given arguments. * * @param t The first argument to the function * @param value1 The second argument to the function * @param value2 The third argument to the function * @return The return value from the function, which is its result. */ float applyAsFloat(T t, byte value1, byte value2); /** * Applies this function partially to some arguments of this one, producing a {@link BiByteToFloatFunction} as * result. * * @param t The first argument to this function used to partially apply this function * @return A {@code BiByteToFloatFunction} that represents this function partially applied the some arguments. */ @Nonnull default BiByteToFloatFunction papplyAsFloat(T t) { return (value1, value2) -> this.applyAsFloat(t, value1, value2); } /** * Applies this function partially to some arguments of this one, producing a {@link ByteToFloatFunction} as result. * * @param t The first argument to this function used to partially apply this function * @param value1 The second argument to this function used to partially apply this function * @return A {@code ByteToFloatFunction} that represents this function partially applied the some arguments. */ @Nonnull default ByteToFloatFunction papplyAsFloat(T t, byte value1) { return (value2) -> this.applyAsFloat(t, value1, value2); } /** * Applies this function partially to some arguments of this one, producing a {@link ObjByteToFloatFunction} as * result. * * @param value1 The second argument to this function used to partially apply this function * @return A {@code ObjByteToFloatFunction} that represents this function partially applied the some arguments. */ @Nonnull default ObjByteToFloatFunction<T> papplyAsFloat(byte value1) { return (t, value2) -> this.applyAsFloat(t, value1, value2); } /** * Applies this function partially to some arguments of this one, producing a {@link ToFloatFunction} as result. * * @param value1 The second argument to this function used to partially apply this function * @param value2 The third argument to this function used to partially apply this function * @return A {@code ToFloatFunction} that represents this function partially applied the some arguments. */ @Nonnull default ToFloatFunction<T> papplyAsFloat(byte value1, byte value2) { return (t) -> this.applyAsFloat(t, value1, value2); } /** * Returns the number of arguments for this function. * * @return The number of arguments for this function. * @implSpec The default implementation always returns {@code 3}. */ @Nonnegative default int arity() { return 3; } /** * Returns a composed {@link ToFloatTriFunction} that first applies the {@code before} functions to its input, and * then applies this function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * * @param <A> The type of the argument to the first given function, and of composed function * @param <B> The type of the argument to the second given function, and of composed function * @param <C> The type of the argument to the third given function, and of composed function * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code ToFloatTriFunction} that first applies the {@code before} functions to its input, and * then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is able to handle every type. */ @Nonnull default <A, B, C> ToFloatTriFunction<A, B, C> compose(@Nonnull final Function<? super A, ? extends T> before1, @Nonnull final ToByteFunction<? super B> before2, @Nonnull final ToByteFunction<? super C> before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (a, b, c) -> applyAsFloat(before1.apply(a), before2.applyAsByte(b), before3.applyAsByte(c)); } /** * Returns a composed {@link TriBooleanToFloatFunction} that first applies the {@code before} functions to its * input, and then applies this function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * execute an operation which accepts {@code boolean} input, before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriBooleanToFloatFunction} that first applies the {@code before} functions to its * input, and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * boolean}. */ @Nonnull default TriBooleanToFloatFunction composeFromBoolean(@Nonnull final BooleanFunction<? extends T> before1, @Nonnull final BooleanToByteFunction before2, @Nonnull final BooleanToByteFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsFloat(before1.apply(value1), before2.applyAsByte(value2), before3.applyAsByte(value3)); } /** * Returns a composed {@link TriByteToFloatFunction} that first applies the {@code before} functions to * its input, and then applies this function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * This method is just convenience, to provide the ability to execute an operation which accepts {@code byte} input, * before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second operator to apply before this function is applied * @param before3 The third operator to apply before this function is applied * @return A composed {@code TriByteToFloatFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * byte}. */ @Nonnull default TriByteToFloatFunction composeFromByte(@Nonnull final ByteFunction<? extends T> before1, @Nonnull final ByteUnaryOperator before2, @Nonnull final ByteUnaryOperator before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsFloat(before1.apply(value1), before2.applyAsByte(value2), before3.applyAsByte(value3)); } /** * Returns a composed {@link TriCharToFloatFunction} that first applies the {@code before} functions to * its input, and then applies this function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * This method is just convenience, to provide the ability to execute an operation which accepts {@code char} input, * before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriCharToFloatFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * char}. */ @Nonnull default TriCharToFloatFunction composeFromChar(@Nonnull final CharFunction<? extends T> before1, @Nonnull final CharToByteFunction before2, @Nonnull final CharToByteFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsFloat(before1.apply(value1), before2.applyAsByte(value2), before3.applyAsByte(value3)); } /** * Returns a composed {@link TriDoubleToFloatFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * execute an operation which accepts {@code double} input, before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriDoubleToFloatFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * double}. */ @Nonnull default TriDoubleToFloatFunction composeFromDouble(@Nonnull final DoubleFunction<? extends T> before1, @Nonnull final DoubleToByteFunction before2, @Nonnull final DoubleToByteFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsFloat(before1.apply(value1), before2.applyAsByte(value2), before3.applyAsByte(value3)); } /** * Returns a composed {@link FloatTernaryOperator} that first applies the {@code before} functions to its input, and * then applies this function to the result. If evaluation of either operation throws an exception, it is relayed to * the caller of the composed operation. This method is just convenience, to provide the ability to execute an * operation which accepts {@code float} input, before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code FloatTernaryOperator} that first applies the {@code before} functions to its input, and * then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * float}. */ @Nonnull default FloatTernaryOperator composeFromFloat(@Nonnull final FloatFunction<? extends T> before1, @Nonnull final FloatToByteFunction before2, @Nonnull final FloatToByteFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsFloat(before1.apply(value1), before2.applyAsByte(value2), before3.applyAsByte(value3)); } /** * Returns a composed {@link TriIntToFloatFunction} that first applies the {@code before} functions to * its input, and then applies this function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * This method is just convenience, to provide the ability to execute an operation which accepts {@code int} input, * before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriIntToFloatFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * int}. */ @Nonnull default TriIntToFloatFunction composeFromInt(@Nonnull final IntFunction<? extends T> before1, @Nonnull final IntToByteFunction before2, @Nonnull final IntToByteFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsFloat(before1.apply(value1), before2.applyAsByte(value2), before3.applyAsByte(value3)); } /** * Returns a composed {@link TriLongToFloatFunction} that first applies the {@code before} functions to * its input, and then applies this function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * This method is just convenience, to provide the ability to execute an operation which accepts {@code long} input, * before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriLongToFloatFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * long}. */ @Nonnull default TriLongToFloatFunction composeFromLong(@Nonnull final LongFunction<? extends T> before1, @Nonnull final LongToByteFunction before2, @Nonnull final LongToByteFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsFloat(before1.apply(value1), before2.applyAsByte(value2), before3.applyAsByte(value3)); } /** * Returns a composed {@link TriShortToFloatFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * execute an operation which accepts {@code short} input, before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriShortToFloatFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * short}. */ @Nonnull default TriShortToFloatFunction composeFromShort(@Nonnull final ShortFunction<? extends T> before1, @Nonnull final ShortToByteFunction before2, @Nonnull final ShortToByteFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsFloat(before1.apply(value1), before2.applyAsByte(value2), before3.applyAsByte(value3)); } /** * Returns a composed {@link ObjBiByteFunction} that first applies this function to its input, and then applies the * {@code after} function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * * @param <S> The type of return value from the {@code after} function, and of the composed function * @param after The function to apply after this function is applied * @return A composed {@code ObjBiByteFunction} that first applies this function to its input, and then applies the * {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is able to return every type. */ @Nonnull default <S> ObjBiByteFunction<T, S> andThen(@Nonnull final FloatFunction<? extends S> after) { Objects.requireNonNull(after); return (t, value1, value2) -> after.apply(applyAsFloat(t, value1, value2)); } /** * Returns a composed {@link ObjBiBytePredicate} that first applies this function to its input, and then applies the * {@code after} predicate to the result. If evaluation of either operation throws an exception, it is relayed to * the caller of the composed operation. This method is just convenience, to provide the ability to transform this * primitive function to an operation returning {@code boolean}. * * @param after The predicate to apply after this function is applied * @return A composed {@code ObjBiBytePredicate} that first applies this function to its input, and then applies the * {@code after} predicate to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * boolean}. */ @Nonnull default ObjBiBytePredicate<T> andThenToBoolean(@Nonnull final FloatPredicate after) { Objects.requireNonNull(after); return (t, value1, value2) -> after.test(applyAsFloat(t, value1, value2)); } /** * Returns a composed {@link ObjBiByteToByteFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code byte}. * * @param after The function to apply after this function is applied * @return A composed {@code ObjBiByteToByteFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * byte}. */ @Nonnull default ObjBiByteToByteFunction<T> andThenToByte(@Nonnull final FloatToByteFunction after) { Objects.requireNonNull(after); return (t, value1, value2) -> after.applyAsByte(applyAsFloat(t, value1, value2)); } /** * Returns a composed {@link ObjBiByteToCharFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code char}. * * @param after The function to apply after this function is applied * @return A composed {@code ObjBiByteToCharFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * char}. */ @Nonnull default ObjBiByteToCharFunction<T> andThenToChar(@Nonnull final FloatToCharFunction after) { Objects.requireNonNull(after); return (t, value1, value2) -> after.applyAsChar(applyAsFloat(t, value1, value2)); } /** * Returns a composed {@link ObjBiByteToDoubleFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code double}. * * @param after The function to apply after this function is applied * @return A composed {@code ObjBiByteToDoubleFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * double}. */ @Nonnull default ObjBiByteToDoubleFunction<T> andThenToDouble(@Nonnull final FloatToDoubleFunction after) { Objects.requireNonNull(after); return (t, value1, value2) -> after.applyAsDouble(applyAsFloat(t, value1, value2)); } /** * Returns a composed {@link ObjBiByteToFloatFunction} that first applies this function to its input, and then * applies the {@code after} operator to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code float}. * * @param after The operator to apply after this function is applied * @return A composed {@code ObjBiByteToFloatFunction} that first applies this function to its input, and then * applies the {@code after} operator to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * float}. */ @Nonnull default ObjBiByteToFloatFunction<T> andThenToFloat(@Nonnull final FloatUnaryOperator after) { Objects.requireNonNull(after); return (t, value1, value2) -> after.applyAsFloat(applyAsFloat(t, value1, value2)); } /** * Returns a composed {@link ObjBiByteToIntFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to * the caller of the composed operation. This method is just convenience, to provide the ability to transform this * primitive function to an operation returning {@code int}. * * @param after The function to apply after this function is applied * @return A composed {@code ObjBiByteToIntFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * int}. */ @Nonnull default ObjBiByteToIntFunction<T> andThenToInt(@Nonnull final FloatToIntFunction after) { Objects.requireNonNull(after); return (t, value1, value2) -> after.applyAsInt(applyAsFloat(t, value1, value2)); } /** * Returns a composed {@link ObjBiByteToLongFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code long}. * * @param after The function to apply after this function is applied * @return A composed {@code ObjBiByteToLongFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * long}. */ @Nonnull default ObjBiByteToLongFunction<T> andThenToLong(@Nonnull final FloatToLongFunction after) { Objects.requireNonNull(after); return (t, value1, value2) -> after.applyAsLong(applyAsFloat(t, value1, value2)); } /** * Returns a composed {@link ObjBiByteToShortFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code short}. * * @param after The function to apply after this function is applied * @return A composed {@code ObjBiByteToShortFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * short}. */ @Nonnull default ObjBiByteToShortFunction<T> andThenToShort(@Nonnull final FloatToShortFunction after) { Objects.requireNonNull(after); return (t, value1, value2) -> after.applyAsShort(applyAsFloat(t, value1, value2)); } /** * Returns a composed {@link ObjBiByteConsumer} that fist applies this function to its input, and then consumes the * result using the given {@link FloatConsumer}. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. * * @param consumer The operation which consumes the result from this operation * @return A composed {@code ObjBiByteConsumer} that first applies this function to its input, and then consumes the * result using the given {@code FloatConsumer}. * @throws NullPointerException If given argument is {@code null} */ @Nonnull default ObjBiByteConsumer<T> consume(@Nonnull final FloatConsumer consumer) { Objects.requireNonNull(consumer); return (t, value1, value2) -> consumer.accept(applyAsFloat(t, value1, value2)); } /** * Returns a memoized (caching) version of this {@link ObjBiByteToFloatFunction}. Whenever it is called, the mapping * between the input parameters and the return value is preserved in a cache, making subsequent calls returning the * memoized value instead of computing the return value again. * <p> * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values * forever. * * @return A memoized (caching) version of this {@code ObjBiByteToFloatFunction}. * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the * resulting memoized function, as the cache used internally does not permit {@code null} keys or values. * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it * thread-safe. */ @Nonnull default ObjBiByteToFloatFunction<T> memoized() { if (isMemoized()) { return this; } else { final Map<Triple<T, Byte, Byte>, Float> cache = new ConcurrentHashMap<>(); final Object lock = new Object(); return (ObjBiByteToFloatFunction<T> & Memoized) (t, value1, value2) -> { final float returnValue; synchronized (lock) { returnValue = cache.computeIfAbsent(Triple.of(t, value1, value2), key -> applyAsFloat(key.getLeft(), key.getMiddle(), key.getRight())); } return returnValue; }; } } /** * Returns a composed {@link TriFunction} which represents this {@link ObjBiByteToFloatFunction}. Thereby the * primitive input argument for this function is autoboxed. This method provides the possibility to use this {@code * ObjBiByteToFloatFunction} with methods provided by the {@code JDK}. * * @return A composed {@code TriFunction} which represents this {@code ObjBiByteToFloatFunction}. */ @Nonnull default TriFunction<T, Byte, Byte, Float> boxed() { return this::applyAsFloat; } }
apache-2.0
McLeodMoores/starling
projects/integration/src/main/java/com/opengamma/integration/tool/portfolio/PortfolioAggregationTool.java
6227
/** * Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.integration.tool.portfolio; import java.util.HashMap; import java.util.Map; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.component.tool.AbstractTool; import com.opengamma.core.security.SecuritySource; import com.opengamma.financial.aggregation.AggregationFunction; import com.opengamma.financial.aggregation.AssetClassAggregationFunction; import com.opengamma.financial.aggregation.CdsObligorNameAggregationFunction; import com.opengamma.financial.aggregation.CdsObligorTickerAggregationFunction; import com.opengamma.financial.aggregation.CdsRedCodeAggregationFunction; import com.opengamma.financial.aggregation.CdsSeniorityAggregationFunction; import com.opengamma.financial.aggregation.CurrencyAggregationFunction; import com.opengamma.financial.aggregation.DetailedAssetClassAggregationFunction; import com.opengamma.financial.aggregation.GICSAggregationFunction; import com.opengamma.financial.aggregation.PortfolioAggregator; import com.opengamma.financial.aggregation.PositionAttributeAggregationFunction; import com.opengamma.financial.aggregation.UnderlyingAggregationFunction; import com.opengamma.financial.tool.ToolContext; import com.opengamma.scripts.Scriptable; /** * Tool to aggregate portfolios. */ @Scriptable public class PortfolioAggregationTool extends AbstractTool<ToolContext> { /** Logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(PortfolioAggregationTool.class); private final Map<String, AggregationFunction<?>> _aggregationFunctions = new HashMap<>(); private static final String PORTFOLIO_OPT = "p"; private static final String AGGREGATION_OPT = "a"; private static final String SPLIT_OPT = "s"; // ------------------------------------------------------------------------- /** * Main method to run the tool. * * @param args * the standard tool arguments, not null */ public static void main(final String[] args) { // CSIGNORE new PortfolioAggregationTool().invokeAndTerminate(args); } // ------------------------------------------------------------------------- @Override protected void doRun() { populateAggregationFunctionMap(getToolContext().getSecuritySource()); PortfolioAggregator.aggregate(getCommandLine().getOptionValue(PORTFOLIO_OPT), getCommandLine().getOptionValues(AGGREGATION_OPT)[0], getToolContext().getPortfolioMaster(), getToolContext().getPositionMaster(), getToolContext().getPositionSource(), getToolContext().getSecuritySource(), createAggregationFunctions(getCommandLine().getOptionValues(AGGREGATION_OPT)), getCommandLine().hasOption(SPLIT_OPT)); } private void populateAggregationFunctionMap(final SecuritySource secSource) { _aggregationFunctions.put("AssetClass", new AssetClassAggregationFunction()); _aggregationFunctions.put("Currency", new CurrencyAggregationFunction()); _aggregationFunctions.put("DetailedAssetClass", new DetailedAssetClassAggregationFunction()); _aggregationFunctions.put("Underlying", new UnderlyingAggregationFunction(secSource, "BLOOMBERG_TICKER")); _aggregationFunctions.put("ReferenceEntityName", new CdsObligorNameAggregationFunction(getToolContext().getSecuritySource(), getToolContext().getLegalEntitySource())); _aggregationFunctions.put("ReferenceEntityTicker", new CdsObligorTickerAggregationFunction(getToolContext().getSecuritySource(), getToolContext().getLegalEntitySource())); _aggregationFunctions.put("Sector", new GICSAggregationFunction(getToolContext().getSecuritySource(), getToolContext().getLegalEntitySource(), GICSAggregationFunction.Level.SECTOR, false, false)); _aggregationFunctions.put("RedCode", new CdsRedCodeAggregationFunction(getToolContext().getSecuritySource())); _aggregationFunctions.put("Seniority", new CdsSeniorityAggregationFunction(getToolContext().getSecuritySource())); } private AggregationFunction<?>[] createAggregationFunctions(final String[] aggregatorNames) { if (aggregatorNames == null) { LOGGER.error("No aggregators specified"); System.exit(1); return null; // idiot compiler... } final AggregationFunction<?>[] results = new AggregationFunction<?>[aggregatorNames.length]; for (int i = 0; i < aggregatorNames.length; i++) { final AggregationFunction<?> aggregationFunction = _aggregationFunctions.get(aggregatorNames[i].trim()); if (aggregationFunction != null) { results[i] = aggregationFunction; } else { results[i] = new PositionAttributeAggregationFunction(aggregatorNames[i].trim()); } } return results; } @Override protected Options createOptions(final boolean contextProvided) { final Options options = super.createOptions(contextProvided); @SuppressWarnings("static-access") final Option baseViewOption = OptionBuilder.withLongOpt("portfolio") .hasArg() .isRequired() .withDescription("The portfolio name") .create(PORTFOLIO_OPT); options.addOption(baseViewOption); @SuppressWarnings("static-access") final Option aggregationTypesOption = OptionBuilder.withLongOpt("aggregation-types") .hasArgs() .isRequired() .withValueSeparator(',') .withDescription("The (comma, no space seperated) names of the aggregation" + " styles to use: e.g AssetClass,Currency,DetailedAssetClass") .create(AGGREGATION_OPT); options.addOption(aggregationTypesOption); @SuppressWarnings("static-access") final Option splitPortfoliosOption = OptionBuilder.withLongOpt("split") .withDescription( "Split into separate portfolios grouped by the top-level aggregator" + " instead of aggregating the existing portfoliio") .create(SPLIT_OPT); options.addOption(splitPortfoliosOption); return options; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-greengrassv2/src/main/java/com/amazonaws/services/greengrassv2/model/DescribeComponentResult.java
20799
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.greengrassv2.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/DescribeComponent" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeComponentResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the component * version. * </p> */ private String arn; /** * <p> * The name of the component. * </p> */ private String componentName; /** * <p> * The version of the component. * </p> */ private String componentVersion; /** * <p> * The time at which the component was created, expressed in ISO 8601 format. * </p> */ private java.util.Date creationTimestamp; /** * <p> * The publisher of the component version. * </p> */ private String publisher; /** * <p> * The description of the component version. * </p> */ private String description; /** * <p> * The status of the component version in IoT Greengrass V2. This status is different from the status of the * component on a core device. * </p> */ private CloudComponentStatus status; /** * <p> * The platforms that the component version supports. * </p> */ private java.util.List<ComponentPlatform> platforms; /** * <p> * A list of key-value pairs that contain metadata for the resource. For more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/tag-resources.html">Tag your resources</a> in the * <i>IoT Greengrass V2 Developer Guide</i>. * </p> */ private java.util.Map<String, String> tags; /** * <p> * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the component * version. * </p> * * @param arn * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the * component version. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the component * version. * </p> * * @return The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the * component version. */ public String getArn() { return this.arn; } /** * <p> * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the component * version. * </p> * * @param arn * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the * component version. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult withArn(String arn) { setArn(arn); return this; } /** * <p> * The name of the component. * </p> * * @param componentName * The name of the component. */ public void setComponentName(String componentName) { this.componentName = componentName; } /** * <p> * The name of the component. * </p> * * @return The name of the component. */ public String getComponentName() { return this.componentName; } /** * <p> * The name of the component. * </p> * * @param componentName * The name of the component. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult withComponentName(String componentName) { setComponentName(componentName); return this; } /** * <p> * The version of the component. * </p> * * @param componentVersion * The version of the component. */ public void setComponentVersion(String componentVersion) { this.componentVersion = componentVersion; } /** * <p> * The version of the component. * </p> * * @return The version of the component. */ public String getComponentVersion() { return this.componentVersion; } /** * <p> * The version of the component. * </p> * * @param componentVersion * The version of the component. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult withComponentVersion(String componentVersion) { setComponentVersion(componentVersion); return this; } /** * <p> * The time at which the component was created, expressed in ISO 8601 format. * </p> * * @param creationTimestamp * The time at which the component was created, expressed in ISO 8601 format. */ public void setCreationTimestamp(java.util.Date creationTimestamp) { this.creationTimestamp = creationTimestamp; } /** * <p> * The time at which the component was created, expressed in ISO 8601 format. * </p> * * @return The time at which the component was created, expressed in ISO 8601 format. */ public java.util.Date getCreationTimestamp() { return this.creationTimestamp; } /** * <p> * The time at which the component was created, expressed in ISO 8601 format. * </p> * * @param creationTimestamp * The time at which the component was created, expressed in ISO 8601 format. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult withCreationTimestamp(java.util.Date creationTimestamp) { setCreationTimestamp(creationTimestamp); return this; } /** * <p> * The publisher of the component version. * </p> * * @param publisher * The publisher of the component version. */ public void setPublisher(String publisher) { this.publisher = publisher; } /** * <p> * The publisher of the component version. * </p> * * @return The publisher of the component version. */ public String getPublisher() { return this.publisher; } /** * <p> * The publisher of the component version. * </p> * * @param publisher * The publisher of the component version. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult withPublisher(String publisher) { setPublisher(publisher); return this; } /** * <p> * The description of the component version. * </p> * * @param description * The description of the component version. */ public void setDescription(String description) { this.description = description; } /** * <p> * The description of the component version. * </p> * * @return The description of the component version. */ public String getDescription() { return this.description; } /** * <p> * The description of the component version. * </p> * * @param description * The description of the component version. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult withDescription(String description) { setDescription(description); return this; } /** * <p> * The status of the component version in IoT Greengrass V2. This status is different from the status of the * component on a core device. * </p> * * @param status * The status of the component version in IoT Greengrass V2. This status is different from the status of the * component on a core device. */ public void setStatus(CloudComponentStatus status) { this.status = status; } /** * <p> * The status of the component version in IoT Greengrass V2. This status is different from the status of the * component on a core device. * </p> * * @return The status of the component version in IoT Greengrass V2. This status is different from the status of the * component on a core device. */ public CloudComponentStatus getStatus() { return this.status; } /** * <p> * The status of the component version in IoT Greengrass V2. This status is different from the status of the * component on a core device. * </p> * * @param status * The status of the component version in IoT Greengrass V2. This status is different from the status of the * component on a core device. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult withStatus(CloudComponentStatus status) { setStatus(status); return this; } /** * <p> * The platforms that the component version supports. * </p> * * @return The platforms that the component version supports. */ public java.util.List<ComponentPlatform> getPlatforms() { return platforms; } /** * <p> * The platforms that the component version supports. * </p> * * @param platforms * The platforms that the component version supports. */ public void setPlatforms(java.util.Collection<ComponentPlatform> platforms) { if (platforms == null) { this.platforms = null; return; } this.platforms = new java.util.ArrayList<ComponentPlatform>(platforms); } /** * <p> * The platforms that the component version supports. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setPlatforms(java.util.Collection)} or {@link #withPlatforms(java.util.Collection)} if you want to * override the existing values. * </p> * * @param platforms * The platforms that the component version supports. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult withPlatforms(ComponentPlatform... platforms) { if (this.platforms == null) { setPlatforms(new java.util.ArrayList<ComponentPlatform>(platforms.length)); } for (ComponentPlatform ele : platforms) { this.platforms.add(ele); } return this; } /** * <p> * The platforms that the component version supports. * </p> * * @param platforms * The platforms that the component version supports. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult withPlatforms(java.util.Collection<ComponentPlatform> platforms) { setPlatforms(platforms); return this; } /** * <p> * A list of key-value pairs that contain metadata for the resource. For more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/tag-resources.html">Tag your resources</a> in the * <i>IoT Greengrass V2 Developer Guide</i>. * </p> * * @return A list of key-value pairs that contain metadata for the resource. For more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/tag-resources.html">Tag your resources</a> * in the <i>IoT Greengrass V2 Developer Guide</i>. */ public java.util.Map<String, String> getTags() { return tags; } /** * <p> * A list of key-value pairs that contain metadata for the resource. For more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/tag-resources.html">Tag your resources</a> in the * <i>IoT Greengrass V2 Developer Guide</i>. * </p> * * @param tags * A list of key-value pairs that contain metadata for the resource. For more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/tag-resources.html">Tag your resources</a> * in the <i>IoT Greengrass V2 Developer Guide</i>. */ public void setTags(java.util.Map<String, String> tags) { this.tags = tags; } /** * <p> * A list of key-value pairs that contain metadata for the resource. For more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/tag-resources.html">Tag your resources</a> in the * <i>IoT Greengrass V2 Developer Guide</i>. * </p> * * @param tags * A list of key-value pairs that contain metadata for the resource. For more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/tag-resources.html">Tag your resources</a> * in the <i>IoT Greengrass V2 Developer Guide</i>. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; } /** * Add a single Tags entry * * @see DescribeComponentResult#withTags * @returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult addTagsEntry(String key, String value) { if (null == this.tags) { this.tags = new java.util.HashMap<String, String>(); } if (this.tags.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.tags.put(key, value); return this; } /** * Removes all the entries added into Tags. * * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeComponentResult clearTagsEntries() { this.tags = null; return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getArn() != null) sb.append("Arn: ").append(getArn()).append(","); if (getComponentName() != null) sb.append("ComponentName: ").append(getComponentName()).append(","); if (getComponentVersion() != null) sb.append("ComponentVersion: ").append(getComponentVersion()).append(","); if (getCreationTimestamp() != null) sb.append("CreationTimestamp: ").append(getCreationTimestamp()).append(","); if (getPublisher() != null) sb.append("Publisher: ").append(getPublisher()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getStatus() != null) sb.append("Status: ").append(getStatus()).append(","); if (getPlatforms() != null) sb.append("Platforms: ").append(getPlatforms()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeComponentResult == false) return false; DescribeComponentResult other = (DescribeComponentResult) obj; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; if (other.getComponentName() == null ^ this.getComponentName() == null) return false; if (other.getComponentName() != null && other.getComponentName().equals(this.getComponentName()) == false) return false; if (other.getComponentVersion() == null ^ this.getComponentVersion() == null) return false; if (other.getComponentVersion() != null && other.getComponentVersion().equals(this.getComponentVersion()) == false) return false; if (other.getCreationTimestamp() == null ^ this.getCreationTimestamp() == null) return false; if (other.getCreationTimestamp() != null && other.getCreationTimestamp().equals(this.getCreationTimestamp()) == false) return false; if (other.getPublisher() == null ^ this.getPublisher() == null) return false; if (other.getPublisher() != null && other.getPublisher().equals(this.getPublisher()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; if (other.getPlatforms() == null ^ this.getPlatforms() == null) return false; if (other.getPlatforms() != null && other.getPlatforms().equals(this.getPlatforms()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); hashCode = prime * hashCode + ((getComponentName() == null) ? 0 : getComponentName().hashCode()); hashCode = prime * hashCode + ((getComponentVersion() == null) ? 0 : getComponentVersion().hashCode()); hashCode = prime * hashCode + ((getCreationTimestamp() == null) ? 0 : getCreationTimestamp().hashCode()); hashCode = prime * hashCode + ((getPublisher() == null) ? 0 : getPublisher().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); hashCode = prime * hashCode + ((getPlatforms() == null) ? 0 : getPlatforms().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public DescribeComponentResult clone() { try { return (DescribeComponentResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
spinnaker/kayenta
kayenta-azure/src/main/java/com/netflix/kayenta/azure/config/AzureConfiguration.java
4315
/* * Copyright 2019 Microsoft Corporation. * * 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.netflix.kayenta.azure.config; import com.netflix.kayenta.azure.security.AzureCredentials; import com.netflix.kayenta.azure.security.AzureNamedAccountCredentials; import com.netflix.kayenta.security.AccountCredentials; import com.netflix.kayenta.security.AccountCredentialsRepository; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; @Configuration @EnableConfigurationProperties @ConditionalOnProperty("kayenta.azure.enabled") @ComponentScan({"com.netflix.kayenta.azure"}) @Slf4j public class AzureConfiguration { @Bean @ConfigurationProperties("kayenta.azure") AzureConfigurationProperties azureConfigurationProperties() { return new AzureConfigurationProperties(); } @Bean boolean registerAzureCredentials( AzureConfigurationProperties azureConfigurationProperties, AccountCredentialsRepository accountCredentialsRepository) { List<AzureManagedAccount> azureAccounts = azureConfigurationProperties.getAccounts(); for (AzureManagedAccount azureManagedAccount : azureAccounts) { String name = azureManagedAccount.getName(); String storageAccountName = azureManagedAccount.getStorageAccountName(); List<AccountCredentials.Type> supportedTypes = azureManagedAccount.getSupportedTypes(); log.info("Registering Azure account {} with supported types {}.", name, supportedTypes); try { String accountAccessKey = azureManagedAccount.getAccountAccessKey(); String endpointSuffix = azureManagedAccount.getEndpointSuffix(); AzureCredentials azureCredentials = new AzureCredentials(storageAccountName, accountAccessKey, endpointSuffix); AzureNamedAccountCredentials.AzureNamedAccountCredentialsBuilder azureNamedAccountCredentialsBuilder = AzureNamedAccountCredentials.builder().name(name).credentials(azureCredentials); if (!CollectionUtils.isEmpty(supportedTypes)) { if (supportedTypes.contains(AccountCredentials.Type.OBJECT_STORE)) { String container = azureManagedAccount.getContainer(); String rootFolder = azureManagedAccount.getRootFolder(); if (StringUtils.isEmpty(container)) { throw new IllegalArgumentException( "Azure/Blobs account " + name + " is required to specify a container."); } if (StringUtils.isEmpty(rootFolder)) { throw new IllegalArgumentException( "Azure/Blobs account " + name + " is required to specify a rootFolder."); } azureNamedAccountCredentialsBuilder.rootFolder(rootFolder); azureNamedAccountCredentialsBuilder.azureContainer( azureCredentials.getAzureContainer(container)); } azureNamedAccountCredentialsBuilder.supportedTypes(supportedTypes); } AzureNamedAccountCredentials azureNamedAccountCredentials = azureNamedAccountCredentialsBuilder.build(); accountCredentialsRepository.save(name, azureNamedAccountCredentials); } catch (Throwable t) { log.error("Could not load Azure account " + name + ".", t); } } return true; } }
apache-2.0
laotse-ltd/semantic-ui
src/main/java/org/laotse/coding/easyui/service/UserServiceImpl.java
3183
/******************************************************************************* * * Copyright (c) 2001-2017 Primeton Technologies, Ltd. * All rights reserved. * * Created on Apr 5, 2017 10:42:49 PM *******************************************************************************/ package org.laotse.coding.easyui.service; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang.StringUtils; import org.laotse.coding.easyui.model.User; import org.laotse.coding.easyui.util.UuidUtils; import org.springframework.stereotype.Service; /** * UserServiceImpl. <br> * * @author ZhongWen Li (mailto: lizw@primeton.com) */ @Service public class UserServiceImpl implements UserService { private Map<String, User> users = new ConcurrentHashMap<>(); { for (int i = 0; i < 10; i++) { User user = new User(); user.setDept(i % 2 == 0 ? "Dev" : "Test"); user.setGender(i % 2 == 0 ? "F" : "M"); user.setEmail("sh" + (10000 + i) + "@laotse.com"); user.setName(UuidUtils.generateNewId()); user.setPassword("000000"); create(user); } } /* (non-Javadoc) * @see org.laotse.coding.easyui.service.UserService#create(org.apache.catalina.User) */ @Override public User create(User user) { if (null == user || StringUtils.isBlank(user.getEmail())) { return null; } User old = null; if (null != (old = get(user.getEmail()))) { return old; } String id = UuidUtils.generateNewId(); user.setId(id); users.put(id, user); return user; } /* (non-Javadoc) * @see org.laotse.coding.easyui.service.UserService#update(org.apache.catalina.User) */ @Override public User update(User user) { if (null == user) { return null; } User old = null; if (StringUtils.isNotBlank(user.getId()) && null != (old = users.get(user.getId()))) { users.put(user.getId(), user); return user; } if (StringUtils.isNotBlank(user.getEmail()) && null != (old = get(user.getEmail()))) { String id = StringUtils.isBlank(old.getId()) ? UuidUtils.generateNewId() : old.getId(); users.put(id, user); return user; } return null; } /* (non-Javadoc) * @see org.laotse.coding.easyui.service.UserService#get(java.lang.String) */ @Override public User get(String id) { if (StringUtils.isBlank(id)) { return null; } if (users.containsKey(id)) { return users.get(id); } for (User user : users.values()) { if (StringUtils.equals(id, user.getEmail())) { return user; } } return null; } /* (non-Javadoc) * @see org.laotse.coding.easyui.service.UserService#remove(java.lang.String) */ @Override public User remove(String id) { if (StringUtils.isBlank(id)) { return null; } if (users.containsKey(id)) { return users.remove(id); } for (User user : users.values()) { if (StringUtils.equals(id, user.getEmail())) { users.remove(user); return user; } } return null; } /* (non-Javadoc) * @see org.laotse.coding.easyui.service.UserService#query() */ @Override public List<User> query() { return Arrays.asList(users.values().toArray(new User[users.size()])); } }
apache-2.0
OpenSourceConsulting/athena-chameleon
src/main/java/com/athena/chameleon/engine/entity/xml/application/jeus/v6_0/EngineContainerType.java
21416
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.09.17 at 07:02:27 오후 KST // package com.athena.chameleon.engine.entity.xml.application.jeus.v6_0; 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.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for engine-containerType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="engine-containerType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}token"/> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="base-port" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="command-option" type="{http://www.w3.org/2001/XMLSchema}token" minOccurs="0"/> * &lt;element name="jvm-config" type="{http://www.tmaxsoft.com/xml/ns/jeus}jvmConfigType" minOccurs="0"/> * &lt;element name="user-class-path" type="{http://www.w3.org/2001/XMLSchema}token" minOccurs="0"/> * &lt;element name="engine-command" type="{http://www.tmaxsoft.com/xml/ns/jeus}engine-commandType" maxOccurs="unbounded"/> * &lt;element name="enable-interop" type="{http://www.tmaxsoft.com/xml/ns/jeus}enable-interopType" minOccurs="0"/> * &lt;element name="start-on-boot" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="sequential-start" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="auto-restart" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="tm-config" type="{http://www.tmaxsoft.com/xml/ns/jeus}tm-configType" minOccurs="0"/> * &lt;element name="scheduler" type="{http://www.tmaxsoft.com/xml/ns/jeus}schedulerType" minOccurs="0"/> * &lt;element name="user-logging" type="{http://www.tmaxsoft.com/xml/ns/jeus}system-loggingType" minOccurs="0"/> * &lt;element name="system-logging" type="{http://www.tmaxsoft.com/xml/ns/jeus}system-loggingType" maxOccurs="unbounded" minOccurs="0"/> * &lt;group ref="{http://www.tmaxsoft.com/xml/ns/jeus}log-stdout-to-raw-format-group"/> * &lt;element name="invocation-manager-action" type="{http://www.tmaxsoft.com/xml/ns/jeus}action-on-resource-leakType" minOccurs="0"/> * &lt;element name="jmx-manager" type="{http://www.tmaxsoft.com/xml/ns/jeus}jmx-managerType" minOccurs="0"/> * &lt;element name="use-MEJB" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="lifecycle-invocation" type="{http://www.tmaxsoft.com/xml/ns/jeus}lifecycle-invocationType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="application-path" type="{http://www.w3.org/2001/XMLSchema}token" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="res-ref" type="{http://www.tmaxsoft.com/xml/ns/jeus}res-refType" minOccurs="0"/> * &lt;element name="external-resource" type="{http://www.tmaxsoft.com/xml/ns/jeus}external-resourceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "engine-containerType", propOrder = { "name", "id", "basePort", "commandOption", "jvmConfig", "userClassPath", "engineCommand", "enableInterop", "startOnBoot", "sequentialStart", "autoRestart", "tmConfig", "scheduler", "userLogging", "systemLogging", "logStdoutToRawFormat", "invocationManagerAction", "jmxManager", "useMEJB", "lifecycleInvocation", "applicationPath", "resRef", "externalResource" }) public class EngineContainerType { @XmlElement(namespace = "http://www.tmaxsoft.com/xml/ns/jeus", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String name; @XmlElement(namespace = "http://www.tmaxsoft.com/xml/ns/jeus") protected Integer id; @XmlElement(name = "base-port", namespace = "http://www.tmaxsoft.com/xml/ns/jeus") protected Integer basePort; @XmlElement(name = "command-option", namespace = "http://www.tmaxsoft.com/xml/ns/jeus") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String commandOption; @XmlElement(name = "jvm-config", namespace = "http://www.tmaxsoft.com/xml/ns/jeus") protected JvmConfigType jvmConfig; @XmlElement(name = "user-class-path", namespace = "http://www.tmaxsoft.com/xml/ns/jeus") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String userClassPath; @XmlElement(name = "engine-command", namespace = "http://www.tmaxsoft.com/xml/ns/jeus", required = true) protected List<EngineCommandType> engineCommand; @XmlElement(name = "enable-interop", namespace = "http://www.tmaxsoft.com/xml/ns/jeus") protected EnableInteropType enableInterop; @XmlElement(name = "start-on-boot", namespace = "http://www.tmaxsoft.com/xml/ns/jeus", defaultValue = "true") protected Boolean startOnBoot; @XmlElement(name = "sequential-start", namespace = "http://www.tmaxsoft.com/xml/ns/jeus", defaultValue = "true") protected Boolean sequentialStart; @XmlElement(name = "auto-restart", namespace = "http://www.tmaxsoft.com/xml/ns/jeus") protected Boolean autoRestart; @XmlElement(name = "tm-config", namespace = "http://www.tmaxsoft.com/xml/ns/jeus") protected TmConfigType tmConfig; @XmlElement(namespace = "http://www.tmaxsoft.com/xml/ns/jeus") protected SchedulerType scheduler; @XmlElement(name = "user-logging", namespace = "http://www.tmaxsoft.com/xml/ns/jeus") protected SystemLoggingType userLogging; @XmlElement(name = "system-logging", namespace = "http://www.tmaxsoft.com/xml/ns/jeus", required = true) protected List<SystemLoggingType> systemLogging; @XmlElement(name = "log-stdout-to-raw-format", namespace = "http://www.tmaxsoft.com/xml/ns/jeus") protected Boolean logStdoutToRawFormat; @XmlElement(name = "invocation-manager-action", namespace = "http://www.tmaxsoft.com/xml/ns/jeus", defaultValue = "Warning") protected ActionOnResourceLeakType invocationManagerAction; @XmlElement(name = "jmx-manager", namespace = "http://www.tmaxsoft.com/xml/ns/jeus") protected JmxManagerType jmxManager; @XmlElement(name = "use-MEJB", namespace = "http://www.tmaxsoft.com/xml/ns/jeus", defaultValue = "false") protected Boolean useMEJB; @XmlElement(name = "lifecycle-invocation", namespace = "http://www.tmaxsoft.com/xml/ns/jeus", required = true) protected List<LifecycleInvocationType> lifecycleInvocation; @XmlElementRef(name = "application-path", namespace = "http://www.tmaxsoft.com/xml/ns/jeus", type = JAXBElement.class) protected List<JAXBElement<String>> applicationPath; @XmlElement(name = "res-ref", namespace = "http://www.tmaxsoft.com/xml/ns/jeus") protected ResRefType resRef; @XmlElement(name = "external-resource", namespace = "http://www.tmaxsoft.com/xml/ns/jeus", required = true) protected List<ExternalResourceType> externalResource; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link Integer } * */ public Integer getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Integer } * */ public void setId(Integer value) { this.id = value; } /** * Gets the value of the basePort property. * * @return * possible object is * {@link Integer } * */ public Integer getBasePort() { return basePort; } /** * Sets the value of the basePort property. * * @param value * allowed object is * {@link Integer } * */ public void setBasePort(Integer value) { this.basePort = value; } /** * Gets the value of the commandOption property. * * @return * possible object is * {@link String } * */ public String getCommandOption() { return commandOption; } /** * Sets the value of the commandOption property. * * @param value * allowed object is * {@link String } * */ public void setCommandOption(String value) { this.commandOption = value; } /** * Gets the value of the jvmConfig property. * * @return * possible object is * {@link JvmConfigType } * */ public JvmConfigType getJvmConfig() { return jvmConfig; } /** * Sets the value of the jvmConfig property. * * @param value * allowed object is * {@link JvmConfigType } * */ public void setJvmConfig(JvmConfigType value) { this.jvmConfig = value; } /** * Gets the value of the userClassPath property. * * @return * possible object is * {@link String } * */ public String getUserClassPath() { return userClassPath; } /** * Sets the value of the userClassPath property. * * @param value * allowed object is * {@link String } * */ public void setUserClassPath(String value) { this.userClassPath = value; } /** * Gets the value of the engineCommand 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 engineCommand property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEngineCommand().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EngineCommandType } * * */ public List<EngineCommandType> getEngineCommand() { if (engineCommand == null) { engineCommand = new ArrayList<EngineCommandType>(); } return this.engineCommand; } /** * Gets the value of the enableInterop property. * * @return * possible object is * {@link EnableInteropType } * */ public EnableInteropType getEnableInterop() { return enableInterop; } /** * Sets the value of the enableInterop property. * * @param value * allowed object is * {@link EnableInteropType } * */ public void setEnableInterop(EnableInteropType value) { this.enableInterop = value; } /** * Gets the value of the startOnBoot property. * * @return * possible object is * {@link Boolean } * */ public Boolean isStartOnBoot() { return startOnBoot; } /** * Sets the value of the startOnBoot property. * * @param value * allowed object is * {@link Boolean } * */ public void setStartOnBoot(Boolean value) { this.startOnBoot = value; } /** * Gets the value of the sequentialStart property. * * @return * possible object is * {@link Boolean } * */ public Boolean isSequentialStart() { return sequentialStart; } /** * Sets the value of the sequentialStart property. * * @param value * allowed object is * {@link Boolean } * */ public void setSequentialStart(Boolean value) { this.sequentialStart = value; } /** * Gets the value of the autoRestart property. * * @return * possible object is * {@link Boolean } * */ public Boolean isAutoRestart() { return autoRestart; } /** * Sets the value of the autoRestart property. * * @param value * allowed object is * {@link Boolean } * */ public void setAutoRestart(Boolean value) { this.autoRestart = value; } /** * Gets the value of the tmConfig property. * * @return * possible object is * {@link TmConfigType } * */ public TmConfigType getTmConfig() { return tmConfig; } /** * Sets the value of the tmConfig property. * * @param value * allowed object is * {@link TmConfigType } * */ public void setTmConfig(TmConfigType value) { this.tmConfig = value; } /** * Gets the value of the scheduler property. * * @return * possible object is * {@link SchedulerType } * */ public SchedulerType getScheduler() { return scheduler; } /** * Sets the value of the scheduler property. * * @param value * allowed object is * {@link SchedulerType } * */ public void setScheduler(SchedulerType value) { this.scheduler = value; } /** * Gets the value of the userLogging property. * * @return * possible object is * {@link SystemLoggingType } * */ public SystemLoggingType getUserLogging() { return userLogging; } /** * Sets the value of the userLogging property. * * @param value * allowed object is * {@link SystemLoggingType } * */ public void setUserLogging(SystemLoggingType value) { this.userLogging = value; } /** * Gets the value of the systemLogging 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 systemLogging property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSystemLogging().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SystemLoggingType } * * */ public List<SystemLoggingType> getSystemLogging() { if (systemLogging == null) { systemLogging = new ArrayList<SystemLoggingType>(); } return this.systemLogging; } /** * Gets the value of the logStdoutToRawFormat property. * * @return * possible object is * {@link Boolean } * */ public Boolean isLogStdoutToRawFormat() { return logStdoutToRawFormat; } /** * Sets the value of the logStdoutToRawFormat property. * * @param value * allowed object is * {@link Boolean } * */ public void setLogStdoutToRawFormat(Boolean value) { this.logStdoutToRawFormat = value; } /** * Gets the value of the invocationManagerAction property. * * @return * possible object is * {@link ActionOnResourceLeakType } * */ public ActionOnResourceLeakType getInvocationManagerAction() { return invocationManagerAction; } /** * Sets the value of the invocationManagerAction property. * * @param value * allowed object is * {@link ActionOnResourceLeakType } * */ public void setInvocationManagerAction(ActionOnResourceLeakType value) { this.invocationManagerAction = value; } /** * Gets the value of the jmxManager property. * * @return * possible object is * {@link JmxManagerType } * */ public JmxManagerType getJmxManager() { return jmxManager; } /** * Sets the value of the jmxManager property. * * @param value * allowed object is * {@link JmxManagerType } * */ public void setJmxManager(JmxManagerType value) { this.jmxManager = value; } /** * Gets the value of the useMEJB property. * * @return * possible object is * {@link Boolean } * */ public Boolean isUseMEJB() { return useMEJB; } /** * Sets the value of the useMEJB property. * * @param value * allowed object is * {@link Boolean } * */ public void setUseMEJB(Boolean value) { this.useMEJB = value; } /** * Gets the value of the lifecycleInvocation 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 lifecycleInvocation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLifecycleInvocation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link LifecycleInvocationType } * * */ public List<LifecycleInvocationType> getLifecycleInvocation() { if (lifecycleInvocation == null) { lifecycleInvocation = new ArrayList<LifecycleInvocationType>(); } return this.lifecycleInvocation; } /** * Gets the value of the applicationPath 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 applicationPath property. * * <p> * For example, to add a new item, do as follows: * <pre> * getApplicationPath().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link JAXBElement }{@code <}{@link String }{@code >} * * */ public List<JAXBElement<String>> getApplicationPath() { if (applicationPath == null) { applicationPath = new ArrayList<JAXBElement<String>>(); } return this.applicationPath; } /** * Gets the value of the resRef property. * * @return * possible object is * {@link ResRefType } * */ public ResRefType getResRef() { return resRef; } /** * Sets the value of the resRef property. * * @param value * allowed object is * {@link ResRefType } * */ public void setResRef(ResRefType value) { this.resRef = value; } /** * Gets the value of the externalResource 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 externalResource property. * * <p> * For example, to add a new item, do as follows: * <pre> * getExternalResource().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ExternalResourceType } * * */ public List<ExternalResourceType> getExternalResource() { if (externalResource == null) { externalResource = new ArrayList<ExternalResourceType>(); } return this.externalResource; } }
apache-2.0
Union-Investment/Crud2Go
eai-portal-domain-crudportlet/src/test/java/de/unioninvestment/eai/portal/portlet/crud/domain/test/commons/TestUser.java
1320
/* * 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 de.unioninvestment.eai.portal.portlet.crud.domain.test.commons; import java.util.Set; import de.unioninvestment.eai.portal.portlet.crud.domain.model.Role; import de.unioninvestment.eai.portal.portlet.crud.domain.model.user.CurrentUser; public class TestUser extends CurrentUser { private String name; public TestUser(String name) { super(null); this.name = name; } public TestUser(Set<Role> portalRoles) { super(portalRoles); } @Override public String getName() { return name; } }
apache-2.0
jpbirdy/WordsDetection
weibo/src/main/java/weibo4j/examples/comment/GetCommentMentions.java
578
package weibo4j.examples.comment; import weibo4j.Comments; import weibo4j.examples.oauth2.Log; import weibo4j.model.CommentWapper; import weibo4j.model.WeiboException; public class GetCommentMentions { public static void main(String[] args) { String access_token = args[0]; Comments cm = new Comments(access_token); try { CommentWapper comment = cm.getCommentMentions(); Log.logInfo(comment.toString()); } catch (WeiboException e) { e.printStackTrace(); } } }
apache-2.0
sbower/kuali-rice-1
client-contrib/src/main/java/org/kuali/rice/core/util/jaxb/RiceXmlListAdditionListener.java
1631
/* * Copyright 2011 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.core.util.jaxb; import java.io.Serializable; /** * Helper interface for use with the RiceXmlStreamingList class. * * <p>If "streaming" of child elements is desired during JAXB unmarshalling, then the parent element * assigns an instance of RiceXmlStreamingList to the appropriate list field/property, and gives the * list an implementation of this interface for the list to invoke whenever it receives a * newly-unmarshalled child element. This allows the implementation to process the new element and then * discard it. * * @author Kuali Rice Team (rice.collab@kuali.org) */ public interface RiceXmlListAdditionListener<T> extends Serializable { /** * This method is invoked whenever the associated RiceXmlStreamingList instance receives * a newly-unmarshalled child element. * * @param item The unmarshalled element (or adapter-generated object) to be processed. */ public void newItemAdded(T item); }
apache-2.0
oshai/simba
java/src_no_junit/sim/configuration/BestFitConfiguration.java
288
package sim.configuration; import sim.scheduling.graders.Grader; import sim.scheduling.matchers.GradeMatcherProvider; public class BestFitConfiguration extends ProductionSimbaConfiguration { @Override protected Grader grader() { return GradeMatcherProvider.createGraderBf2(); } }
apache-2.0
aryaman02/hhs_algorithms
hhsalgo/src/main/java/net/aryaman/algo/hackerrank/Between.java
2191
package net.aryaman.algo.hackerrank; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Between { public static void main(String[] args) { Between bt = new Between(); Scanner in = new Scanner(System.in); String str = in.nextLine(); String[] strArray = str.split(" "); int a = Integer.parseInt(strArray[0]); int b = Integer.parseInt(strArray[1]); int[] arrayA = new int[a]; int[] arrayB = new int[b]; for (int i = 0; i < arrayA.length; i++) { arrayA[i] = in.nextInt(); } for (int i = 0; i < arrayB.length; i++) { arrayB[i] = in.nextInt(); } System.out.println(bt.betweenTwoSets(arrayA, arrayB)); in.close(); } public int betweenTwoSets(int[] arrayA, int[] arrayB) { int gcf = euclidAlgorithm2(arrayB); List<Integer> factors = factors(gcf); int numCount = 0; for (int i : factors) { int count = 0; for (int j = 0; j < arrayA.length; j++) { if (i % arrayA[j] == 0) { count++; } } if (count == arrayA.length) { numCount++; } } return numCount; } public int euclidAlgorithm(int a, int b) { if (a == 0) { return b; } else if (b == 0) { return a; } else { return euclidAlgorithm(b, a % b); } } public int euclidAlgorithm2(int[] array) { if (array.length == 0) { return 0; } else if (array.length == 1) { return array[0]; } else { int gcf = euclidAlgorithm(array[0], array[1]); for (int i = 2; i < array.length; i++) { gcf = euclidAlgorithm(gcf, array[i]); } return gcf; } } public List<Integer> factors(int n) { List<Integer> factors = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (n % i == 0) { factors.add(i); } } return factors; } }
apache-2.0
nafae/developer
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201409/o/TargetingIdea.java
2103
package com.google.api.ads.adwords.jaxws.v201409.o; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Represents a {@link TargetingIdea} returned by search criteria specified in * the {@link TargetingIdeaSelector}. Targeting ideas are keywords or placements * that are similar to those the user inputs. * * * <p>Java class for TargetingIdea complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="TargetingIdea"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="data" type="{https://adwords.google.com/api/adwords/o/v201409}Type_AttributeMapEntry" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TargetingIdea", propOrder = { "data" }) public class TargetingIdea { protected List<TypeAttributeMapEntry> data; /** * Gets the value of the data 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 data property. * * <p> * For example, to add a new item, do as follows: * <pre> * getData().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TypeAttributeMapEntry } * * */ public List<TypeAttributeMapEntry> getData() { if (data == null) { data = new ArrayList<TypeAttributeMapEntry>(); } return this.data; } }
apache-2.0
dermotte/esop15
src/at/aau/esop15/course10/ThreadConcurrencyExample.java
1295
package at.aau.esop15.course10; import java.util.Iterator; import java.util.LinkedList; /** * @author Dr. Mathias Lux, mlux@itec.aau.at, 10.12.2015. */ public class ThreadConcurrencyExample implements Runnable { boolean up; // increment or decrement int count = 100000000; // each runs # times static int sum; // shared variable public ThreadConcurrencyExample(boolean up) { this.up = up; } public void run() { while (count-- > 0) if (up) sum++; else sum--; } public static void main(String[] args) { LinkedList<Thread> t = new LinkedList<Thread>(); boolean upMe = true; for (int i = 0; i < 10000; i++) { // creating 10 threads Thread thread = new Thread(new ThreadConcurrencyExample(upMe)); upMe = !upMe; thread.start(); t.add(thread); } // making sure to wait for them to end: for (Iterator<Thread> iterator = t.iterator(); iterator.hasNext(); ) { try { iterator.next().join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("sum = " + sum); } }
apache-2.0
vladimirveselov/chatbot-editor-service
src/main/java/org/vvv/chatbotdb/model/SMRule.java
1667
package org.vvv.chatbotdb.model; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class SMRule { private Long id; private String name; private String stateMachineName; private Set<SMCondition> conditions = new HashSet<SMCondition>(); private List<String> actions = new ArrayList<String>(); private List<String> actionNames = new ArrayList<String>(); public Set<SMCondition> getConditions() { return conditions; } public void setConditions(Set<SMCondition> conditions) { this.conditions = conditions; } public List<String> getActions() { return actions; } public void setActions(List<String> actions) { this.actions = actions; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getActionNames() { return actionNames; } public void setActionNames(List<String> actionNames) { this.actionNames = actionNames; } public String getStateMachineName() { return stateMachineName; } public void setStateMachineName(String stateMachineName) { this.stateMachineName = stateMachineName; } @Override public String toString() { return "SMRule [id=" + id + ", name=" + name + ", stateMachineName=" + stateMachineName + ", conditions=" + conditions + ", actions=" + actions + ", actionNames=" + actionNames + "]"; } }
apache-2.0
yasserg/fastutil
test/it/unimi/dsi/fastutil/objects/ObjectAVLTreeSetTest.java
2013
package it.unimi.dsi.fastutil.objects; /* * Copyright (C) 2017 Sebastiano Vigna * * 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. */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.Test; import it.unimi.dsi.fastutil.ints.Int2IntAVLTreeMap; public class ObjectAVLTreeSetTest { @Test public void testGet() { final ObjectAVLTreeSet<Integer> s = new ObjectAVLTreeSet<>(); final Integer o = Integer.valueOf(0); s.add(o); assertSame(o, s.get(Integer.valueOf(0))); } @Test public void testAddTo() { final Int2IntAVLTreeMap a = new Int2IntAVLTreeMap(); final Int2IntAVLTreeMap b = new Int2IntAVLTreeMap(); // test addTo with empty map a.addTo(0, 1); // 0 -> 1 assertEquals(1, a.get(0)); // test addTo with empty map and weird defaultReturnValue b.defaultReturnValue(100); a.addTo(0, 0); // 0 -> 100 assertEquals(100, b.get(0)); // test addTo with existing values a.addTo(0, 1); // 0 -> 2 b.addTo(0, -100); // 0 -> 0 assertEquals(2, a.get(0)); assertEquals(0, b.get(0)); // test addTo with overflow values a.put(0, Integer.MAX_VALUE); a.addTo(0, 1); // 0 -> MIN_VALUE assertEquals(Integer.MIN_VALUE, a.get(0)); // test various addTo operations a.put(0, 0); a.put(1, 1); a.put(2, 2); a.addTo(0, 10); // 0 -> 10 a.addTo(1, 9); // 1 -> 10 a.addTo(2, 8); // 2 -> 10 assertEquals(10, a.get(0)); assertEquals(10, a.get(1)); assertEquals(10, a.get(2)); } }
apache-2.0
gravitee-io/gravitee-definition
jackson/src/main/java/io/gravitee/definition/jackson/datatype/api/deser/LoggingDeserializer.java
2505
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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.gravitee.definition.jackson.datatype.api.deser; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer; import com.fasterxml.jackson.databind.node.TextNode; import io.gravitee.definition.model.Logging; import io.gravitee.definition.model.LoggingContent; import io.gravitee.definition.model.LoggingMode; import io.gravitee.definition.model.LoggingScope; import java.io.IOException; /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team */ public class LoggingDeserializer extends StdScalarDeserializer<Logging> { private static final JsonNode NULL = new TextNode("null"); public LoggingDeserializer(Class<Logging> vc) { super(vc); } @Override public Logging deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); Logging logging = new Logging(); JsonNode mode = node.get("mode"); if (mode != null) { logging.setMode(LoggingMode.valueOf(mode.asText().toUpperCase())); } JsonNode content = node.get("content"); if (content != null) { logging.setContent(LoggingContent.valueOf(content.asText().toUpperCase())); } JsonNode scope = node.get("scope"); if (scope != null) { logging.setScope(LoggingScope.valueOf(scope.asText().toUpperCase())); } JsonNode condition = node.get("condition"); // since 1.20 // test "null" for legacy configuration if (condition != null && !NULL.equals(condition)) { logging.setCondition(condition.asText()); } return logging; } }
apache-2.0
youngwookim/presto
presto-main/src/main/java/io/prestosql/sql/planner/optimizations/MetadataQueryOptimizer.java
9447
/* * 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.prestosql.sql.planner.optimizations; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import io.prestosql.Session; import io.prestosql.SystemSessionProperties; import io.prestosql.execution.warnings.WarningCollector; import io.prestosql.metadata.Metadata; import io.prestosql.metadata.TableProperties; import io.prestosql.spi.connector.ColumnHandle; import io.prestosql.spi.connector.ColumnMetadata; import io.prestosql.spi.connector.DiscretePredicates; import io.prestosql.spi.predicate.NullableValue; import io.prestosql.spi.predicate.TupleDomain; import io.prestosql.spi.type.Type; import io.prestosql.sql.planner.DeterminismEvaluator; import io.prestosql.sql.planner.LiteralEncoder; import io.prestosql.sql.planner.PlanNodeIdAllocator; import io.prestosql.sql.planner.Symbol; import io.prestosql.sql.planner.SymbolAllocator; import io.prestosql.sql.planner.TypeProvider; import io.prestosql.sql.planner.plan.AggregationNode; import io.prestosql.sql.planner.plan.AggregationNode.Aggregation; import io.prestosql.sql.planner.plan.FilterNode; import io.prestosql.sql.planner.plan.LimitNode; import io.prestosql.sql.planner.plan.MarkDistinctNode; import io.prestosql.sql.planner.plan.PlanNode; import io.prestosql.sql.planner.plan.ProjectNode; import io.prestosql.sql.planner.plan.SimplePlanRewriter; import io.prestosql.sql.planner.plan.SortNode; import io.prestosql.sql.planner.plan.TableScanNode; import io.prestosql.sql.planner.plan.TopNNode; import io.prestosql.sql.planner.plan.ValuesNode; import io.prestosql.sql.tree.Expression; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import static java.util.Objects.requireNonNull; /** * Converts cardinality-insensitive aggregations (max, min, "distinct") over partition keys * into simple metadata queries */ public class MetadataQueryOptimizer implements PlanOptimizer { private static final Set<String> ALLOWED_FUNCTIONS = ImmutableSet.of("max", "min", "approx_distinct"); private final Metadata metadata; private final LiteralEncoder literalEncoder; public MetadataQueryOptimizer(Metadata metadata) { requireNonNull(metadata, "metadata is null"); this.metadata = metadata; this.literalEncoder = new LiteralEncoder(metadata.getBlockEncodingSerde()); } @Override public PlanNode optimize(PlanNode plan, Session session, TypeProvider types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) { if (!SystemSessionProperties.isOptimizeMetadataQueries(session)) { return plan; } return SimplePlanRewriter.rewriteWith(new Optimizer(session, metadata, literalEncoder, idAllocator), plan, null); } private static class Optimizer extends SimplePlanRewriter<Void> { private final PlanNodeIdAllocator idAllocator; private final Session session; private final Metadata metadata; private final LiteralEncoder literalEncoder; private Optimizer(Session session, Metadata metadata, LiteralEncoder literalEncoder, PlanNodeIdAllocator idAllocator) { this.session = session; this.metadata = metadata; this.literalEncoder = literalEncoder; this.idAllocator = idAllocator; } @Override public PlanNode visitAggregation(AggregationNode node, RewriteContext<Void> context) { // supported functions are only MIN/MAX/APPROX_DISTINCT or distinct aggregates for (Aggregation aggregation : node.getAggregations().values()) { if (!ALLOWED_FUNCTIONS.contains(aggregation.getCall().getName().toString()) && !aggregation.getCall().isDistinct()) { return context.defaultRewrite(node); } } Optional<TableScanNode> result = findTableScan(node.getSource()); if (!result.isPresent()) { return context.defaultRewrite(node); } // verify all outputs of table scan are partition keys TableScanNode tableScan = result.get(); ImmutableMap.Builder<Symbol, Type> typesBuilder = ImmutableMap.builder(); ImmutableMap.Builder<Symbol, ColumnHandle> columnBuilder = ImmutableMap.builder(); List<Symbol> inputs = tableScan.getOutputSymbols(); for (Symbol symbol : inputs) { ColumnHandle column = tableScan.getAssignments().get(symbol); ColumnMetadata columnMetadata = metadata.getColumnMetadata(session, tableScan.getTable(), column); typesBuilder.put(symbol, columnMetadata.getType()); columnBuilder.put(symbol, column); } Map<Symbol, ColumnHandle> columns = columnBuilder.build(); Map<Symbol, Type> types = typesBuilder.build(); // Materialize the list of partitions and replace the TableScan node // with a Values node TableProperties layout = metadata.getTableProperties(session, tableScan.getTable()); if (!layout.getDiscretePredicates().isPresent()) { return context.defaultRewrite(node); } DiscretePredicates predicates = layout.getDiscretePredicates().get(); // the optimization is only valid if the aggregation node only relies on partition keys if (!predicates.getColumns().containsAll(columns.values())) { return context.defaultRewrite(node); } ImmutableList.Builder<List<Expression>> rowsBuilder = ImmutableList.builder(); for (TupleDomain<ColumnHandle> domain : predicates.getPredicates()) { if (!domain.isNone()) { Map<ColumnHandle, NullableValue> entries = TupleDomain.extractFixedValues(domain).get(); ImmutableList.Builder<Expression> rowBuilder = ImmutableList.builder(); // for each input column, add a literal expression using the entry value for (Symbol input : inputs) { ColumnHandle column = columns.get(input); Type type = types.get(input); NullableValue value = entries.get(column); if (value == null) { // partition key does not have a single value, so bail out to be safe return context.defaultRewrite(node); } else { rowBuilder.add(literalEncoder.toExpression(value.getValue(), type)); } } rowsBuilder.add(rowBuilder.build()); } } // replace the tablescan node with a values node ValuesNode valuesNode = new ValuesNode(idAllocator.getNextId(), inputs, rowsBuilder.build()); return SimplePlanRewriter.rewriteWith(new Replacer(valuesNode), node); } private static Optional<TableScanNode> findTableScan(PlanNode source) { while (true) { // allow any chain of linear transformations if (source instanceof MarkDistinctNode || source instanceof FilterNode || source instanceof LimitNode || source instanceof TopNNode || source instanceof SortNode) { source = source.getSources().get(0); } else if (source instanceof ProjectNode) { // verify projections are deterministic ProjectNode project = (ProjectNode) source; if (!Iterables.all(project.getAssignments().getExpressions(), DeterminismEvaluator::isDeterministic)) { return Optional.empty(); } source = project.getSource(); } else if (source instanceof TableScanNode) { return Optional.of((TableScanNode) source); } else { return Optional.empty(); } } } } private static class Replacer extends SimplePlanRewriter<Void> { private final ValuesNode replacement; private Replacer(ValuesNode replacement) { this.replacement = replacement; } @Override public PlanNode visitTableScan(TableScanNode node, RewriteContext<Void> context) { return replacement; } } }
apache-2.0
bella0101/websitePortal
src/main/java/org/nmrg/common/utils/equipment/EquipmentUtiles.java
1089
package org.nmrg.common.utils.equipment; import eu.bitwalker.useragentutils.UserAgent; import org.slf4j.LoggerFactory; import org.nmrg.model.client.EquipmentModel; import org.slf4j.Logger; import javax.servlet.http.HttpServletRequest; /** * 获取用户设备信息 * 示例: * 设备名 * 设备型号 * 设备系统 * 设备系统版本 * Created by admin on 2017/9/20. */ public class EquipmentUtiles { private static final Logger _LOG = LoggerFactory.getLogger(EquipmentUtiles.class); /** * 返回用户设备信息 * @param request * @return */ public static EquipmentModel getEquipmentInfo(HttpServletRequest request){ EquipmentModel equipmentModel = new EquipmentModel(); String userAgentStr = ""; userAgentStr = request.getHeader("User-Agent"); UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr); equipmentModel.setUserAgent(userAgentStr); equipmentModel.setName(""); return equipmentModel; } }
apache-2.0
BiaoWu/BAdapter
example/src/main/java/com/biao/badapter/sample/multi/DataBindingMultiItemFragment.java
4366
package com.biao.badapter.sample.multi; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.biao.badapter.BAdapter; import com.biao.badapter.BDataSource; import com.biao.badapter.OnItemClickListener; import com.biao.badapter.sample.BFragment; import com.biao.badapter.sample.R; import com.biao.badapter.sample.databinding.SimpleText1Binding; import com.biao.badapter.sample.databinding.SimpleText2Binding; import com.biao.delegate.databinding.BDataBindingItemDelegate; import com.biao.delegate.databinding.BDataBindingViewHolder; /** * @author biaowu. */ public class DataBindingMultiItemFragment extends BFragment { @Override protected BAdapter buildAdapter() { BDataSource<Person> dataSource = new BDataSource<>(); for (int i = 1; i <= 30; i++) { dataSource.add(new Person(i, "Clone Bill No." + i)); } BDataBindingItemDelegate<SimpleText1Binding, Person> itemDelegate1 = new BDataBindingItemDelegate<SimpleText1Binding, Person>() { @Override protected void onBind(BDataBindingViewHolder<SimpleText1Binding> holder, Person person) { holder.binding.setContent(person.toString()); } @Override protected SimpleText1Binding onCreateBinding(LayoutInflater inflater, ViewGroup parent) { return SimpleText1Binding.inflate(inflater, parent, false); } @Override protected boolean onIntercept(int position, Object o) { return o instanceof Person && ((Person) o).id % 2 == 0; } }; itemDelegate1.dispatchViewClick(R.id.image) .setOnItemClickListener( new OnItemClickListener<BDataBindingViewHolder<SimpleText1Binding>, Person>() { @Override public void onItemClick(View view, BDataBindingViewHolder<SimpleText1Binding> viewHolder, Person person) { switch (view.getId()) { case R.id.image: Toast.makeText(view.getContext(), "Image Click at position : " + viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show(); break; default: Toast.makeText(view.getContext(), "Item Click at position : " + viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show(); break; } } }); BDataBindingItemDelegate<SimpleText2Binding, Person> itemDelegate2 = new BDataBindingItemDelegate<SimpleText2Binding, Person>() { @Override protected void onBind(BDataBindingViewHolder<SimpleText2Binding> holder, Person person) { holder.binding.setContent(person.toString()); } @Override protected SimpleText2Binding onCreateBinding(LayoutInflater inflater, ViewGroup parent) { return SimpleText2Binding.inflate(inflater, parent, false); } @Override protected boolean onIntercept(int position, Object o) { return o instanceof Person && ((Person) o).id % 2 != 0; } }; itemDelegate2.dispatchViewClick(R.id.image) .setOnItemClickListener( new OnItemClickListener<BDataBindingViewHolder<SimpleText2Binding>, Person>() { @Override public void onItemClick(View view, BDataBindingViewHolder<SimpleText2Binding> viewHolder, Person person) { switch (view.getId()) { case R.id.image: Toast.makeText(view.getContext(), "Image Click at position : " + viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show(); break; default: Toast.makeText(view.getContext(), "Item Click at position : " + viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show(); break; } } }); return BAdapter.builder() .dataSource(dataSource) .itemDelegate(itemDelegate1) .itemDelegate(itemDelegate2) .build(); } }
apache-2.0
lsimons/phloc-schematron-standalone
phloc-commons/src/test/java/com/phloc/commons/collections/pair/ReadonlyIntPairTest.java
2138
/** * Copyright (C) 2006-2013 phloc systems * http://www.phloc.com * office[at]phloc[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.phloc.commons.collections.pair; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.phloc.commons.mock.PhlocTestUtils; /** * Test class for class {@link ReadonlyIntPair}. * * @author Philip Helger */ public final class ReadonlyIntPairTest { @Test public void testCtor () { ReadonlyIntPair aPair = new ReadonlyIntPair (0, 0); assertEquals (0, aPair.getFirst ()); assertEquals (0, aPair.getSecond ()); ReadonlyIntPair aPair2 = new ReadonlyIntPair (aPair); assertEquals (0, aPair2.getFirst ()); assertEquals (0, aPair2.getSecond ()); aPair = new ReadonlyIntPair (5, 2); assertEquals (5, aPair.getFirst ()); assertEquals (2, aPair.getSecond ()); aPair2 = new ReadonlyIntPair (aPair); assertEquals (5, aPair2.getFirst ()); assertEquals (2, aPair2.getSecond ()); PhlocTestUtils.testDefaultImplementationWithEqualContentObject (new ReadonlyIntPair (5, -30), new ReadonlyIntPair (5, -30)); PhlocTestUtils.testDefaultImplementationWithDifferentContentObject (new ReadonlyIntPair (5, -30), new ReadonlyIntPair (-5, -30)); PhlocTestUtils.testDefaultImplementationWithDifferentContentObject (new ReadonlyIntPair (5, -30), new ReadonlyIntPair (5, 30)); } }
apache-2.0
CloudWorkers/cloudworker
server/src/main/java/com/cloudworkers/cloudworker/repository/UserRepository.java
825
package com.cloudworkers.cloudworker.repository; import com.cloudworkers.cloudworker.domain.User; import java.time.ZonedDateTime; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; import java.util.Optional; /** * Spring Data JPA repository for the User entity. */ public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findOneByActivationKey(String activationKey); List<User> findAllByActivatedIsFalseAndCreatedDateBefore(ZonedDateTime dateTime); Optional<User> findOneByResetKey(String resetKey); Optional<User> findOneByEmail(String email); Optional<User> findOneByLogin(String login); Optional<User> findOneById(Long userId); @Override void delete(User t); }
apache-2.0
DenverM80/ds3_java_sdk
ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/parsers/GetTapeDriveSpectraS3ResponseParser.java
2381
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ // This code is auto-generated, do not modify package com.spectralogic.ds3client.commands.parsers; import com.spectralogic.ds3client.commands.parsers.interfaces.AbstractResponseParser; import com.spectralogic.ds3client.commands.parsers.utils.ResponseParserUtils; import com.spectralogic.ds3client.commands.spectrads3.GetTapeDriveSpectraS3Response; import com.spectralogic.ds3client.models.TapeDrive; import com.spectralogic.ds3client.networking.WebResponse; import com.spectralogic.ds3client.serializer.XmlOutput; import java.io.IOException; import java.io.InputStream; public class GetTapeDriveSpectraS3ResponseParser extends AbstractResponseParser<GetTapeDriveSpectraS3Response> { private final int[] expectedStatusCodes = new int[]{200}; @Override public GetTapeDriveSpectraS3Response parseXmlResponse(final WebResponse response) throws IOException { final int statusCode = response.getStatusCode(); if (ResponseParserUtils.validateStatusCode(statusCode, expectedStatusCodes)) { switch (statusCode) { case 200: try (final InputStream inputStream = response.getResponseStream()) { final TapeDrive result = XmlOutput.fromXml(inputStream, TapeDrive.class); return new GetTapeDriveSpectraS3Response(result, this.getChecksum(), this.getChecksumType()); } default: assert false: "validateStatusCode should have made it impossible to reach this line"; } } throw ResponseParserUtils.createFailedRequest(response, expectedStatusCodes); } }
apache-2.0
turing2017/Dise-o-2017
SistemaPagoImpuestos/src/sistemapagoimpuestos/View/Admin/GestionarTipoImpuesto/IUGestionarTipoImpuestoModificar.java
14822
package sistemapagoimpuestos.View.Admin.GestionarTipoImpuesto; import exceptions.Excepciones; import java.awt.Component; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Vector; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import sistemapagoimpuestos.Controller.ControladorGestionarTipoImpuesto; import sistemapagoimpuestos.Dto.DTOEmpresaTipImpItem; import sistemapagoimpuestos.Dto.DTOEmpresaTipoImpuestoItems; import sistemapagoimpuestos.Dto.DTOItem; import sistemapagoimpuestos.Dto.DTOTipoImpuesto; import sistemapagoimpuestos.Dto.DtoItemOrden; /** * * @author lunamarcos */ public class IUGestionarTipoImpuestoModificar extends javax.swing.JFrame { ControladorGestionarTipoImpuesto controlador = new ControladorGestionarTipoImpuesto(); private static List<DTOEmpresaTipImpItem> dTOEmpresaTipImpItemList = new ArrayList<>(); public static List<DTOEmpresaTipImpItem> getdTOEmpresaTipImpItemList() { return dTOEmpresaTipImpItemList; } public static void setdTOEmpresaTipImpItemList(List<DTOEmpresaTipImpItem> dTOEmpresaTipImpItemList) { IUGestionarTipoImpuestoModificar.dTOEmpresaTipImpItemList = dTOEmpresaTipImpItemList; } public String getNombre_actual() { return nombre_actual.getText(); } public void setNombre_actual(String nombre_actual) { this.nombre_actual.setText(nombre_actual); } public static void adddTOEmpresaTipImpItemList(DTOEmpresaTipImpItem dTOEmpresaTipImpItem){ if(dTOEmpresaTipImpItemList==null){ dTOEmpresaTipImpItemList = new ArrayList<>(); } dTOEmpresaTipImpItemList.add(dTOEmpresaTipImpItem); } public static void removedTOEmpresaTipImpItemList(int index){ dTOEmpresaTipImpItemList.remove(index); } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor. */ public IUGestionarTipoImpuestoModificar( String cuitEmpresa) { } public IUGestionarTipoImpuestoModificar() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { label_nombre = new javax.swing.JLabel(); label_deshabilitar = new javax.swing.JLabel(); label_esEditable = new javax.swing.JLabel(); textfield_nombre = new javax.swing.JTextField(); checkbox_habilitado = new javax.swing.JCheckBox(); checkbox_esEditable = new javax.swing.JCheckBox(); button_modificar = new javax.swing.JButton(); nombre_actual = new javax.swing.JLabel(); cancel_button = new javax.swing.JButton(); label_fecha = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); label_nombre.setText("Nombre"); label_nombre.setToolTipText(""); label_deshabilitar.setText("Habilitado"); label_esEditable.setText("Es editable"); textfield_nombre.setToolTipText(""); textfield_nombre.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textfield_nombreActionPerformed(evt); } }); checkbox_habilitado.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkbox_habilitadoActionPerformed(evt); } }); checkbox_esEditable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkbox_esEditableActionPerformed(evt); } }); button_modificar.setText("Modificar"); button_modificar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button_modificarActionPerformed(evt); } }); nombre_actual.setForeground(new java.awt.Color(240, 240, 240)); nombre_actual.setText("nombreActual"); cancel_button.setText("Cancelar"); cancel_button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancel_buttonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(68, 68, 68) .addComponent(cancel_button) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(button_modificar)) .addGroup(layout.createSequentialGroup() .addContainerGap(119, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(label_deshabilitar) .addComponent(label_esEditable)) .addGroup(layout.createSequentialGroup() .addGap(3, 3, 3) .addComponent(label_nombre))) .addGap(94, 94, 94) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(checkbox_esEditable) .addComponent(textfield_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(checkbox_habilitado, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(label_fecha)) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(nombre_actual))))) .addGap(56, 56, 56)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(128, 128, 128) .addComponent(nombre_actual)) .addGroup(layout.createSequentialGroup() .addGap(49, 49, 49) .addComponent(label_fecha))) .addGap(66, 66, 66) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cancel_button) .addComponent(button_modificar))) .addGroup(layout.createSequentialGroup() .addGap(41, 41, 41) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textfield_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label_nombre)) .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(checkbox_habilitado) .addComponent(label_deshabilitar)) .addGap(27, 27, 27) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label_esEditable) .addComponent(checkbox_esEditable)))) .addContainerGap(27, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void button_modificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_modificarActionPerformed // TODO add your handling code here: try{ if(textfield_nombre.getText().equals("")){ textfield_nombre.setText(null); throw new java.lang.NumberFormatException(); } controlador.modificarTipoImpuesto(textfield_nombre.getText(), nombre_actual.getText(), checkbox_esEditable.isSelected(), checkbox_habilitado.isSelected(), dTOEmpresaTipImpItemList); this.dispose(); controlador.iniciar(); }catch(java.lang.NumberFormatException e){ Excepciones.getInstance().camposRequerido(Arrays.asList("Nombre")); } }//GEN-LAST:event_button_modificarActionPerformed private void textfield_nombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textfield_nombreActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textfield_nombreActionPerformed private void cancel_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancel_buttonActionPerformed this.dispose(); controlador.iniciar(); }//GEN-LAST:event_cancel_buttonActionPerformed private void checkbox_habilitadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkbox_habilitadoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_checkbox_habilitadoActionPerformed private void checkbox_esEditableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkbox_esEditableActionPerformed // TODO add your handling code here: }//GEN-LAST:event_checkbox_esEditableActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(IUGestionarTipoImpuestoModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(IUGestionarTipoImpuestoModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(IUGestionarTipoImpuestoModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(IUGestionarTipoImpuestoModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { // Asociacion con el controlador IUGestionarTipoImpuestoModificar pantallaModificar = new IUGestionarTipoImpuestoModificar(); } }); } // Getters public String getTextfield_nombre() { return textfield_nombre.getText(); } public void setTextfield_nombre(String text) { this.textfield_nombre.setText(text); } public boolean getCheckbox_deshabilitar() { return checkbox_habilitado.isSelected(); } public void setCheckbox_Habilitar(boolean habilitado) { this.checkbox_habilitado.setSelected(habilitado); } public boolean getCheckbox_esEditable() { return checkbox_esEditable.isSelected(); } public void setCheckbox_esEditable(boolean editable) { this.checkbox_esEditable.setSelected(editable); } public JLabel getLabel_fecha() { return label_fecha; } public void setLabel_fecha(JLabel label_fecha) { this.label_fecha = label_fecha; } public String getLabel_nombre() { return label_nombre.getText(); } public void setLabel_nombre(String nombre) { this.label_nombre.setText(nombre); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton button_modificar; private javax.swing.JButton cancel_button; private javax.swing.JCheckBox checkbox_esEditable; private javax.swing.JCheckBox checkbox_habilitado; private javax.swing.JLabel label_deshabilitar; private javax.swing.JLabel label_esEditable; private javax.swing.JLabel label_fecha; private javax.swing.JLabel label_nombre; private javax.swing.JLabel nombre_actual; private javax.swing.JTextField textfield_nombre; // End of variables declaration//GEN-END:variables }
apache-2.0
arnelandwehr/killbill-adyen-plugin
src/main/java/org/killbill/billing/plugin/adyen/client/payment/converter/impl/AmexConverter.java
990
/* * Copyright 2015 Groupon, Inc * * Groupon 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.killbill.billing.plugin.adyen.client.payment.converter.impl; import org.killbill.billing.plugin.adyen.client.model.PaymentType; import static org.killbill.billing.plugin.adyen.client.model.PaymentType.AMEX; public class AmexConverter extends CreditCardConverter { @Override public PaymentType getPaymentType() { return AMEX; } }
apache-2.0
DenverM80/ds3_java_sdk
ds3-sdk/src/main/java/com/spectralogic/ds3client/models/TapeState.java
1463
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ // This code is auto-generated, do not modify package com.spectralogic.ds3client.models; public enum TapeState { NORMAL, OFFLINE, ONLINE_PENDING, ONLINE_IN_PROGRESS, PENDING_INSPECTION, UNKNOWN, DATA_CHECKPOINT_FAILURE, DATA_CHECKPOINT_FAILURE_DUE_TO_READ_ONLY, DATA_CHECKPOINT_MISSING, LTFS_WITH_FOREIGN_DATA, RAW_IMPORT_PENDING, RAW_IMPORT_IN_PROGRESS, FOREIGN, IMPORT_PENDING, IMPORT_IN_PROGRESS, INCOMPATIBLE, LOST, BAD, CANNOT_FORMAT_DUE_TO_WRITE_PROTECTION, SERIAL_NUMBER_MISMATCH, BAR_CODE_MISSING, FORMAT_PENDING, FORMAT_IN_PROGRESS, EJECT_TO_EE_IN_PROGRESS, EJECT_FROM_EE_PENDING, EJECTED }
apache-2.0
hong123608/testtwo
android-app/app/src/main/java/net/oschina/app/widget/TouchImageView.java
42401
package net.oschina.app.widget; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.ImageView; import android.widget.OverScroller; import android.widget.Scroller; /** * Created by serhatsurguvec on 10/14/15. */ /* * TouchImageView.java * By: Michael Ortiz * Updated By: Patrick Lackemacher * Updated By: Babay88 * Updated By: @ipsilondev * Updated By: hank-cp * Updated By: singpolyma * ------------------- * Extends Android ImageView to include pinch zooming, panning, fling and double tap zoom. */ public class TouchImageView extends ImageView { private final String TAG = getClass().getName(); private static final String DEBUG = "DEBUG"; // // SuperMin and SuperMax multipliers. Determine how much the image can be // zoomed below or above the zoom boundaries, before animating back to the // min/max zoom boundary. // private static final float SUPER_MIN_MULTIPLIER = .75f; private static final float SUPER_MAX_MULTIPLIER = 1.25f; // // Scale of image ranges from minScale to maxScale, where minScale == 1 // when the image is stretched to fit view. // private float normalizedScale; // // Matrix applied to image. MSCALE_X and MSCALE_Y should always be equal. // MTRANS_X and MTRANS_Y are the other values used. prevMatrix is the matrix // saved prior to the screen rotating. // private Matrix matrix, prevMatrix; private static enum State {NONE, DRAG, ZOOM, FLING, ANIMATE_ZOOM} private State state; private float minScale; private float maxScale; private float superMinScale; private float superMaxScale; private float[] m; private Context context; private Fling fling; private ScaleType mScaleType; private boolean imageRenderedAtLeastOnce; private boolean onDrawReady; private ZoomVariables delayedZoomVariables; // // Size of view and previous view size (ie before rotation) // private int viewWidth, viewHeight, prevViewWidth, prevViewHeight; // // Size of image when it is stretched to fit view. Before and After rotation. // private float matchViewWidth, matchViewHeight, prevMatchViewWidth, prevMatchViewHeight; private ScaleGestureDetector mScaleDetector; private GestureDetector mGestureDetector; private GestureDetector.OnDoubleTapListener doubleTapListener = null; private OnTouchListener userTouchListener = null; private OnTouchImageViewListener touchImageViewListener = null; public TouchImageView(Context context) { super(context); sharedConstructing(context); } public TouchImageView(Context context, AttributeSet attrs) { super(context, attrs); sharedConstructing(context); } public TouchImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); sharedConstructing(context); } private void sharedConstructing(Context context) { super.setClickable(true); this.context = context; mScaleDetector = new ScaleGestureDetector(context, new ScaleListener()); mGestureDetector = new GestureDetector(context, new GestureListener()); matrix = new Matrix(); prevMatrix = new Matrix(); m = new float[9]; normalizedScale = 1; if (mScaleType == null) { mScaleType = ScaleType.MATRIX; } minScale = 1; maxScale = 4; superMinScale = SUPER_MIN_MULTIPLIER * minScale; superMaxScale = SUPER_MAX_MULTIPLIER * maxScale; setImageMatrix(matrix); setScaleType(ScaleType.MATRIX); setState(State.NONE); onDrawReady = false; super.setOnTouchListener(new PrivateOnTouchListener()); } @Override public void setOnTouchListener(OnTouchListener l) { userTouchListener = l; } public void setOnTouchImageViewListener(OnTouchImageViewListener l) { touchImageViewListener = l; } public void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener l) { doubleTapListener = l; } @Override public void setImageResource(int resId) { super.setImageResource(resId); savePreviousImageValues(); fitImageToView(); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); savePreviousImageValues(); fitImageToView(); } @Override public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); savePreviousImageValues(); fitImageToView(); } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); savePreviousImageValues(); fitImageToView(); } @Override public void setScaleType(ScaleType type) { if (type == ScaleType.FIT_START || type == ScaleType.FIT_END) { throw new UnsupportedOperationException("TouchImageView does not support FIT_START or FIT_END"); } if (type == ScaleType.MATRIX) { super.setScaleType(ScaleType.MATRIX); } else { mScaleType = type; if (onDrawReady) { // // If the image is already rendered, scaleType has been called programmatically // and the TouchImageView should be updated with the new scaleType. // setZoom(this); } } } @Override public ScaleType getScaleType() { return mScaleType; } /** * Returns false if image is in initial, unzoomed state. False, otherwise. * * @return true if image is zoomed */ public boolean isZoomed() { return normalizedScale != 1; } /** * Return a Rect representing the zoomed image. * * @return rect representing zoomed image */ public RectF getZoomedRect() { if (mScaleType == ScaleType.FIT_XY) { throw new UnsupportedOperationException("getZoomedRect() not supported with FIT_XY"); } PointF topLeft = transformCoordTouchToBitmap(0, 0, true); PointF bottomRight = transformCoordTouchToBitmap(viewWidth, viewHeight, true); float w = getDrawable().getIntrinsicWidth(); float h = getDrawable().getIntrinsicHeight(); return new RectF(topLeft.x / w, topLeft.y / h, bottomRight.x / w, bottomRight.y / h); } /** * Save the current matrix and view dimensions * in the prevMatrix and prevView variables. */ private void savePreviousImageValues() { if (matrix != null && viewHeight != 0 && viewWidth != 0) { matrix.getValues(m); prevMatrix.setValues(m); prevMatchViewHeight = matchViewHeight; prevMatchViewWidth = matchViewWidth; prevViewHeight = viewHeight; prevViewWidth = viewWidth; } } @Override public Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); bundle.putParcelable("instanceState", super.onSaveInstanceState()); bundle.putFloat("saveScale", normalizedScale); bundle.putFloat("matchViewHeight", matchViewHeight); bundle.putFloat("matchViewWidth", matchViewWidth); bundle.putInt("viewWidth", viewWidth); bundle.putInt("viewHeight", viewHeight); matrix.getValues(m); bundle.putFloatArray("matrix", m); bundle.putBoolean("imageRendered", imageRenderedAtLeastOnce); return bundle; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Bundle bundle = (Bundle) state; normalizedScale = bundle.getFloat("saveScale"); m = bundle.getFloatArray("matrix"); prevMatrix.setValues(m); prevMatchViewHeight = bundle.getFloat("matchViewHeight"); prevMatchViewWidth = bundle.getFloat("matchViewWidth"); prevViewHeight = bundle.getInt("viewHeight"); prevViewWidth = bundle.getInt("viewWidth"); imageRenderedAtLeastOnce = bundle.getBoolean("imageRendered"); super.onRestoreInstanceState(bundle.getParcelable("instanceState")); return; } super.onRestoreInstanceState(state); } @Override protected void onDraw(Canvas canvas) { onDrawReady = true; imageRenderedAtLeastOnce = true; if (delayedZoomVariables != null) { setZoom(delayedZoomVariables.scale, delayedZoomVariables.focusX, delayedZoomVariables.focusY, delayedZoomVariables.scaleType); delayedZoomVariables = null; } super.onDraw(canvas); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); savePreviousImageValues(); } /** * Get the max zoom multiplier. * * @return max zoom multiplier. */ public float getMaxZoom() { return maxScale; } /** * Set the max zoom multiplier. Default value: 3. * * @param max max zoom multiplier. */ public void setMaxZoom(float max) { maxScale = max; superMaxScale = SUPER_MAX_MULTIPLIER * maxScale; } /** * Get the min zoom multiplier. * * @return min zoom multiplier. */ public float getMinZoom() { return minScale; } /** * Get the current zoom. This is the zoom relative to the initial * scale, not the original resource. * * @return current zoom multiplier. */ public float getCurrentZoom() { return normalizedScale; } /** * Set the min zoom multiplier. Default value: 1. * * @param min min zoom multiplier. */ public void setMinZoom(float min) { minScale = min; superMinScale = SUPER_MIN_MULTIPLIER * minScale; } /** * Reset zoom and translation to initial state. */ public void resetZoom() { normalizedScale = 1; fitImageToView(); } /** * Set zoom to the specified scale. Image will be centered by default. * * @param scale */ public void setZoom(float scale) { setZoom(scale, 0.5f, 0.5f); } /** * Set zoom to the specified scale. Image will be centered around the point * (focusX, focusY). These floats range from 0 to 1 and denote the focus point * as a fraction from the left and top of the view. For example, the top left * corner of the image would be (0, 0). And the bottom right corner would be (1, 1). * * @param scale * @param focusX * @param focusY */ public void setZoom(float scale, float focusX, float focusY) { setZoom(scale, focusX, focusY, mScaleType); } /** * Set zoom to the specified scale. Image will be centered around the point * (focusX, focusY). These floats range from 0 to 1 and denote the focus point * as a fraction from the left and top of the view. For example, the top left * corner of the image would be (0, 0). And the bottom right corner would be (1, 1). * * @param scale * @param focusX * @param focusY * @param scaleType */ public void setZoom(float scale, float focusX, float focusY, ScaleType scaleType) { // // setZoom can be called before the image is on the screen, but at this point, // image and view sizes have not yet been calculated in onMeasure. Thus, we should // delay calling setZoom until the view has been measured. // if (!onDrawReady) { delayedZoomVariables = new ZoomVariables(scale, focusX, focusY, scaleType); return; } if (scaleType != mScaleType) { setScaleType(scaleType); } resetZoom(); scaleImage(scale, viewWidth / 2, viewHeight / 2, true); matrix.getValues(m); m[Matrix.MTRANS_X] = -((focusX * getImageWidth()) - (viewWidth * 0.5f)); m[Matrix.MTRANS_Y] = -((focusY * getImageHeight()) - (viewHeight * 0.5f)); matrix.setValues(m); fixTrans(); setImageMatrix(matrix); } /** * Set zoom parameters equal to another TouchImageView. Including scale, position, * and ScaleType. * * @param img */ public void setZoom(TouchImageView img) { PointF center = img.getScrollPosition(); setZoom(img.getCurrentZoom(), center.x, center.y, img.getScaleType()); } /** * Return the point at the center of the zoomed image. The PointF coordinates range * in value between 0 and 1 and the focus point is denoted as a fraction from the left * and top of the view. For example, the top left corner of the image would be (0, 0). * And the bottom right corner would be (1, 1). * * @return PointF representing the scroll position of the zoomed image. */ public PointF getScrollPosition() { Drawable drawable = getDrawable(); if (drawable == null) { return null; } int drawableWidth = drawable.getIntrinsicWidth(); int drawableHeight = drawable.getIntrinsicHeight(); PointF point = transformCoordTouchToBitmap(viewWidth / 2, viewHeight / 2, true); point.x /= drawableWidth; point.y /= drawableHeight; return point; } /** * Set the focus point of the zoomed image. The focus points are denoted as a fraction from the * left and top of the view. The focus points can range in value between 0 and 1. * * @param focusX * @param focusY */ public void setScrollPosition(float focusX, float focusY) { setZoom(normalizedScale, focusX, focusY); } /** * Performs boundary checking and fixes the image matrix if it * is out of bounds. */ private void fixTrans() { matrix.getValues(m); float transX = m[Matrix.MTRANS_X]; float transY = m[Matrix.MTRANS_Y]; float fixTransX = getFixTrans(transX, viewWidth, getImageWidth()); float fixTransY = getFixTrans(transY, viewHeight, getImageHeight()); if (fixTransX != 0 || fixTransY != 0) { matrix.postTranslate(fixTransX, fixTransY); } } /** * When transitioning from zooming from focus to zoom from center (or vice versa) * the image can become unaligned within the view. This is apparent when zooming * quickly. When the content size is less than the view size, the content will often * be centered incorrectly within the view. fixScaleTrans first calls fixTrans() and * then makes sure the image is centered correctly within the view. */ private void fixScaleTrans() { fixTrans(); matrix.getValues(m); if (getImageWidth() < viewWidth) { m[Matrix.MTRANS_X] = (viewWidth - getImageWidth()) / 2; } if (getImageHeight() < viewHeight) { m[Matrix.MTRANS_Y] = (viewHeight - getImageHeight()) / 2; } matrix.setValues(m); } private float getFixTrans(float trans, float viewSize, float contentSize) { float minTrans, maxTrans; if (contentSize <= viewSize) { minTrans = 0; maxTrans = viewSize - contentSize; } else { minTrans = viewSize - contentSize; maxTrans = 0; } if (trans < minTrans) return -trans + minTrans; if (trans > maxTrans) return -trans + maxTrans; return 0; } private float getFixDragTrans(float delta, float viewSize, float contentSize) { if (contentSize <= viewSize) { return 0; } return delta; } private float getImageWidth() { return matchViewWidth * normalizedScale; } private float getImageHeight() { return matchViewHeight * normalizedScale; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Drawable drawable = getDrawable(); if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) { setMeasuredDimension(0, 0); return; } int drawableWidth = drawable.getIntrinsicWidth(); int drawableHeight = drawable.getIntrinsicHeight(); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); viewWidth = setViewSize(widthMode, widthSize, drawableWidth); viewHeight = setViewSize(heightMode, heightSize, drawableHeight); // // Set view dimensions // setMeasuredDimension(viewWidth, viewHeight); // // Fit content within view // fitImageToView(); } /** * If the normalizedScale is equal to 1, then the image is made to fit the screen. Otherwise, * it is made to fit the screen according to the dimensions of the previous image matrix. This * allows the image to maintain its zoom after rotation. */ private void fitImageToView() { Drawable drawable = getDrawable(); if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) { return; } if (matrix == null || prevMatrix == null) { return; } int drawableWidth = drawable.getIntrinsicWidth(); int drawableHeight = drawable.getIntrinsicHeight(); // TLog.log("imageView", "viewWidth=" + viewWidth + ":viewHeight" + viewHeight + "drawableWidth=" + drawableWidth + ":drawableHeight" + drawableHeight); // // Scale image for view // float scaleX = (float) viewWidth / drawableWidth; float scaleY = scaleX; // // Center the image // float redundantXSpace = viewWidth - (scaleX * drawableWidth); float redundantYSpace = viewHeight - (scaleY * drawableHeight); matchViewWidth = viewWidth - redundantXSpace; matchViewHeight = viewHeight - redundantYSpace; if (!isZoomed() && !imageRenderedAtLeastOnce) { // // Stretch and center image to fit view // matrix.setScale(scaleX, scaleY); if (matchViewHeight > viewHeight) { matrix.postTranslate(0, 0); } else { matrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2); } normalizedScale = 1; } else { // // These values should never be 0 or we will set viewWidth and viewHeight // to NaN in translateMatrixAfterRotate. To avoid this, call savePreviousImageValues // to set them equal to the current values. // if (prevMatchViewWidth == 0 || prevMatchViewHeight == 0) { savePreviousImageValues(); } prevMatrix.getValues(m); // // Rescale Matrix after rotation // m[Matrix.MSCALE_X] = matchViewWidth / drawableWidth * normalizedScale; m[Matrix.MSCALE_Y] = matchViewHeight / drawableHeight * normalizedScale; // // TransX and TransY from previous matrix // float transX = m[Matrix.MTRANS_X]; float transY = m[Matrix.MTRANS_Y]; // // Width // float prevActualWidth = prevMatchViewWidth * normalizedScale; float actualWidth = getImageWidth(); translateMatrixAfterRotate(Matrix.MTRANS_X, transX, prevActualWidth, actualWidth, prevViewWidth, viewWidth, drawableWidth); // // Height // float prevActualHeight = prevMatchViewHeight * normalizedScale; float actualHeight = getImageHeight(); translateMatrixAfterRotate(Matrix.MTRANS_Y, transY, prevActualHeight, actualHeight, prevViewHeight, viewHeight, drawableHeight); // // Set the matrix to the adjusted scale and translate values. // matrix.setValues(m); } fixTrans(); setImageMatrix(matrix); } /** * Set view dimensions based on layout params * * @param mode * @param size * @param drawableWidth * @return */ private int setViewSize(int mode, int size, int drawableWidth) { int viewSize; switch (mode) { case MeasureSpec.EXACTLY: viewSize = size; break; case MeasureSpec.AT_MOST: viewSize = Math.min(drawableWidth, size); break; case MeasureSpec.UNSPECIFIED: viewSize = drawableWidth; break; default: viewSize = size; break; } return viewSize; } /** * After rotating, the matrix needs to be translated. This function finds the area of image * which was previously centered and adjusts translations so that is again the center, post-rotation. * * @param axis Matrix.MTRANS_X or Matrix.MTRANS_Y * @param trans the value of trans in that axis before the rotation * @param prevImageSize the width/height of the image before the rotation * @param imageSize width/height of the image after rotation * @param prevViewSize width/height of view before rotation * @param viewSize width/height of view after rotation * @param drawableSize width/height of drawable */ private void translateMatrixAfterRotate(int axis, float trans, float prevImageSize, float imageSize, int prevViewSize, int viewSize, int drawableSize) { if (imageSize < viewSize) { // // The width/height of image is less than the view's width/height. Center it. // m[axis] = (viewSize - (drawableSize * m[Matrix.MSCALE_X])) * 0.5f; } else if (trans > 0) { // // The image is larger than the view, but was not before rotation. Center it. // m[axis] = -((imageSize - viewSize) * 0.5f); } else { // // Find the area of the image which was previously centered in the view. Determine its distance // from the left/top side of the view as a fraction of the entire image's width/height. Use that percentage // to calculate the trans in the new view width/height. // float percentage = (Math.abs(trans) + (0.5f * prevViewSize)) / prevImageSize; m[axis] = -((percentage * imageSize) - (viewSize * 0.5f)); } } private void setState(State state) { this.state = state; } public boolean canScrollHorizontallyFroyo(int direction) { return canScrollHorizontally(direction); } @Override public boolean canScrollHorizontally(int direction) { matrix.getValues(m); float x = m[Matrix.MTRANS_X]; if (getImageWidth() < viewWidth) { return false; } else if (x >= -1 && direction < 0) { return false; } else if (Math.abs(x) + viewWidth + 1 >= getImageWidth() && direction > 0) { return false; } return true; } /** * Gesture Listener detects a single click or long click and passes that on * to the view's listener. * * @author Ortiz */ private class GestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapConfirmed(MotionEvent e) { if (doubleTapListener != null) { return doubleTapListener.onSingleTapConfirmed(e); } return performClick(); } @Override public void onLongPress(MotionEvent e) { performLongClick(); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (fling != null) { // // If a previous fling is still active, it should be cancelled so that two flings // are not run simultaenously. // fling.cancelFling(); } fling = new Fling((int) velocityX, (int) velocityY); compatPostOnAnimation(fling); return super.onFling(e1, e2, velocityX, velocityY); } @Override public boolean onDoubleTap(MotionEvent e) { boolean consumed = false; if (doubleTapListener != null) { consumed = doubleTapListener.onDoubleTap(e); } if (state == State.NONE) { float targetZoom = (normalizedScale == minScale) ? maxScale : minScale; DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom, e.getX(), e.getY(), false); compatPostOnAnimation(doubleTap); consumed = true; } return consumed; } @Override public boolean onDoubleTapEvent(MotionEvent e) { if (doubleTapListener != null) { return doubleTapListener.onDoubleTapEvent(e); } return false; } } public interface OnTouchImageViewListener { public void onMove(); } /** * Responsible for all touch events. Handles the heavy lifting of drag and also sends * touch events to Scale Detector and Gesture Detector. * * @author Ortiz */ private class PrivateOnTouchListener implements OnTouchListener { // // Remember last point position for dragging // private PointF last = new PointF(); @Override public boolean onTouch(View v, MotionEvent event) { mScaleDetector.onTouchEvent(event); mGestureDetector.onTouchEvent(event); PointF curr = new PointF(event.getX(), event.getY()); if (state == State.NONE || state == State.DRAG || state == State.FLING) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: last.set(curr); if (fling != null) fling.cancelFling(); setState(State.DRAG); break; case MotionEvent.ACTION_MOVE: if (state == State.DRAG) { float deltaX = curr.x - last.x; float deltaY = curr.y - last.y; float fixTransX = getFixDragTrans(deltaX, viewWidth, getImageWidth()); float fixTransY = getFixDragTrans(deltaY, viewHeight, getImageHeight()); matrix.postTranslate(fixTransX, fixTransY); fixTrans(); last.set(curr.x, curr.y); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: setState(State.NONE); break; } } setImageMatrix(matrix); // // User-defined OnTouchListener // if (userTouchListener != null) { userTouchListener.onTouch(v, event); } // // OnTouchImageViewListener is set: TouchImageView dragged by user. // if (touchImageViewListener != null) { touchImageViewListener.onMove(); } // // indicate event was handled // return true; } } /** * ScaleListener detects user two finger scaling and scales image. * * @author Ortiz */ private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScaleBegin(ScaleGestureDetector detector) { setState(State.ZOOM); return true; } @Override public boolean onScale(ScaleGestureDetector detector) { scaleImage(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY(), true); // // OnTouchImageViewListener is set: TouchImageView pinch zoomed by user. // if (touchImageViewListener != null) { touchImageViewListener.onMove(); } return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { super.onScaleEnd(detector); setState(State.NONE); boolean animateToZoomBoundary = false; float targetZoom = normalizedScale; if (normalizedScale > maxScale) { targetZoom = maxScale; animateToZoomBoundary = true; } else if (normalizedScale < minScale) { targetZoom = minScale; animateToZoomBoundary = true; } if (animateToZoomBoundary) { DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom, viewWidth / 2, viewHeight / 2, true); compatPostOnAnimation(doubleTap); } } } private void scaleImage(double deltaScale, float focusX, float focusY, boolean stretchImageToSuper) { float lowerScale, upperScale; if (stretchImageToSuper) { lowerScale = superMinScale; upperScale = superMaxScale; } else { lowerScale = minScale; upperScale = maxScale; } float origScale = normalizedScale; normalizedScale *= deltaScale; if (normalizedScale > upperScale) { normalizedScale = upperScale; deltaScale = upperScale / origScale; } else if (normalizedScale < lowerScale) { normalizedScale = lowerScale; deltaScale = lowerScale / origScale; } matrix.postScale((float) deltaScale, (float) deltaScale, focusX, focusY); fixScaleTrans(); } /** * DoubleTapZoom calls a series of runnables which apply * an animated zoom in/out graphic to the image. * * @author Ortiz */ private class DoubleTapZoom implements Runnable { private long startTime; private static final float ZOOM_TIME = 500; private float startZoom, targetZoom; private float bitmapX, bitmapY; private boolean stretchImageToSuper; private AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator(); private PointF startTouch; private PointF endTouch; DoubleTapZoom(float targetZoom, float focusX, float focusY, boolean stretchImageToSuper) { setState(State.ANIMATE_ZOOM); startTime = System.currentTimeMillis(); this.startZoom = normalizedScale; this.targetZoom = targetZoom; this.stretchImageToSuper = stretchImageToSuper; PointF bitmapPoint = transformCoordTouchToBitmap(focusX, focusY, false); this.bitmapX = bitmapPoint.x; this.bitmapY = bitmapPoint.y; // // Used for translating image during scaling // startTouch = transformCoordBitmapToTouch(bitmapX, bitmapY); endTouch = new PointF(viewWidth / 2, viewHeight / 2); } @Override public void run() { float t = interpolate(); double deltaScale = calculateDeltaScale(t); scaleImage(deltaScale, bitmapX, bitmapY, stretchImageToSuper); translateImageToCenterTouchPosition(t); fixScaleTrans(); setImageMatrix(matrix); // // OnTouchImageViewListener is set: double tap runnable updates listener // with every frame. // if (touchImageViewListener != null) { touchImageViewListener.onMove(); } if (t < 1f) { // // We haven't finished zooming // compatPostOnAnimation(this); } else { // // Finished zooming // setState(State.NONE); } } /** * Interpolate between where the image should start and end in order to translate * the image so that the point that is touched is what ends up centered at the end * of the zoom. * * @param t */ private void translateImageToCenterTouchPosition(float t) { float targetX = startTouch.x + t * (endTouch.x - startTouch.x); float targetY = startTouch.y + t * (endTouch.y - startTouch.y); PointF curr = transformCoordBitmapToTouch(bitmapX, bitmapY); matrix.postTranslate(targetX - curr.x, targetY - curr.y); } /** * Use interpolator to get t * * @return */ private float interpolate() { long currTime = System.currentTimeMillis(); float elapsed = (currTime - startTime) / ZOOM_TIME; elapsed = Math.min(1f, elapsed); return interpolator.getInterpolation(elapsed); } /** * Interpolate the current targeted zoom and get the delta * from the current zoom. * * @param t * @return */ private double calculateDeltaScale(float t) { double zoom = startZoom + t * (targetZoom - startZoom); return zoom / normalizedScale; } } /** * This function will transform the coordinates in the touch event to the coordinate * system of the drawable that the imageview contain * * @param x x-coordinate of touch event * @param y y-coordinate of touch event * @param clipToBitmap Touch event may occur within view, but outside image content. True, to clip return value * to the bounds of the bitmap size. * @return Coordinates of the point touched, in the coordinate system of the original drawable. */ private PointF transformCoordTouchToBitmap(float x, float y, boolean clipToBitmap) { matrix.getValues(m); float origW = getDrawable().getIntrinsicWidth(); float origH = getDrawable().getIntrinsicHeight(); float transX = m[Matrix.MTRANS_X]; float transY = m[Matrix.MTRANS_Y]; float finalX = ((x - transX) * origW) / getImageWidth(); float finalY = ((y - transY) * origH) / getImageHeight(); if (clipToBitmap) { finalX = Math.min(Math.max(finalX, 0), origW); finalY = Math.min(Math.max(finalY, 0), origH); } return new PointF(finalX, finalY); } /** * Inverse of transformCoordTouchToBitmap. This function will transform the coordinates in the * drawable's coordinate system to the view's coordinate system. * * @param bx x-coordinate in original bitmap coordinate system * @param by y-coordinate in original bitmap coordinate system * @return Coordinates of the point in the view's coordinate system. */ private PointF transformCoordBitmapToTouch(float bx, float by) { matrix.getValues(m); float origW = getDrawable().getIntrinsicWidth(); float origH = getDrawable().getIntrinsicHeight(); float px = bx / origW; float py = by / origH; float finalX = m[Matrix.MTRANS_X] + getImageWidth() * px; float finalY = m[Matrix.MTRANS_Y] + getImageHeight() * py; return new PointF(finalX, finalY); } /** * Fling launches sequential runnables which apply * the fling graphic to the image. The values for the translation * are interpolated by the Scroller. * * @author Ortiz */ private class Fling implements Runnable { CompatScroller scroller; int currX, currY; Fling(int velocityX, int velocityY) { setState(State.FLING); scroller = new CompatScroller(context); matrix.getValues(m); int startX = (int) m[Matrix.MTRANS_X]; int startY = (int) m[Matrix.MTRANS_Y]; int minX, maxX, minY, maxY; if (getImageWidth() > viewWidth) { minX = viewWidth - (int) getImageWidth(); maxX = 0; } else { minX = maxX = startX; } if (getImageHeight() > viewHeight) { minY = viewHeight - (int) getImageHeight(); maxY = 0; } else { minY = maxY = startY; } scroller.fling(startX, startY, (int) velocityX, (int) velocityY, minX, maxX, minY, maxY); currX = startX; currY = startY; } public void cancelFling() { if (scroller != null) { setState(State.NONE); scroller.forceFinished(true); } } @Override public void run() { // // OnTouchImageViewListener is set: TouchImageView listener has been flung by user. // Listener runnable updated with each frame of fling animation. // if (touchImageViewListener != null) { touchImageViewListener.onMove(); } if (scroller.isFinished()) { scroller = null; return; } if (scroller.computeScrollOffset()) { int newX = scroller.getCurrX(); int newY = scroller.getCurrY(); int transX = newX - currX; int transY = newY - currY; currX = newX; currY = newY; matrix.postTranslate(transX, transY); fixTrans(); setImageMatrix(matrix); compatPostOnAnimation(this); } } } @TargetApi(VERSION_CODES.GINGERBREAD) private class CompatScroller { Scroller scroller; OverScroller overScroller; boolean isPreGingerbread; public CompatScroller(Context context) { if (VERSION.SDK_INT < VERSION_CODES.GINGERBREAD) { isPreGingerbread = true; scroller = new Scroller(context); } else { isPreGingerbread = false; overScroller = new OverScroller(context); } } public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY) { if (isPreGingerbread) { scroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY); } else { overScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY); } } public void forceFinished(boolean finished) { if (isPreGingerbread) { scroller.forceFinished(finished); } else { overScroller.forceFinished(finished); } } public boolean isFinished() { if (isPreGingerbread) { return scroller.isFinished(); } else { return overScroller.isFinished(); } } public boolean computeScrollOffset() { if (isPreGingerbread) { return scroller.computeScrollOffset(); } else { overScroller.computeScrollOffset(); return overScroller.computeScrollOffset(); } } public int getCurrX() { if (isPreGingerbread) { return scroller.getCurrX(); } else { return overScroller.getCurrX(); } } public int getCurrY() { if (isPreGingerbread) { return scroller.getCurrY(); } else { return overScroller.getCurrY(); } } } @TargetApi(VERSION_CODES.JELLY_BEAN) private void compatPostOnAnimation(Runnable runnable) { if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) { postOnAnimation(runnable); } else { postDelayed(runnable, 1000 / 60); } } private class ZoomVariables { public float scale; public float focusX; public float focusY; public ScaleType scaleType; public ZoomVariables(float scale, float focusX, float focusY, ScaleType scaleType) { this.scale = scale; this.focusX = focusX; this.focusY = focusY; this.scaleType = scaleType; } } private void printMatrixInfo() { float[] n = new float[9]; matrix.getValues(n); Log.d(DEBUG, "Scale: " + n[Matrix.MSCALE_X] + " TransX: " + n[Matrix.MTRANS_X] + " TransY: " + n[Matrix.MTRANS_Y]); } }
apache-2.0
YoungDigitalPlanet/empiria.player
src/main/java/eu/ydp/empiria/player/client/module/simulation/SimulationController.java
1724
/* * Copyright 2017 Young Digital Planet S.A. * * 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 eu.ydp.empiria.player.client.module.simulation; import com.google.gwt.core.client.JavaScriptObject; import com.google.inject.Inject; import com.google.inject.Singleton; import eu.ydp.gwtutil.client.json.NativeMethodInvocator; @Singleton public class SimulationController { private static final String METHOD_NAME_RESUME_ANIMATION = "resumeAnimation"; private static final String METHOD_NAME_PAUSE_ANIMATION = "pauseAnimation"; private static final String METHOD_NAME_WINDOW_RESIZED = "onWindowResized"; @Inject private NativeMethodInvocator methodInvocator; public void pauseAnimation(JavaScriptObject context) { callMethod(context, METHOD_NAME_PAUSE_ANIMATION); } public void resumeAnimation(JavaScriptObject context) { callMethod(context, METHOD_NAME_RESUME_ANIMATION); } public void onWindowResized(JavaScriptObject context) { callMethod(context, METHOD_NAME_WINDOW_RESIZED); } private void callMethod(JavaScriptObject context, String methodName) { methodInvocator.callMethod(context, methodName); } }
apache-2.0
cyberdrcarr/guvnor
droolsjbpm-ide-common/src/test/java/org/drools/ide/common/server/util/ScenarioXMLPersistenceTest.java
11802
/* * Copyright 2010 JBoss 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 org.drools.ide.common.server.util; import org.drools.ide.common.client.modeldriven.testing.*; import org.junit.Test; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class ScenarioXMLPersistenceTest { @Test public void testToXML() { ScenarioXMLPersistence p = ScenarioXMLPersistence.getInstance(); Scenario sc = new Scenario(); String s = p.marshal(sc); assertNotNull(s); sc = getDemo(); s = p.marshal(sc); assertTrue(s.indexOf("<ruleName>Life unverse and everything</ruleName>") > 0); Scenario sc_ = p.unmarshal(s); assertEquals(sc.getGlobals().size(), sc_.getGlobals().size()); assertEquals(sc.getFixtures().size(), sc_.getFixtures().size()); assertTrue(s.indexOf("org.drools") == -1); //check we have aliased all } @Test public void testTrimUneededSection() { Scenario sc = getDemo(); Scenario orig = getDemo(); sc.getFixtures().add(new ExecutionTrace()); int origSize = orig.getFixtures().size(); assertEquals(origSize + 1, sc.getFixtures().size()); String xml = ScenarioXMLPersistence.getInstance().marshal(sc); Scenario sc_ = ScenarioXMLPersistence.getInstance().unmarshal(xml); assertEquals(origSize, sc_.getFixtures().size()); verifyFieldDataNamesAreNotNull(sc_); } @Test public void testLoadLegacyTestScenario() throws Exception { StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("testLoadLegacyTestScenario.xml"))); String text = null; while ((text = reader.readLine()) != null) { contents.append(text); } } catch (Exception e) { if (reader != null) { reader.close(); } throw new IllegalStateException("Error while reading file.", e); } Scenario scenario = ScenarioXMLPersistence.getInstance().unmarshal(contents.toString()); verifyFieldDataNamesAreNotNull(scenario); FactData factData = (FactData) scenario.getFixtures().get(0); assertTrue(factData.getFieldData().get(0) instanceof FieldData); FieldData fieldData = (FieldData) factData.getFieldData().get(0); assertEquals("42", fieldData.getValue()); assertEquals("age", fieldData.getName()); } @Test public void testLoadCollectionFieldTestScenario() throws Exception { StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("CollectionFieldTestScenario.xml"))); String text = null; while ((text = reader.readLine()) != null) { contents.append(text); } } catch (Exception e) { if (reader != null) { reader.close(); } throw new IllegalStateException("Error while reading file.", e); } Scenario scenario = ScenarioXMLPersistence.getInstance().unmarshal(contents.toString()); verifyFieldDataNamesAreNotNull(scenario); FactData factData = (FactData) scenario.getFixtures().get(0); assertTrue(factData.getFieldData().get(0) instanceof CollectionFieldData); } @Test public void testLoadCollectionLegacyFieldTestScenario() throws Exception { StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("CollectionLegacyFieldTestScenario.xml"))); String text = null; while ((text = reader.readLine()) != null) { contents.append(text); } } catch (Exception e) { if (reader != null) { reader.close(); } throw new IllegalStateException("Error while reading file.", e); } Scenario scenario = ScenarioXMLPersistence.getInstance().unmarshal(contents.toString()); verifyFieldDataNamesAreNotNull(scenario); FactData factData = (FactData) scenario.getFixtures().get(0); assertTrue(factData.getFieldData().get(0) instanceof CollectionFieldData); } @Test public void testLoadEvenOlderCollectionLegacyFieldTestScenario() throws Exception { StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("CollectionLegacyFieldTestScenario2.xml"))); String text = null; while ((text = reader.readLine()) != null) { contents.append(text); } } catch (Exception e) { if (reader != null) { reader.close(); } throw new IllegalStateException("Error while reading file.", e); } Scenario scenario = ScenarioXMLPersistence.getInstance().unmarshal(contents.toString()); verifyFieldDataNamesAreNotNull(scenario); FactData factData = (FactData) scenario.getFixtures().get(0); assertTrue(factData.getFieldData().get(0) instanceof CollectionFieldData); } @Test public void testLoadLegacyFieldDataTestScenario() throws Exception { StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("LegacyFieldDataTestScenario.xml"))); String text = null; while ((text = reader.readLine()) != null) { contents.append(text); } } catch (Exception e) { if (reader != null) { reader.close(); } throw new IllegalStateException("Error while reading file.", e); } Scenario scenario = ScenarioXMLPersistence.getInstance().unmarshal(contents.toString()); verifyFieldDataNamesAreNotNull(scenario); FactData factData = (FactData) scenario.getFixtures().get(0); assertTrue(factData.getFieldData().get(0) instanceof CollectionFieldData); CollectionFieldData collectionFieldData=(CollectionFieldData)factData.getFieldData().get(0); FieldData fieldData = collectionFieldData.getCollectionFieldList().get(0); assertEquals("ratingSummaries", fieldData.getName()); assertEquals("=c1",fieldData.getValue()); } @Test public void testLoadAssignedFactTestScenario() throws Exception { StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("testLoadAssignedFactTestScenario.xml"))); String text = null; while ((text = reader.readLine()) != null) { contents.append(text); } } catch (Exception e) { if (reader != null) { reader.close(); } throw new IllegalStateException("Error while reading file.", e); } Scenario scenario = ScenarioXMLPersistence.getInstance().unmarshal(contents.toString()); verifyFieldDataNamesAreNotNull(scenario); } @Test public void testNewScenario() { FactData d1 = new FactData("Driver", "d1", ls(new FieldData[]{new FieldData("age", "42"), new FieldData("name", "david")}), false); Scenario sc = new Scenario(); sc.getFixtures().add(d1); sc.getFixtures().add(new ExecutionTrace()); int size = sc.getFixtures().size(); String xml = ScenarioXMLPersistence.getInstance().marshal(sc); Scenario sc_ = ScenarioXMLPersistence.getInstance().unmarshal(xml); assertEquals(size, sc_.getFixtures().size()); sc = new Scenario(); sc.getFixtures().add(new ExecutionTrace()); xml = ScenarioXMLPersistence.getInstance().marshal(sc); sc_ = ScenarioXMLPersistence.getInstance().unmarshal(xml); assertEquals(1, sc_.getFixtures().size()); } private void verifyFieldDataNamesAreNotNull(Scenario sc) { for (Fixture fixture : sc.getFixtures()) { if (fixture instanceof FactData) { FactData factData = (FactData) fixture; for (Field field : factData.getFieldData()) { if (field instanceof FieldData) { FieldData fieldData = (FieldData) field; assertNotNull(fieldData.getName()); } } } } } private Scenario getDemo() { //Sample data FactData d1 = new FactData("Driver", "d1", ls(new FieldData[]{new FieldData("age", "42"), new FieldData("name", "david")}), false); FactData d2 = new FactData("Driver", "d2", ls(new FieldData[]{new FieldData("name", "michael")}), false); FactData d3 = new FactData("Driver", "d3", ls(new FieldData[]{new FieldData("name", "michael2")}), false); FactData d4 = new FactData("Accident", "a1", ls(new FieldData[]{new FieldData("name", "michael2")}), false); Scenario sc = new Scenario(); sc.getFixtures().add(d1); sc.getFixtures().add(d2); sc.getGlobals().add(d3); sc.getGlobals().add(d4); sc.getRules().add("rule1"); sc.getRules().add("rule2"); sc.getFixtures().add(new ExecutionTrace()); List fields = new ArrayList(); VerifyField vfl = new VerifyField("age", "42", "=="); vfl.setActualResult("43"); vfl.setSuccessResult(new Boolean(false)); vfl.setExplanation("Not cool jimmy."); fields.add(vfl); vfl = new VerifyField("name", "michael", "!="); vfl.setActualResult("bob"); vfl.setSuccessResult(new Boolean(true)); vfl.setExplanation("Yeah !"); fields.add(vfl); VerifyFact vf = new VerifyFact("d1", fields); sc.getFixtures().add(vf); VerifyRuleFired vf1 = new VerifyRuleFired("Life unverse and everything", new Integer(42), null); vf1.setActualResult(new Integer(42)); vf1.setSuccessResult(new Boolean(true)); vf1.setExplanation("All good here."); VerifyRuleFired vf2 = new VerifyRuleFired("Everything else", null, new Boolean(true)); vf2.setActualResult(new Integer(0)); vf2.setSuccessResult(new Boolean(false)); vf2.setExplanation("Not so good here."); sc.getFixtures().add(vf1); sc.getFixtures().add(vf2); return sc; } private List ls(FieldData[] fieldDatas) { List ls = new ArrayList(); for (int i = 0; i < fieldDatas.length; i++) { ls.add(fieldDatas[i]); } return ls; } }
apache-2.0
pbuda/intellij-pony
src/me/piotrbuda/intellij/pony/parser/PonyLexer.java
37091
/* The following code was generated by JFlex 1.4.3 on 7/6/16 10:16 AM */ package me.piotrbuda.intellij.pony.parser; import com.intellij.lexer.FlexLexer; import com.intellij.psi.tree.IElementType; import static me.piotrbuda.intellij.pony.psi.PonyTypes.*; import com.intellij.psi.TokenType; import static me.piotrbuda.intellij.pony.parser.PonyParserDefinition.*; /** * This class is a scanner generated by * <a href="http://www.jflex.de/">JFlex</a> 1.4.3 * on 7/6/16 10:16 AM from the specification file * <tt>/Volumes/Devel/intellij-pony/src/me/piotrbuda/intellij/pony/parser/pony.flex</tt> */ public class PonyLexer implements FlexLexer { /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int MLSTRING = 2; public static final int YYINITIAL = 0; /** * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l * at the beginning of a line * l is of the form l = 2*k, k a non negative integer */ private static final int ZZ_LEXSTATE[] = { 0, 0, 1, 1 }; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\11\7\1\3\1\1\1\0\1\3\1\2\16\7\4\0\1\3\1\36"+ "\1\41\1\0\1\7\1\31\1\50\1\7\1\52\1\55\1\31\1\31"+ "\1\61\1\31\1\5\1\32\12\4\1\54\1\60\1\33\1\35\1\34"+ "\1\44\1\43\32\7\1\53\1\0\1\56\1\0\1\6\1\0\1\20"+ "\1\37\1\21\1\27\1\13\1\17\1\40\1\47\1\14\1\51\1\46"+ "\1\24\1\22\1\15\1\26\1\12\1\7\1\16\1\25\1\10\1\42"+ "\1\23\1\45\1\30\1\11\1\7\1\0\1\57\2\0\41\7\2\0"+ "\4\7\4\0\1\7\2\0\1\7\7\0\1\7\4\0\1\7\5\0"+ "\27\7\1\0\37\7\1\0\u01ca\7\4\0\14\7\16\0\5\7\7\0"+ "\1\7\1\0\1\7\21\0\160\7\5\7\1\0\2\7\2\0\4\7"+ "\10\0\1\7\1\0\3\7\1\0\1\7\1\0\24\7\1\0\123\7"+ "\1\0\213\7\1\0\5\7\2\0\236\7\11\0\46\7\2\0\1\7"+ "\7\0\47\7\7\0\1\7\1\0\55\7\1\0\1\7\1\0\2\7"+ "\1\0\2\7\1\0\1\7\10\0\33\7\5\0\3\7\15\0\5\7"+ "\6\0\1\7\4\0\13\7\5\0\53\7\25\7\12\4\4\0\2\7"+ "\1\7\143\7\1\0\1\7\10\7\1\0\6\7\2\7\2\7\1\0"+ "\4\7\2\7\12\4\3\7\2\0\1\7\17\0\1\7\1\7\1\7"+ "\36\7\33\7\2\0\131\7\13\7\1\7\16\0\12\4\41\7\11\7"+ "\2\7\4\0\1\7\5\0\26\7\4\7\1\7\11\7\1\7\3\7"+ "\1\7\5\7\22\0\31\7\3\7\104\0\1\7\1\0\13\7\67\0"+ "\33\7\1\0\4\7\66\7\3\7\1\7\22\7\1\7\7\7\12\7"+ "\2\7\2\0\12\4\1\0\7\7\1\0\7\7\1\0\3\7\1\0"+ "\10\7\2\0\2\7\2\0\26\7\1\0\7\7\1\0\1\7\3\0"+ "\4\7\2\0\1\7\1\7\7\7\2\0\2\7\2\0\3\7\1\7"+ "\10\0\1\7\4\0\2\7\1\0\3\7\2\7\2\0\12\4\4\7"+ "\7\0\1\7\5\0\3\7\1\0\6\7\4\0\2\7\2\0\26\7"+ "\1\0\7\7\1\0\2\7\1\0\2\7\1\0\2\7\2\0\1\7"+ "\1\0\5\7\4\0\2\7\2\0\3\7\3\0\1\7\7\0\4\7"+ "\1\0\1\7\7\0\12\4\2\7\3\7\1\7\13\0\3\7\1\0"+ "\11\7\1\0\3\7\1\0\26\7\1\0\7\7\1\0\2\7\1\0"+ "\5\7\2\0\1\7\1\7\10\7\1\0\3\7\1\0\3\7\2\0"+ "\1\7\17\0\2\7\2\7\2\0\12\4\1\0\1\7\17\0\3\7"+ "\1\0\10\7\2\0\2\7\2\0\26\7\1\0\7\7\1\0\2\7"+ "\1\0\5\7\2\0\1\7\1\7\7\7\2\0\2\7\2\0\3\7"+ "\10\0\2\7\4\0\2\7\1\0\3\7\2\7\2\0\12\4\1\0"+ "\1\7\20\0\1\7\1\7\1\0\6\7\3\0\3\7\1\0\4\7"+ "\3\0\2\7\1\0\1\7\1\0\2\7\3\0\2\7\3\0\3\7"+ "\3\0\14\7\4\0\5\7\3\0\3\7\1\0\4\7\2\0\1\7"+ "\6\0\1\7\16\0\12\4\11\0\1\7\7\0\3\7\1\0\10\7"+ "\1\0\3\7\1\0\27\7\1\0\12\7\1\0\5\7\3\0\1\7"+ "\7\7\1\0\3\7\1\0\4\7\7\0\2\7\1\0\2\7\6\0"+ "\2\7\2\7\2\0\12\4\22\0\2\7\1\0\10\7\1\0\3\7"+ "\1\0\27\7\1\0\12\7\1\0\5\7\2\0\1\7\1\7\7\7"+ "\1\0\3\7\1\0\4\7\7\0\2\7\7\0\1\7\1\0\2\7"+ "\2\7\2\0\12\4\1\0\2\7\17\0\2\7\1\0\10\7\1\0"+ "\3\7\1\0\51\7\2\0\1\7\7\7\1\0\3\7\1\0\4\7"+ "\1\7\10\0\1\7\10\0\2\7\2\7\2\0\12\4\12\0\6\7"+ "\2\0\2\7\1\0\22\7\3\0\30\7\1\0\11\7\1\0\1\7"+ "\2\0\7\7\3\0\1\7\4\0\6\7\1\0\1\7\1\0\10\7"+ "\22\0\2\7\15\0\60\7\1\7\2\7\7\7\4\0\10\7\10\7"+ "\1\0\12\4\47\0\2\7\1\0\1\7\2\0\2\7\1\0\1\7"+ "\2\0\1\7\6\0\4\7\1\0\7\7\1\0\3\7\1\0\1\7"+ "\1\0\1\7\2\0\2\7\1\0\4\7\1\7\2\7\6\7\1\0"+ "\2\7\1\7\2\0\5\7\1\0\1\7\1\0\6\7\2\0\12\4"+ "\2\0\4\7\40\0\1\7\27\0\2\7\6\0\12\4\13\0\1\7"+ "\1\0\1\7\1\0\1\7\4\0\2\7\10\7\1\0\44\7\4\0"+ "\24\7\1\0\2\7\5\7\13\7\1\0\44\7\11\0\1\7\71\0"+ "\53\7\24\7\1\7\12\4\6\0\6\7\4\7\4\7\3\7\1\7"+ "\3\7\2\7\7\7\3\7\4\7\15\7\14\7\1\7\1\7\12\4"+ "\4\7\2\0\46\7\1\0\1\7\5\0\1\7\2\0\53\7\1\0"+ "\u014d\7\1\0\4\7\2\0\7\7\1\0\1\7\1\0\4\7\2\0"+ "\51\7\1\0\4\7\2\0\41\7\1\0\4\7\2\0\7\7\1\0"+ "\1\7\1\0\4\7\2\0\17\7\1\0\71\7\1\0\4\7\2\0"+ "\103\7\2\0\3\7\40\0\20\7\20\0\125\7\14\0\u026c\7\2\0"+ "\21\7\1\0\32\7\5\0\113\7\3\0\3\7\17\0\15\7\1\0"+ "\4\7\3\7\13\0\22\7\3\7\13\0\22\7\2\7\14\0\15\7"+ "\1\0\3\7\1\0\2\7\14\0\64\7\40\7\3\0\1\7\3\0"+ "\2\7\1\7\2\0\12\4\41\0\3\7\2\0\12\4\6\0\130\7"+ "\10\0\51\7\1\7\1\7\5\0\106\7\12\0\35\7\3\0\14\7"+ "\4\0\14\7\12\0\12\4\36\7\2\0\5\7\13\0\54\7\4\0"+ "\21\7\7\7\2\7\6\0\12\4\46\0\27\7\5\7\4\0\65\7"+ "\12\7\1\0\35\7\2\0\1\7\12\4\6\0\12\4\15\0\1\7"+ "\130\0\5\7\57\7\21\7\7\7\4\0\12\4\21\0\11\7\14\0"+ "\3\7\36\7\15\7\2\7\12\4\54\7\16\7\14\0\44\7\24\7"+ "\10\0\12\4\3\0\3\7\12\4\44\7\122\0\3\7\1\0\25\7"+ "\4\7\1\7\4\7\3\7\2\7\11\0\300\7\47\7\25\0\4\7"+ "\u0116\7\2\0\6\7\2\0\46\7\2\0\6\7\2\0\10\7\1\0"+ "\1\7\1\0\1\7\1\0\1\7\1\0\37\7\2\0\65\7\1\0"+ "\7\7\1\0\1\7\3\0\3\7\1\0\7\7\3\0\4\7\2\0"+ "\6\7\4\0\15\7\5\0\3\7\1\0\7\7\16\0\5\7\32\0"+ "\5\7\20\0\2\7\23\0\1\7\13\0\5\7\5\0\6\7\1\0"+ "\1\7\15\0\1\7\20\0\15\7\3\0\33\7\25\0\15\7\4\0"+ "\1\7\3\0\14\7\21\0\1\7\4\0\1\7\2\0\12\7\1\0"+ "\1\7\3\0\5\7\6\0\1\7\1\0\1\7\1\0\1\7\1\0"+ "\4\7\1\0\13\7\2\0\4\7\5\0\5\7\4\0\1\7\21\0"+ "\51\7\u0a77\0\57\7\1\0\57\7\1\0\205\7\6\0\4\7\3\7"+ "\2\7\14\0\46\7\1\0\1\7\5\0\1\7\2\0\70\7\7\0"+ "\1\7\17\0\1\7\27\7\11\0\7\7\1\0\7\7\1\0\7\7"+ "\1\0\7\7\1\0\7\7\1\0\7\7\1\0\7\7\1\0\7\7"+ "\1\0\40\7\57\0\1\7\u01d5\0\3\7\31\0\11\7\6\7\1\0"+ "\5\7\2\0\5\7\4\0\126\7\2\0\2\7\2\0\3\7\1\0"+ "\132\7\1\0\4\7\5\0\51\7\3\0\136\7\21\0\33\7\65\0"+ "\20\7\u0200\0\u19b6\7\112\0\u51cd\7\63\0\u048d\7\103\0\56\7\2\0"+ "\u010d\7\3\0\20\7\12\4\2\7\24\0\57\7\1\7\4\0\12\7"+ "\1\0\31\7\7\0\1\7\120\7\2\7\45\0\11\7\2\0\147\7"+ "\2\0\4\7\1\0\4\7\14\0\13\7\115\0\12\7\1\7\3\7"+ "\1\7\4\7\1\7\27\7\5\7\20\0\1\7\7\0\64\7\14\0"+ "\2\7\62\7\21\7\13\0\12\4\6\0\22\7\6\7\3\0\1\7"+ "\4\0\12\4\34\7\10\7\2\0\27\7\15\7\14\0\35\7\3\0"+ "\4\7\57\7\16\7\16\0\1\7\12\4\46\0\51\7\16\7\11\0"+ "\3\7\1\7\10\7\2\7\2\0\12\4\6\0\27\7\3\0\1\7"+ "\1\7\4\0\60\7\1\7\1\7\3\7\2\7\2\7\5\7\2\7"+ "\1\7\1\7\1\7\30\0\3\7\2\0\13\7\5\7\2\0\3\7"+ "\2\7\12\0\6\7\2\0\6\7\2\0\6\7\11\0\7\7\1\0"+ "\7\7\221\0\43\7\10\7\1\0\2\7\2\0\12\4\6\0\u2ba4\7"+ "\14\0\27\7\4\0\61\7\u2104\0\u016e\7\2\0\152\7\46\0\7\7"+ "\14\0\5\7\5\0\1\7\1\7\12\7\1\0\15\7\1\0\5\7"+ "\1\0\1\7\1\0\2\7\1\0\2\7\1\0\154\7\41\0\u016b\7"+ "\22\0\100\7\2\0\66\7\50\0\15\7\3\0\20\7\20\0\7\7"+ "\14\0\2\7\30\0\3\7\31\0\1\7\6\0\5\7\1\0\207\7"+ "\2\0\1\7\4\0\1\7\13\0\12\4\7\0\32\7\4\0\1\7"+ "\1\0\32\7\13\0\131\7\3\0\6\7\2\0\6\7\2\0\6\7"+ "\2\0\3\7\3\0\2\7\3\0\2\7\22\0\3\7\4\0"; /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\1\1\1\2\1\3\1\4\1\5\1\6\20\1\4\7"+ "\1\10\1\3\1\1\1\3\1\1\1\11\1\12\1\1"+ "\1\13\1\14\1\15\1\16\1\17\1\20\1\21\1\22"+ "\1\23\1\2\1\24\1\1\1\25\10\1\1\26\1\27"+ "\1\30\10\1\1\31\6\1\1\30\1\1\1\32\1\1"+ "\1\0\1\33\1\34\2\1\1\0\1\35\4\1\1\0"+ "\1\1\1\36\1\37\3\1\1\40\5\1\1\41\3\1"+ "\1\42\5\1\1\43\1\44\2\1\2\45\1\1\1\35"+ "\1\46\1\1\1\47\3\1\1\50\1\51\1\1\1\52"+ "\2\1\1\53\17\1\1\54\3\1\1\55\11\1\1\56"+ "\2\1\1\57\1\60\1\61\1\62\1\1\1\63\2\1"+ "\1\64\1\65\4\1\1\66\1\67\3\1\1\70\1\1"+ "\1\71\2\1\1\72\3\1\1\73\10\1\1\74"; private static int [] zzUnpackAction() { int [] result = new int[202]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\62\0\144\0\226\0\310\0\372\0\u012c\0\u015e"+ "\0\u0190\0\u01c2\0\u01f4\0\u0226\0\u0258\0\u028a\0\u02bc\0\u02ee"+ "\0\u0320\0\u0352\0\u0384\0\u03b6\0\u03e8\0\u041a\0\144\0\u044c"+ "\0\u047e\0\u04b0\0\u04e2\0\u0514\0\u0546\0\u0578\0\u05aa\0\144"+ "\0\144\0\u05dc\0\144\0\144\0\144\0\144\0\144\0\144"+ "\0\144\0\144\0\144\0\u060e\0\u0640\0\310\0\372\0\u0672"+ "\0\u06a4\0\u06d6\0\u0708\0\u073a\0\u076c\0\u079e\0\u07d0\0\u0802"+ "\0\u012c\0\u0834\0\u0866\0\u0898\0\u08ca\0\u08fc\0\u092e\0\u0960"+ "\0\u0992\0\u09c4\0\u012c\0\u09f6\0\u0a28\0\u0a5a\0\u0a8c\0\u0abe"+ "\0\u0af0\0\u012c\0\u0b22\0\u012c\0\u0b54\0\u0b86\0\144\0\u012c"+ "\0\u0bb8\0\u0bea\0\u0c1c\0\u0c4e\0\u0c80\0\u0cb2\0\u0ce4\0\u0d16"+ "\0\u0d48\0\u0d7a\0\u012c\0\u012c\0\u0dac\0\u0dde\0\u0e10\0\u012c"+ "\0\u0e42\0\u0e74\0\u0ea6\0\u0ed8\0\u0f0a\0\u012c\0\u0f3c\0\u0f6e"+ "\0\u0fa0\0\u012c\0\u0fd2\0\u1004\0\u1036\0\u1068\0\u109a\0\u012c"+ "\0\u012c\0\u10cc\0\u10fe\0\144\0\u0b86\0\u1130\0\u0c1c\0\u0c1c"+ "\0\u1162\0\u012c\0\u1194\0\u11c6\0\u11f8\0\144\0\u012c\0\u122a"+ "\0\u012c\0\u125c\0\u128e\0\u12c0\0\u12f2\0\u1324\0\u1356\0\u1388"+ "\0\u13ba\0\u13ec\0\u141e\0\u1450\0\u1482\0\u14b4\0\u14e6\0\u1518"+ "\0\u154a\0\u157c\0\u15ae\0\u012c\0\u15e0\0\u1612\0\u1644\0\u012c"+ "\0\u1676\0\u16a8\0\u16da\0\u170c\0\u173e\0\u1770\0\u17a2\0\u17d4"+ "\0\u1806\0\u012c\0\u1838\0\u186a\0\u012c\0\u012c\0\u012c\0\u012c"+ "\0\u189c\0\u012c\0\u18ce\0\u1900\0\u012c\0\u012c\0\u1932\0\u1964"+ "\0\u1996\0\u19c8\0\u012c\0\u012c\0\u19fa\0\u1a2c\0\u1a5e\0\u012c"+ "\0\u1a90\0\u012c\0\u1ac2\0\u1af4\0\u012c\0\u1b26\0\u1b58\0\u1b8a"+ "\0\u012c\0\u1bbc\0\u1bee\0\u1c20\0\u1c52\0\u1c84\0\u1cb6\0\u1ce8"+ "\0\u1d1a\0\u012c"; private static int [] zzUnpackRowMap() { int [] result = new int[202]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\1\3\3\4\1\5\1\6\2\7\1\10\1\7\1\11"+ "\1\12\1\13\1\14\1\15\1\16\1\17\1\20\1\21"+ "\1\22\1\23\1\7\1\24\1\25\1\26\1\27\1\30"+ "\1\31\1\32\1\33\1\34\1\35\1\7\1\36\1\37"+ "\1\40\1\41\1\42\2\7\1\43\1\7\1\44\1\45"+ "\1\46\1\47\1\50\1\51\1\52\1\53\41\54\1\55"+ "\20\54\63\0\3\4\62\0\1\56\1\57\23\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\57\61\0\1\7\1\0\23\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\3\7\1\60\4\7\1\61\1\7\1\62\10\7\6\0"+ "\2\7\1\0\1\7\2\0\2\7\1\63\1\0\1\7"+ "\14\0\1\7\1\0\10\7\1\64\12\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\7\7\1\65\1\66\5\7\1\67\4\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\7\7\1\70\1\7\1\71\5\7\1\72"+ "\1\7\1\73\1\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\5\7\1\74"+ "\12\7\1\75\2\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\5\7\1\76"+ "\15\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\20\7\1\77\2\7\6\0"+ "\2\7\1\0\1\100\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\7\7\1\101\3\7\1\102\3\7\1\103"+ "\3\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\16\7\1\104\1\7\1\105"+ "\2\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\12\7\1\106\10\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\12\7\1\107\10\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\5\7\1\110\4\7\1\111\10\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\10\7\1\112\12\7\6\0\1\113\1\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\20\7"+ "\1\114\2\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\20\7\1\115\2\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\42\0\1\116\62\0\1\27\1\0\1\27\60\0\2\27"+ "\60\0\1\117\1\27\61\0\1\27\30\0\1\7\1\0"+ "\5\7\1\120\2\7\1\121\7\7\1\122\2\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\10\0"+ "\1\123\1\0\37\123\1\124\20\123\4\0\1\7\1\0"+ "\7\7\1\125\7\7\1\126\3\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\6\7\1\127\14\7\6\0\2\7\1\0\1\7\2\0"+ "\2\7\1\130\1\0\1\7\10\0\41\54\1\0\20\54"+ "\41\0\1\131\24\0\1\7\1\0\4\7\1\132\16\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\3\7\1\133\3\7\1\134\2\7"+ "\1\135\10\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\23\7\6\0\1\7"+ "\1\134\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\5\7\1\136\15\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\6\7\1\137\14\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\21\7\1\140"+ "\1\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\10\7\1\141\12\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\17\7\1\142\3\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\2\7\1\143\20\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\7\7\1\144"+ "\10\7\1\134\2\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\5\7\1\145"+ "\15\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\23\7\6\0\2\7\1\0"+ "\1\7\2\0\1\120\2\7\1\0\1\7\14\0\1\7"+ "\1\0\2\7\1\146\20\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\2\7"+ "\1\147\1\7\1\150\4\7\1\134\1\7\1\151\7\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\10\7\1\152\12\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\7\7\1\120\13\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\21\7"+ "\1\112\1\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\2\7\1\153\20\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\12\7\1\154\10\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\7\7\1\155\4\7\1\156\6\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\2\7\1\157\20\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\10\7"+ "\1\160\5\7\1\134\4\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\2\7"+ "\1\161\20\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\14\7\1\162\6\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\23\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\163\14\0\1\7\1\0\10\7"+ "\1\112\12\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\10\0\1\116\1\164\1\165\57\116\4\0"+ "\1\7\1\0\5\7\1\166\15\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\22\7\1\134\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\10\0\1\123\1\0\37\123\1\167\21\123"+ "\1\0\37\123\1\170\20\123\4\0\1\7\1\0\2\7"+ "\1\171\20\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\5\7\1\172\15\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\2\7\1\173\20\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\5\7\1\174\1\175\14\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\51\0\1\176\24\0"+ "\1\7\1\0\5\7\1\177\15\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\6\7\1\200\14\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\7\7\1\201"+ "\13\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\14\7\1\202\6\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\20\7\1\203\2\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\5\7\1\204\15\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\5\7\1\205"+ "\15\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\2\7\1\112\20\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\7\7\1\206\13\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\23\7\6\0\2\7\1\0\1\207\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\5\7\1\210\15\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\20\7\1\211\2\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\20\7\1\212\2\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\17\7\1\213"+ "\3\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\2\7\1\214\14\7\1\215"+ "\3\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\4\7\1\216\16\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\13\7\1\217\7\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\23\7\6\0\1\220\1\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\5\7\1\221\15\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\12\7\1\222\10\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\6\7\1\223\14\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\23\7"+ "\6\0\2\7\1\0\1\7\2\0\2\7\1\224\1\0"+ "\1\7\14\0\1\7\1\0\10\7\1\225\12\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\16\7\1\226\4\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\2\7\1\177\20\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\6\7\1\227"+ "\14\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\10\7\1\230\12\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\6\7\1\231\14\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\10\7\1\232\12\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\2\7\1\233"+ "\20\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\10\7\1\234\12\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\12\7\1\235\10\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\15\7\1\236\5\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\10\7\1\177"+ "\12\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\17\7\1\177\3\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\6\7\1\237\14\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\23\7\6\0\2\7\1\0\1\240\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\6\7\1\241\14\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\23\7\6\0\2\7\1\0\1\7\2\0"+ "\2\7\1\242\1\0\1\7\14\0\1\7\1\0\21\7"+ "\1\243\1\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\13\7\1\244\7\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\23\7\6\0\2\7\1\0\1\7"+ "\2\0\1\7\1\245\1\7\1\0\1\7\14\0\1\7"+ "\1\0\16\7\1\246\4\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\5\7"+ "\1\247\15\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\5\7\1\250\15\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\2\7\1\251\20\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\11\7\1\252\11\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\11\7"+ "\1\253\11\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\6\7\1\254\14\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\7\7\1\255\13\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\2\7\1\256\20\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\5\7"+ "\1\257\15\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\7\7\1\260\13\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\14\7\1\261\6\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\16\7\1\262\4\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\12\7"+ "\1\263\10\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\2\7\1\264\20\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\6\7\1\265\14\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\12\7\1\266\10\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\2\7"+ "\1\267\20\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\10\7\1\270\12\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\23\7\6\0\2\7\1\0\1\271"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\5\7"+ "\1\272\15\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\5\7\1\273\15\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\15\7\1\132\5\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\13\7\1\132\7\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\3\7"+ "\1\274\17\7\6\0\2\7\1\0\1\7\2\0\3\7"+ "\1\0\1\7\14\0\1\7\1\0\5\7\1\275\15\7"+ "\6\0\2\7\1\0\1\7\2\0\3\7\1\0\1\7"+ "\14\0\1\7\1\0\10\7\1\276\12\7\6\0\2\7"+ "\1\0\1\7\2\0\3\7\1\0\1\7\14\0\1\7"+ "\1\0\20\7\1\277\2\7\6\0\2\7\1\0\1\7"+ "\2\0\3\7\1\0\1\7\14\0\1\7\1\0\1\300"+ "\22\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\11\7\1\301\11\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\6\7\1\302\14\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\7\7\1\303\13\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\2\7\1\304"+ "\20\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\10\7\1\305\12\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\6\7\1\306\14\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\14\0\1\7\1\0"+ "\7\7\1\307\13\7\6\0\2\7\1\0\1\7\2\0"+ "\3\7\1\0\1\7\14\0\1\7\1\0\17\7\1\310"+ "\3\7\6\0\2\7\1\0\1\7\2\0\3\7\1\0"+ "\1\7\14\0\1\7\1\0\6\7\1\311\14\7\6\0"+ "\2\7\1\0\1\7\2\0\3\7\1\0\1\7\14\0"+ "\1\7\1\0\13\7\1\312\7\7\6\0\2\7\1\0"+ "\1\7\2\0\3\7\1\0\1\7\10\0"; private static int [] zzUnpackTrans() { int [] result = new int[7500]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int zzUnpackTrans(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); value--; do result[j++] = value; while (--count > 0); } return j; } /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; private static final char[] EMPTY_BUFFER = new char[0]; private static final int YYEOF = -1; private static java.io.Reader zzReader = null; // Fake /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\2\1\1\11\23\1\1\11\10\1\2\11\1\1\11\11"+ "\42\1\1\0\1\11\3\1\1\0\5\1\1\0\32\1"+ "\1\11\11\1\1\11\114\1"; private static int [] zzUnpackAttribute() { int [] result = new int[202]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private CharSequence zzBuffer = ""; /** this buffer may contains the current text array to be matched when it is cheap to acquire it */ private char[] zzBufferArray; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the textposition at the last state to be included in yytext */ private int zzPushbackPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /** denotes if the user-EOF-code has already been executed */ private boolean zzEOFDone; /* user code: */ public PonyLexer() { this((java.io.Reader)null); } /** * Creates a new scanner * * @param in the java.io.Reader to read input from. */ public PonyLexer(java.io.Reader in) { this.zzReader = in; } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { char [] map = new char[0x10000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < 2258) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } public final int getTokenStart(){ return zzStartRead; } public final int getTokenEnd(){ return getTokenStart() + yylength(); } public void reset(CharSequence buffer, int start, int end,int initialState){ zzBuffer = buffer; zzBufferArray = com.intellij.util.text.CharArrayUtil.fromSequenceWithoutCopying(buffer); zzCurrentPos = zzMarkedPos = zzStartRead = start; zzPushbackPos = 0; zzAtEOF = false; zzAtBOL = true; zzEndRead = end; yybegin(initialState); } /** * Refills the input buffer. * * @return <code>false</code>, iff there was new input. * * @exception java.io.IOException if any I/O-Error occurs */ private boolean zzRefill() throws java.io.IOException { return true; } /** * Returns the current lexical state. */ public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final CharSequence yytext() { return zzBuffer.subSequence(zzStartRead, zzMarkedPos); } /** * Returns the character at position <tt>pos</tt> from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBufferArray != null ? zzBufferArray[zzStartRead+pos]:zzBuffer.charAt(zzStartRead+pos); } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Contains user EOF-code, which will be executed exactly once, * when the end of file is reached */ private void zzDoEOF() { if (!zzEOFDone) { zzEOFDone = true; return; } } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ public IElementType advance() throws java.io.IOException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; CharSequence zzBufferL = zzBuffer; char[] zzBufferArrayL = zzBufferArray; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) zzInput = (zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++)); else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = (zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++)); } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 27: { return BEGIN_RAWSEQ; } case 61: break; case 26: { return PONY_DO; } case 62: break; case 50: { return PONY_WHILE; } case 63: break; case 53: { return PONY_REPEAT; } case 64: break; case 10: { return PONY_QUESTION; } case 65: break; case 25: { return PONY_AS; } case 66: break; case 17: { return PONY_UNION; } case 67: break; case 45: { return PONY_ERROR; } case 68: break; case 47: { return PONY_BREAK; } case 69: break; case 20: { throw new Error("Illegal character <"+yytext()+">"); } case 70: break; case 60: { return PONY_COMPILER; } case 71: break; case 16: { return RSQUARE; } case 72: break; case 57: { return PONY_CONSUME; } case 73: break; case 33: { return PONY_NOT; } case 74: break; case 44: { return PONY_WITH; } case 75: break; case 8: { return PONY_EQUALS; } case 76: break; case 6: { return DOT; } case 77: break; case 59: { return PONY_IDENTITYOF; } case 78: break; case 46: { return PONY_MATCH; } case 79: break; case 12: { return LPAREN_NEW; } case 80: break; case 18: { return PONY_SEMICOLON; } case 81: break; case 23: { return PONY_IF; } case 82: break; case 13: { return LSQUARE_NEW; } case 83: break; case 54: { return PONY_LAMBDA; } case 84: break; case 42: { return PONY_THEN; } case 85: break; case 51: { return PONY_ELSEIF; } case 86: break; case 58: { return PONY_CONTINUE; } case 87: break; case 41: { return PONY_CLASS_DEF; } case 88: break; case 43: { return PONY_ELSE; } case 89: break; case 14: { return BEGIN_TYPE; } case 90: break; case 5: { return INT; } case 91: break; case 52: { return PONY_RETURN; } case 92: break; case 39: { return PONY_USE; } case 93: break; case 36: { return PONY_LET; } case 94: break; case 37: { return LINE_COMMENT; } case 95: break; case 34: { return PONY_FOR; } case 96: break; case 1: { return ID; } case 97: break; case 21: { return FLOAT; } case 98: break; case 49: { return PONY_WHERE; } case 99: break; case 30: { return PONY_TRY; } case 100: break; case 38: { yybegin(MLSTRING); return ML_STRING; } case 101: break; case 24: { return BINOP; } case 102: break; case 19: { return PONY_COLON; } case 103: break; case 7: { return PONY_OPERATOR; } case 104: break; case 9: { return PONY_AT; } case 105: break; case 22: { return PONY_IN; } case 106: break; case 29: { return STRING; } case 107: break; case 35: { return PONY_VAR; } case 108: break; case 28: { return PONY_METHOD; } case 109: break; case 4: { return com.intellij.psi.TokenType.WHITE_SPACE; } case 110: break; case 11: { return PONY_AMPERSAND; } case 111: break; case 15: { return RPAREN; } case 112: break; case 31: { return CAP; } case 113: break; case 32: { return PONY_END; } case 114: break; case 56: { return PONY_RECOVER; } case 115: break; case 40: { yybegin(YYINITIAL); return ML_STRING; } case 116: break; case 2: { return ML_STRING_CONTENT; } case 117: break; case 55: { return PONY_OBJECT; } case 118: break; case 3: { return com.intellij.psi.TokenType.BAD_CHARACTER; } case 119: break; case 48: { return PONY_UNTIL; } case 120: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; zzDoEOF(); return null; } else { zzScanError(ZZ_NO_MATCH); } } } } }
apache-2.0
glenacota/seine
seine-src/src/experiment/effort/noseine/gossiplive/StreamingInit.java
7050
package experiment.effort.noseine.gossiplive; import peersim.config.Configuration; import peersim.core.Control; import peersim.core.Network; /** * This {@link Control} initialises the actors operating in the gossip protocol, namely, * the video source and the peers. * * Assumption: a cycle lasts 1 second. * * @author Guido Lena Cota */ public class StreamingInit implements Control { /** * The number of {@link Chunk}s sent every 1 second of video streaming. * Considering that the default value of FPS is 30, then the default number of chunks-per-second is 30. */ public static final byte CPS = 30; /** * The bits of video that can be transmitted in a second, in bps. * The default value is taken from the YouTube recommandations for upload encoding which can be found * here: https://support.google.com/youtube/answer/1722171 , https://support.google.com/youtube/answer/2853702 . * The recommended video bit rate for a video with resolution 480 p (854x480) is between 500 Kbps and 2000 Kbps. * Default value: 2 Mbps. * (value in "Stretching Gossip with Live Streaming": 600 Kbps) */ public static final int BITRATE = 674000; /** * The size of a video chunk, in bytes. * As in "Experimental comparison of neighborhood filtering strategies in unstructured P2P-TV systems" * by Traverso et al., we assume that a video chunk corresponds to a singe video frame. * The CHUNK_SIZE value can be thus derived from the {@link BITRATE} and {@link FPS} values. */ public static final int CHUNK_SIZE = BITRATE / CPS / 8; /** * The overhead of the message header, in bits. (16 bits of UDP + 160 bits of IPv4) */ public static final int MESSAGE_HEADER_OVERHEAD = 176 / 8; // PARAMETERS in the PEERSIM CONFIGURATION FILE // ------------------------------------------------------------------------------------------------ /** * The protocol to operate on. */ private static final String PAR_PROTOCOL = "protocol"; /** * The playback deadline, i.e., the maximum allowed time (in cycles) between the creation of a * video chunk and its playback. Chunks received after their playback deadline are discarded. */ private static final String PAR_DEADLINE = "deadline"; /** * The fraction of peers in the network that are directly connected with the video source. */ private static final String PAR_SOURCE_FANOUT = "fanout_source"; /** * The number of communication partners. */ private final String PAR_FANOUT = "fanout"; /** * The period (in seconds) between two updates of the communication partners. */ private static final String PAR_PROACTIVENESS = "proactiveness"; /** * The period (in seconds) between two updates of the source's communication partners. */ private static final String PAR_PROACTIVENESS_SOURCE = "proactiveness_source"; /** * The per-cycle upload bandwidth capacity of the video source, in bits. * The default value [18 Mbps] is taken from the average upload speed of the fastest ISPs * published on www.speedtest.net/awards . */ private static final String PAR_UPLOAD_SOURCE = "upload_source"; /** * The per-cycle upload bandwidth capacity of each peer, in bits. * The default value [5.97 Mbps] is the global average measured by Ookla NetIndex * (data published here http://goo.gl/4E2KsR ). * * Another possible reference value [5.56 Mbps] can be found in "MOLStream: A Modular * Rapid Development and Evaluation Framework for Live P2P Streaming" by Friedman et al. */ private static final String PAR_UPLOAD_PEER = "upload_peer"; // FIELDS // ------------------------------------------------------------------------------------------------ /** * The id of the protocol to operate on, as specified in {@link PAR_PROTOCOL}. */ private final int protocolId; /** * The fraction of the network connected with the source, as specified in {@link PAR_SOURCE_FANOUT}. * The default value is taken from "BAR Gossip" by Li et al. */ private double source_fanout; /** * The number of communication partners, as specified in {@link PAR_FANOUT}. * The default value is taken from "Probabilistic Reliable Dissemination in Large-Scale Systems" * by Kermarrec et al. */ private final int fanout; /** * The playback deadline of media {@link Chunk}s, as specified in {@link PAR_DEADLINE}. * The default value is taken from "Experimental comparison of neighborhood filtering strategies * in unstructured P2P-TV systems" by Traverso et al. */ public static byte deadline; /** * The partners period, as specified in {@link PAR_PROACTIVENESS}. */ private final int partnerPeriod; /** * The partners period of the source, as specified in {@link PAR_PROACTIVENESS_SOURCE}. */ private final int partnerPeriodSource; /** * The per-cycle upload bandwidth capacity of the source, as specified in {@link PAR_UPLOAD_SOURCE}. */ private final long sourceUploadBandwidth; /** * The per-cycle upload bandwidth capacity of each peer, as specified in {@link PAR_UPLOAD_PEER}. */ private final long peerUploadBandwidth; /** * The source. */ public static GossipLive sourceNode; // SUPPORT_CONSTANT private static final double FANOUT_CORRECTION = 0.0047; // INITIALIZATION // ------------------------------------------------------------------------------------------------ public StreamingInit(String prefix) { protocolId = Configuration.getPid(prefix + "." + PAR_PROTOCOL); deadline = (byte) Configuration.getInt(prefix + "." + PAR_DEADLINE, 6); source_fanout = Configuration.getDouble(prefix + "." + PAR_SOURCE_FANOUT, 0.1); source_fanout += Math.log(deadline) * FANOUT_CORRECTION; int defaultFanout = (int) (Math.round(Math.log(Network.size()) * 1.2)); fanout = Configuration.getInt(prefix + "." + PAR_FANOUT, defaultFanout); partnerPeriod = Configuration.getInt(prefix + "." + PAR_PROACTIVENESS, 5); peerUploadBandwidth = Configuration.getLong(prefix + "." + PAR_UPLOAD_PEER, 125000); // 695000 partnerPeriodSource = Configuration.getInt(prefix + "." + PAR_PROACTIVENESS_SOURCE, partnerPeriod); sourceUploadBandwidth = Configuration.getLong(prefix + "." + PAR_UPLOAD_SOURCE, 2250000); } // THE EXECUTE METHOD // ------------------------------------------------------------------------------------------------ @Override public boolean execute() { // init the source node sourceNode = (GossipLive) Network.get(0).getProtocol(protocolId); // GossipLive.initialisePotentialPartnersSupports(); sourceNode.initialiseSource(deadline, sourceUploadBandwidth, partnerPeriodSource, source_fanout); sourceNode.selectSourcePartners(protocolId); // init the other peers int nwSize = Network.size(); // initialize the peers for(short i = 1 ; i < nwSize ; i++) { GossipLive peer = (GossipLive) Network.get(i).getProtocol(protocolId); peer.initialisePeer(deadline, peerUploadBandwidth, partnerPeriod, fanout); peer.selectPartners(protocolId); } return false; } }
apache-2.0