lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
apache-2.0
09aade9323a09ea6141f12b95e9f3dac16b477db
0
haku/Onosendai,haku/Onosendai
package com.vaguehope.onosendai.model; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import com.vaguehope.onosendai.config.InlineMediaStyle; import com.vaguehope.onosendai.images.ImageLoader; import com.vaguehope.onosendai.storage.TweetCursorReader; public class TweetListCursorAdapter extends CursorAdapter { private final InlineMediaStyle inlineMediaStyle; private final ImageLoader imageLoader; private final LinkedTweetLoader tweetLoader; private final View listView; private final LayoutInflater layoutInflater; private final TweetCursorReader cursorReader = new TweetCursorReader(); private final TweetListViewState tweetListViewState = new TweetListViewState(); public TweetListCursorAdapter (final Context context, final InlineMediaStyle inlineMediaStyle, final ImageLoader imageLoader, final LinkedTweetLoader tweetLoader, final View listView) { super(context, null, false); // Initialise with no cursor. this.inlineMediaStyle = inlineMediaStyle; this.imageLoader = imageLoader; this.tweetLoader = tweetLoader; this.listView = listView; this.layoutInflater = LayoutInflater.from(context); } public void dispose () { changeCursor(null); } public String getItemSid (final int position) { return this.cursorReader.readSid((Cursor) getItem(position)); } public long getItemTime (final int position) { if (getCount() < 1) return -1; return this.cursorReader.readTime((Cursor) getItem(position)); } @Override public int getViewTypeCount () { return TweetLayout.values().length; } @Override public int getItemViewType (final int position) { return tweetLayoutType((Cursor) getItem(position)).getIndex(); } @Override public View newView (final Context context, final Cursor cursor, final ViewGroup parent) { final TweetLayout layoutType = tweetLayoutType(cursor); final View view = this.layoutInflater.inflate(layoutType.getLayout(), null); final TweetRowView rowView = layoutType.makeRowView(view, this.tweetListViewState); view.setTag(rowView); return view; } @Override public void bindView (final View view, final Context context, final Cursor cursor) { final TweetLayout layoutType = tweetLayoutType(cursor); final TweetRowView rowView = (TweetRowView) view.getTag(); layoutType.applyCursorTo(cursor, this.cursorReader, rowView, this.imageLoader, this.listView.getWidth(), this.tweetLoader); } private TweetLayout tweetLayoutType (final Cursor c) { switch (this.inlineMediaStyle) { case NONE: // TODO inline quote without media? return TweetLayout.MAIN; case INLINE: if (this.cursorReader.readFiltered(c)) return TweetLayout.MAIN; if (this.cursorReader.readQuotedSid(c) != null) return TweetLayout.QUOTED; return this.cursorReader.readInlineMedia(c) != null ? TweetLayout.INLINE_MEDIA : TweetLayout.MAIN; case SEAMLESS: return this.cursorReader.readInlineMedia(c) != null ? TweetLayout.SEAMLESS_MEDIA : TweetLayout.MAIN; default: return TweetLayout.MAIN; } } }
src/main/java/com/vaguehope/onosendai/model/TweetListCursorAdapter.java
package com.vaguehope.onosendai.model; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import com.vaguehope.onosendai.config.InlineMediaStyle; import com.vaguehope.onosendai.images.ImageLoader; import com.vaguehope.onosendai.storage.TweetCursorReader; public class TweetListCursorAdapter extends CursorAdapter { private final InlineMediaStyle inlineMediaStyle; private final ImageLoader imageLoader; private final LinkedTweetLoader tweetLoader; private final View listView; private final LayoutInflater layoutInflater; private final TweetCursorReader cursorReader = new TweetCursorReader(); private final TweetListViewState tweetListViewState = new TweetListViewState(); public TweetListCursorAdapter (final Context context, final InlineMediaStyle inlineMediaStyle, final ImageLoader imageLoader, final LinkedTweetLoader tweetLoader, final View listView) { super(context, null, false); // Initialise with no cursor. this.inlineMediaStyle = inlineMediaStyle; this.imageLoader = imageLoader; this.tweetLoader = tweetLoader; this.listView = listView; this.layoutInflater = LayoutInflater.from(context); } public void dispose () { changeCursor(null); } public String getItemSid (final int position) { return this.cursorReader.readSid((Cursor) getItem(position)); } public long getItemTime (final int position) { if (getCount() < 1) return -1; return this.cursorReader.readTime((Cursor) getItem(position)); } @Override public int getViewTypeCount () { return TweetLayout.values().length; } @Override public int getItemViewType (final int position) { return tweetLayoutType((Cursor) getItem(position)).getIndex(); } @Override public View newView (final Context context, final Cursor cursor, final ViewGroup parent) { final TweetLayout layoutType = tweetLayoutType(cursor); final View view = this.layoutInflater.inflate(layoutType.getLayout(), null); final TweetRowView rowView = layoutType.makeRowView(view, this.tweetListViewState); view.setTag(rowView); return view; } @Override public void bindView (final View view, final Context context, final Cursor cursor) { final TweetLayout layoutType = tweetLayoutType(cursor); final TweetRowView rowView = (TweetRowView) view.getTag(); layoutType.applyCursorTo(cursor, this.cursorReader, rowView, this.imageLoader, this.listView.getWidth(), this.tweetLoader); } private TweetLayout tweetLayoutType (final Cursor c) { switch (this.inlineMediaStyle) { case NONE: // TODO inline quote without media? return TweetLayout.MAIN; case INLINE: if (this.cursorReader.readQuotedSid(c) != null) return TweetLayout.QUOTED; return this.cursorReader.readInlineMedia(c) != null && !this.cursorReader.readFiltered(c) ? TweetLayout.INLINE_MEDIA : TweetLayout.MAIN; case SEAMLESS: return this.cursorReader.readInlineMedia(c) != null ? TweetLayout.SEAMLESS_MEDIA : TweetLayout.MAIN; default: return TweetLayout.MAIN; } } }
Do not show quoted tweet for a filtered tweet.
src/main/java/com/vaguehope/onosendai/model/TweetListCursorAdapter.java
Do not show quoted tweet for a filtered tweet.
Java
apache-2.0
003e9ae2c330da318090d02b229569ec5518ed51
0
MrRaindrop/incubator-weex,erha19/incubator-weex,cxfeng1/incubator-weex,MrRaindrop/incubator-weex,KalicyZhou/incubator-weex,MrRaindrop/incubator-weex,miomin/incubator-weex,KalicyZhou/incubator-weex,leoward/incubator-weex,Hanks10100/incubator-weex,MrRaindrop/incubator-weex,dianwodaMobile/DWeex,dianwodaMobile/DWeex,Hanks10100/incubator-weex,KalicyZhou/incubator-weex,erha19/incubator-weex,cxfeng1/incubator-weex,erha19/incubator-weex,weexteam/incubator-weex,miomin/incubator-weex,weexteam/incubator-weex,dianwodaMobile/DWeex,yuguitao/incubator-weex,alibaba/weex,alibaba/weex,Hanks10100/incubator-weex,alibaba/weex,weexteam/incubator-weex,yuguitao/incubator-weex,leoward/incubator-weex,Hanks10100/incubator-weex,cxfeng1/incubator-weex,weexteam/incubator-weex,cxfeng1/incubator-weex,Hanks10100/incubator-weex,alibaba/weex,yuguitao/incubator-weex,leoward/incubator-weex,cxfeng1/incubator-weex,alibaba/weex,xiayun200825/weex,KalicyZhou/incubator-weex,leoward/incubator-weex,miomin/incubator-weex,yuguitao/incubator-weex,erha19/incubator-weex,xiayun200825/weex,miomin/incubator-weex,leoward/incubator-weex,KalicyZhou/incubator-weex,alibaba/weex,acton393/incubator-weex,erha19/incubator-weex,MrRaindrop/incubator-weex,acton393/incubator-weex,cxfeng1/incubator-weex,erha19/incubator-weex,yuguitao/incubator-weex,KalicyZhou/incubator-weex,acton393/incubator-weex,acton393/incubator-weex,acton393/incubator-weex,xiayun200825/weex,MrRaindrop/incubator-weex,miomin/incubator-weex,erha19/incubator-weex,Hanks10100/incubator-weex,weexteam/incubator-weex,leoward/incubator-weex,acton393/incubator-weex,xiayun200825/weex,acton393/incubator-weex,alibaba/weex,dianwodaMobile/DWeex,dianwodaMobile/DWeex,weexteam/incubator-weex,erha19/incubator-weex,miomin/incubator-weex,Hanks10100/incubator-weex,xiayun200825/weex,miomin/incubator-weex,acton393/incubator-weex,xiayun200825/weex,yuguitao/incubator-weex,miomin/incubator-weex,dianwodaMobile/DWeex,Hanks10100/incubator-weex
/** * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * 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.taobao.weex.ui.view; import android.annotation.SuppressLint; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.Interpolator; import com.taobao.weex.ui.view.gesture.WXGesture; import com.taobao.weex.ui.view.gesture.WXGestureObservable; import com.taobao.weex.utils.WXLogUtils; import java.lang.ref.WeakReference; import java.lang.reflect.Field; /** */ @SuppressLint("HandlerLeak") public class WXCircleViewPager extends ViewPager implements WXGestureObservable { private WXGesture wxGesture; private boolean isAutoScroll; private long intervalTime = 3 * 1000; private WXSmoothScroller mScroller; private boolean needLoop = true; private boolean scrollable = true; private int mState = ViewPager.SCROLL_STATE_IDLE; private Runnable scrollAction = new ScrollAction(this, intervalTime); @SuppressLint("NewApi") public WXCircleViewPager(Context context) { super(context); init(); } private void init() { setOverScrollMode(View.OVER_SCROLL_NEVER); addOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { mState = state; WXCirclePageAdapter adapter = getCirclePageAdapter(); int currentItemInternal = WXCircleViewPager.super.getCurrentItem(); if (needLoop && state == ViewPager.SCROLL_STATE_IDLE && adapter.getCount() > 1) { if (currentItemInternal == adapter.getCount() - 1) { superSetCurrentItem(1, false); } else if (currentItemInternal == 0) { superSetCurrentItem(adapter.getCount() - 2, false); } } } }); postInitViewPager(); } /** * Override the Scroller instance with our own class so we can change the * duration */ private void postInitViewPager() { if (isInEditMode()) { return; } try { Field scroller = ViewPager.class.getDeclaredField("mScroller"); scroller.setAccessible(true); Field interpolator = ViewPager.class .getDeclaredField("sInterpolator"); interpolator.setAccessible(true); mScroller = new WXSmoothScroller(getContext(), (Interpolator) interpolator.get(null)); scroller.set(this, mScroller); } catch (Exception e) { WXLogUtils.e("[CircleViewPager] postInitViewPager: ", e); } } @SuppressLint("NewApi") public WXCircleViewPager(Context context, AttributeSet attrs) { super(context, attrs); init(); } @Override public int getCurrentItem() { return getRealCurrentItem(); } public int superGetCurrentItem() { return super.getCurrentItem(); } @Override public boolean onTouchEvent(MotionEvent ev) { if(!scrollable) { return true; } boolean result = super.onTouchEvent(ev); if (wxGesture != null) { result |= wxGesture.onTouch(this, ev); } return result; } @Override public void scrollTo(int x, int y) { if(scrollable || mState != ViewPager.SCROLL_STATE_DRAGGING) { super.scrollTo(x, y); } } /** * Start auto scroll. Must be called after {@link #setAdapter(PagerAdapter)} */ public void startAutoScroll() { isAutoScroll = true; removeCallbacks(scrollAction); postDelayed(scrollAction, intervalTime); } public void pauseAutoScroll(){ removeCallbacks(scrollAction); } /** * Stop auto scroll. */ public void stopAutoScroll() { isAutoScroll = false; removeCallbacks(scrollAction); } public boolean isAutoScroll() { return isAutoScroll; } @Override public void setCurrentItem(int item) { setRealCurrentItem(item); } /** * @return the circlePageAdapter */ public WXCirclePageAdapter getCirclePageAdapter() { return (WXCirclePageAdapter) getAdapter(); } /** * @param circlePageAdapter the circlePageAdapter to set */ public void setCirclePageAdapter(WXCirclePageAdapter circlePageAdapter) { this.setAdapter(circlePageAdapter); } /** * Get auto scroll interval. The time unit is micro second. * The default time interval is 3000 micro second * @return the intervalTime */ public long getIntervalTime() { return intervalTime; } /** * Set auto scroll interval. The time unit is micro second. * The default time interval is 3000 micro second * @param intervalTime the intervalTime to set */ public void setIntervalTime(long intervalTime) { this.intervalTime = intervalTime; } public void setCircle(boolean circle) { needLoop = circle; } @Override public boolean dispatchTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: removeCallbacks(scrollAction); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: if (isAutoScroll()) { postDelayed(scrollAction, intervalTime); } break; } return super.dispatchTouchEvent(ev); } public void destory() { } @Override public void registerGestureListener(WXGesture wxGesture) { this.wxGesture = wxGesture; } public int getRealCurrentItem() { int i = super.getCurrentItem(); return ((WXCirclePageAdapter) getAdapter()).getRealPosition(i); } private void setRealCurrentItem(int item) { superSetCurrentItem(((WXCirclePageAdapter) getAdapter()).getFirst() + item, false); } private void superSetCurrentItem(int item, boolean smooth) { try { super.setCurrentItem(item, smooth); } catch (IllegalStateException e) { WXLogUtils.e(e.toString()); if (getAdapter() != null) { getAdapter().notifyDataSetChanged(); super.setCurrentItem(item, smooth); } } } public int getRealCount() { return ((WXCirclePageAdapter) getAdapter()).getRealCount(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { try { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } catch (IllegalStateException e) { WXLogUtils.e(e.toString()); if (getAdapter() != null) { getAdapter().notifyDataSetChanged(); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } } public boolean isScrollable() { return scrollable; } public void setScrollable(boolean scrollable) { this.scrollable = scrollable; } private void showNextItem() { if (!needLoop && superGetCurrentItem() == getRealCount() - 1) { return; } if (getRealCount() == 2 && superGetCurrentItem() == 1) { superSetCurrentItem(0, true); } else { superSetCurrentItem(superGetCurrentItem() + 1, true); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); removeCallbacks(scrollAction); } private static final class ScrollAction implements Runnable { private WeakReference<WXCircleViewPager> targetRef; private long intervalTime; private ScrollAction(WXCircleViewPager target, long intervalTime) { this.targetRef = new WeakReference<>(target); this.intervalTime = intervalTime; } @Override public void run() { WXLogUtils.d("[CircleViewPager] trigger auto play action"); WXCircleViewPager target; if ((target = targetRef.get()) != null) { target.showNextItem(); target.removeCallbacks(this); target.postDelayed(this, intervalTime); } } } }
android/sdk/src/main/java/com/taobao/weex/ui/view/WXCircleViewPager.java
/** * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * 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.taobao.weex.ui.view; import android.annotation.SuppressLint; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.Interpolator; import com.taobao.weex.ui.view.gesture.WXGesture; import com.taobao.weex.ui.view.gesture.WXGestureObservable; import com.taobao.weex.utils.WXLogUtils; import java.lang.ref.WeakReference; import java.lang.reflect.Field; /** */ @SuppressLint("HandlerLeak") public class WXCircleViewPager extends ViewPager implements WXGestureObservable { private WXGesture wxGesture; private boolean isAutoScroll; private long intervalTime = 3 * 1000; private WXSmoothScroller mScroller; private boolean needLoop = true; private boolean scrollable = true; private int mState = ViewPager.SCROLL_STATE_IDLE; private Runnable scrollAction = new ScrollAction(this, intervalTime); @SuppressLint("NewApi") public WXCircleViewPager(Context context) { super(context); init(); } private void init() { setOverScrollMode(View.OVER_SCROLL_NEVER); addOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { mState = state; WXCirclePageAdapter adapter = getCirclePageAdapter(); int currentItemInternal = WXCircleViewPager.super.getCurrentItem(); if (needLoop && state == ViewPager.SCROLL_STATE_IDLE && adapter.getCount() > 1) { if (currentItemInternal == adapter.getCount() - 1) { superSetCurrentItem(1, false); } else if (currentItemInternal == 0) { superSetCurrentItem(adapter.getCount() - 2, false); } } } }); postInitViewPager(); } /** * Override the Scroller instance with our own class so we can change the * duration */ private void postInitViewPager() { if (isInEditMode()) { return; } try { Field scroller = ViewPager.class.getDeclaredField("mScroller"); scroller.setAccessible(true); Field interpolator = ViewPager.class .getDeclaredField("sInterpolator"); interpolator.setAccessible(true); mScroller = new WXSmoothScroller(getContext(), (Interpolator) interpolator.get(null)); scroller.set(this, mScroller); } catch (Exception e) { WXLogUtils.e("[CircleViewPager] postInitViewPager: ", e); } } @SuppressLint("NewApi") public WXCircleViewPager(Context context, AttributeSet attrs) { super(context, attrs); init(); } @Override public int getCurrentItem() { return getRealCurrentItem(); } public int superGetCurrentItem() { return super.getCurrentItem(); } @Override public boolean onTouchEvent(MotionEvent ev) { if(!scrollable) { return true; } boolean result = super.onTouchEvent(ev); if (wxGesture != null) { result |= wxGesture.onTouch(this, ev); } return result; } @Override public void scrollTo(int x, int y) { if(scrollable || mState != ViewPager.SCROLL_STATE_DRAGGING) { super.scrollTo(x, y); } } /** * Start auto scroll. Must be called after {@link #setAdapter(PagerAdapter)} */ public void startAutoScroll() { isAutoScroll = true; removeCallbacks(scrollAction); postDelayed(scrollAction, intervalTime); } public void pauseAutoScroll(){ removeCallbacks(scrollAction); } /** * Stop auto scroll. */ public void stopAutoScroll() { isAutoScroll = false; removeCallbacks(scrollAction); } public boolean isAutoScroll() { return isAutoScroll; } @Override public void setCurrentItem(int item) { setRealCurrentItem(item); } /** * @return the circlePageAdapter */ public WXCirclePageAdapter getCirclePageAdapter() { return (WXCirclePageAdapter) getAdapter(); } /** * @param circlePageAdapter the circlePageAdapter to set */ public void setCirclePageAdapter(WXCirclePageAdapter circlePageAdapter) { this.setAdapter(circlePageAdapter); } /** * Get auto scroll interval. The time unit is micro second. * The default time interval is 3000 micro second * @return the intervalTime */ public long getIntervalTime() { return intervalTime; } /** * Set auto scroll interval. The time unit is micro second. * The default time interval is 3000 micro second * @param intervalTime the intervalTime to set */ public void setIntervalTime(long intervalTime) { this.intervalTime = intervalTime; } public void setCircle(boolean circle) { needLoop = circle; } @Override public boolean dispatchTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: removeCallbacks(scrollAction); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: if (isAutoScroll()) { postDelayed(scrollAction, intervalTime); } break; } return super.dispatchTouchEvent(ev); } public void destory() { } @Override public void registerGestureListener(WXGesture wxGesture) { this.wxGesture = wxGesture; } public int getRealCurrentItem() { int i = super.getCurrentItem(); return ((WXCirclePageAdapter) getAdapter()).getRealPosition(i); } private void setRealCurrentItem(int item) { superSetCurrentItem(((WXCirclePageAdapter) getAdapter()).getFirst() + item, false); } private void superSetCurrentItem(int item, boolean smooth) { try { super.setCurrentItem(item, smooth); } catch (IllegalStateException e) { WXLogUtils.e(e.toString()); if (getAdapter() != null) { getAdapter().notifyDataSetChanged(); super.setCurrentItem(item, smooth); } } } public int getRealCount() { return ((WXCirclePageAdapter) getAdapter()).getRealCount(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { try { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } catch (IllegalStateException e) { WXLogUtils.e(e.toString()); if (getAdapter() != null) { getAdapter().notifyDataSetChanged(); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } } public boolean isScrollable() { return scrollable; } public void setScrollable(boolean scrollable) { this.scrollable = scrollable; } private void showNextItem() { if (getRealCount() == 2 && superGetCurrentItem() == 1) { superSetCurrentItem(0, true); } else { superSetCurrentItem(superGetCurrentItem() + 1, true); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); removeCallbacks(scrollAction); } private static final class ScrollAction implements Runnable { private WeakReference<WXCircleViewPager> targetRef; private long intervalTime; private ScrollAction(WXCircleViewPager target, long intervalTime) { this.targetRef = new WeakReference<>(target); this.intervalTime = intervalTime; } @Override public void run() { WXLogUtils.d("[CircleViewPager] trigger auto play action"); WXCircleViewPager target; if ((target = targetRef.get()) != null) { target.showNextItem(); target.removeCallbacks(this); target.postDelayed(this, intervalTime); } } } }
* [android] disable auto scroll on not infinite
android/sdk/src/main/java/com/taobao/weex/ui/view/WXCircleViewPager.java
* [android] disable auto scroll on not infinite
Java
apache-2.0
60650f1bb64eaa0e196365fec762488113254ad8
0
mikosik/smooth-build,mikosik/smooth-build
package org.smoothbuild.io.fs.base; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.fail; import static org.smoothbuild.io.fs.base.Path.path; import static org.smoothbuild.io.fs.base.RecursivePathsIterator.recursivePathsIterator; import static org.smoothbuild.testing.common.AssertCall.assertCall; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import org.smoothbuild.io.fs.mem.MemoryFileSystem; import okio.BufferedSink; import okio.ByteString; public class RecursivePathsIteratorTest { @Test public void test() throws IOException { doTestIterable("abc", "1.txt", "2.txt", "3.txt", "def/4.txt", "def/5.txt", "ghi/6.txt"); doTestIterable("abc/xyz", "1.txt", "2.txt", "3.txt", "def/4.txt", "def/5.txt", "ghi/6.txt"); doTestIterable("abc/xyz/prs", "1.txt", "2.txt", "3.txt", "def/4.txt", "def/5.txt", "ghi/6.txt"); } private void doTestIterable(String rootDir, String... names) throws IOException { doTestIterable(rootDir, names, rootDir, names); } @Test public void iterates_subdirectory() throws Exception { doTestIterable( "abc", new String[] {"1.txt", "2.txt", "3.txt", "def/4.txt", "def/5.txt", "ghi/6.txt"}, "abc/def", new String[] {"4.txt", "5.txt"}); } @Test public void is_empty_when_dir_doesnt_exist() throws Exception { FileSystem fileSystem = new MemoryFileSystem(); Path path = path("my/file"); assertThat(recursivePathsIterator(fileSystem, path).hasNext()) .isFalse(); } @Test public void throws_exception_when_dir_is_a_file() throws Exception { FileSystem fileSystem = new MemoryFileSystem(); try (BufferedSink sink = fileSystem.sink(path("my/file"))) { sink.write(ByteString.encodeUtf8("abc")); } try { recursivePathsIterator(fileSystem, path("my/file")); fail("exception should be thrown"); } catch (IllegalArgumentException e) { // expected } } @Test public void throws_exception_when_dir_disappears_during_iteration() throws Exception { FileSystem fileSystem = new MemoryFileSystem(); createFiles(fileSystem, "dir", "1.txt", "2.txt", "subdir/somefile"); PathIterator iterator = recursivePathsIterator(fileSystem, path("dir")); iterator.next(); fileSystem.delete(path("dir/subdir")); assertCall(iterator::next).throwsException(new IOException( "FileSystem changed when iterating tree of directory 'dir'. Cannot find 'dir/subdir'.")); } private void doTestIterable(String rootDir, String[] names, String expectedRootDir, String[] expectedNames) throws IOException { FileSystem fileSystem = new MemoryFileSystem(); createFiles(fileSystem, rootDir, names); PathIterator iterator = recursivePathsIterator(fileSystem, path(expectedRootDir)); List<String> created = new ArrayList<>(); while (iterator.hasNext()) { created.add(iterator.next().value()); } assertThat(created) .containsExactly(expectedNames); } private void createFiles(FileSystem fileSystem, String rootDir, String... names) throws IOException { for (String name : names) { Path path = path(rootDir).append(path(name)); fileSystem.sink(path).close(); } } }
src/main/test/org/smoothbuild/io/fs/base/RecursivePathsIteratorTest.java
package org.smoothbuild.io.fs.base; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.smoothbuild.io.fs.base.Path.path; import static org.smoothbuild.io.fs.base.RecursivePathsIterator.recursivePathsIterator; import static org.smoothbuild.testing.common.AssertCall.assertCall; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import org.smoothbuild.io.fs.mem.MemoryFileSystem; import okio.BufferedSink; import okio.ByteString; public class RecursivePathsIteratorTest { @Test public void test() throws IOException { doTestIterable("abc", "1.txt", "2.txt", "3.txt", "def/4.txt", "def/5.txt", "ghi/6.txt"); doTestIterable("abc/xyz", "1.txt", "2.txt", "3.txt", "def/4.txt", "def/5.txt", "ghi/6.txt"); doTestIterable("abc/xyz/prs", "1.txt", "2.txt", "3.txt", "def/4.txt", "def/5.txt", "ghi/6.txt"); } private void doTestIterable(String rootDir, String... names) throws IOException { doTestIterable(rootDir, names, rootDir, names); } @Test public void iterates_subdirectory() throws Exception { doTestIterable( "abc", new String[] {"1.txt", "2.txt", "3.txt", "def/4.txt", "def/5.txt", "ghi/6.txt"}, "abc/def", new String[] {"4.txt", "5.txt"}); } @Test public void is_empty_when_dir_doesnt_exist() throws Exception { FileSystem fileSystem = new MemoryFileSystem(); Path path = path("my/file"); assertFalse(recursivePathsIterator(fileSystem, path).hasNext()); } @Test public void throws_exception_when_dir_is_a_file() throws Exception { FileSystem fileSystem = new MemoryFileSystem(); try (BufferedSink sink = fileSystem.sink(path("my/file"))) { sink.write(ByteString.encodeUtf8("abc")); } try { recursivePathsIterator(fileSystem, path("my/file")); fail("exception should be thrown"); } catch (IllegalArgumentException e) { // expected } } @Test public void throws_exception_when_dir_disappears_during_iteration() throws Exception { FileSystem fileSystem = new MemoryFileSystem(); createFiles(fileSystem, "dir", "1.txt", "2.txt", "subdir/somefile"); PathIterator iterator = recursivePathsIterator(fileSystem, path("dir")); iterator.next(); fileSystem.delete(path("dir/subdir")); assertCall(iterator::next).throwsException(new IOException( "FileSystem changed when iterating tree of directory 'dir'. Cannot find 'dir/subdir'.")); } private void doTestIterable(String rootDir, String[] names, String expectedRootDir, String[] expectedNames) throws IOException { FileSystem fileSystem = new MemoryFileSystem(); createFiles(fileSystem, rootDir, names); PathIterator iterator = recursivePathsIterator(fileSystem, path(expectedRootDir)); List<String> created = new ArrayList<>(); while (iterator.hasNext()) { created.add(iterator.next().value()); } assertThat(created, containsInAnyOrder(expectedNames)); } private void createFiles(FileSystem fileSystem, String rootDir, String... names) throws IOException { for (String name : names) { Path path = path(rootDir).append(path(name)); fileSystem.sink(path).close(); } } }
refactored RecursivePathsIteratorTest to use Truth framework
src/main/test/org/smoothbuild/io/fs/base/RecursivePathsIteratorTest.java
refactored RecursivePathsIteratorTest to use Truth framework
Java
apache-2.0
61cdca636c49cc2d5edfeaa5d14e40f0cf8b24d8
0
yeastrc/proxl-web-app,yeastrc/proxl-web-app,yeastrc/proxl-web-app
package org.yeastrc.proxl.import_xml_to_db.db; import java.sql.Connection; import java.util.HashMap; import java.util.Map; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.yeastrc.xlink.db.DBConnectionFactory; import org.yeastrc.xlink.db.IDBConnectionFactory; /** * Singleton * */ public class ImportDBConnectionFactory implements IDBConnectionFactory { private static Logger log = Logger.getLogger(ImportDBConnectionFactory.class); private static final String _DEFAULT_PORT = "3306"; private static final int COMMIT_AFTER_500_INSERTS = 500; // Singleton private static final ImportDBConnectionFactory _INSTANCE = new ImportDBConnectionFactory(); // private constructor private ImportDBConnectionFactory() { } public static ImportDBConnectionFactory getInstance() { return _INSTANCE; } private Map<String, BasicDataSource> _dataSources = null; private Connection _insertControlCommitConnection = null; private int _insertControlCommitConnectionGetCount = 0; private IDBConnectionParametersProvider dbConnectionParametersProvider = null; /** * Allow setting a value for dbConnectionParametersProvider * * @param dbConnectionParametersProvider */ public void setDbConnectionParametersProvider( IDBConnectionParametersProvider dbConnectionParametersProvider) { this.dbConnectionParametersProvider = dbConnectionParametersProvider; if ( StringUtils.isNotEmpty( dbConnectionParametersProvider.getProxlDbName() ) ) { System.out.println( "Proxl DB Name from Connection Provider: " + dbConnectionParametersProvider.getProxlDbName() ); log.info( "Proxl DB Name from Connection Provider: " + dbConnectionParametersProvider.getProxlDbName() ); } if ( StringUtils.isNotEmpty( dbConnectionParametersProvider.getNrseqDbName() ) ) { System.out.println( "YRC_NRSEQ DB Name from Connection Provider: " + dbConnectionParametersProvider.getNrseqDbName() ); log.info( "YRC_NRSEQ DB Name from Connection Provider: " + dbConnectionParametersProvider.getNrseqDbName() ); } } /** * @return * @throws Exception */ public Connection getInsertControlCommitConnection() throws Exception { if ( _insertControlCommitConnection == null ) { _insertControlCommitConnection = getConnection( DBConnectionFactory.PROXL ); _insertControlCommitConnection.setAutoCommit(false); _insertControlCommitConnectionGetCount = 0; } _insertControlCommitConnectionGetCount++; if ( _insertControlCommitConnectionGetCount > COMMIT_AFTER_500_INSERTS ) { _insertControlCommitConnection.commit(); _insertControlCommitConnectionGetCount = 0; } return _insertControlCommitConnection; } /** * call commit() on the insert connection and return the connection to the pool * @throws Exception */ public void commitInsertControlCommitConnection() throws Exception { if ( _insertControlCommitConnection == null ) { return; } _insertControlCommitConnection.commit(); _insertControlCommitConnection.close(); // Return connection to pool _insertControlCommitConnection = null; } // get a connection to the requested database @Override public Connection getConnection( String db ) throws Exception { if ( dbConnectionParametersProvider == null ) { dbConnectionParametersProvider = new DBConnectionParametersProviderFromPropertiesFile(); dbConnectionParametersProvider.init(); if ( StringUtils.isNotEmpty( dbConnectionParametersProvider.getProxlDbName() ) ) { System.out.println( "Proxl DB Name from Connection Provider: " + dbConnectionParametersProvider.getProxlDbName() ); log.info( "Proxl DB Name from Connection Provider: " + dbConnectionParametersProvider.getProxlDbName() ); } if ( StringUtils.isNotEmpty( dbConnectionParametersProvider.getNrseqDbName() ) ) { System.out.println( "YRC_NRSEQ DB Name from Connection Provider: " + dbConnectionParametersProvider.getNrseqDbName() ); log.info( "YRC_NRSEQ DB Name from Connection Provider: " + dbConnectionParametersProvider.getNrseqDbName() ); } } // Allow change of database if ( DBConnectionFactory.PROXL.equals(db) ) { if ( StringUtils.isNotEmpty( dbConnectionParametersProvider.getProxlDbName() ) ) { db = dbConnectionParametersProvider.getProxlDbName(); } } if( _dataSources == null ) { _dataSources = new HashMap<String, BasicDataSource>(); Class.forName("com.mysql.jdbc.Driver"); } BasicDataSource dataSource = _dataSources.get( db ); if ( dataSource == null ) { // create datasource for this db name String username = dbConnectionParametersProvider.getUsername(); String password = dbConnectionParametersProvider.getPassword(); String dbURL = dbConnectionParametersProvider.getDBURL(); String dbPort = dbConnectionParametersProvider.getDBPort(); if ( StringUtils.isEmpty( username ) ) { String msg = "No provided DB username or DB username is empty string."; log.error( msg ); throw new Exception(msg); } if ( StringUtils.isEmpty( password ) ) { String msg = "No provided DB password or DB password is empty string."; log.error( msg ); throw new Exception(msg); } if ( StringUtils.isEmpty( dbURL ) ) { String msg = "No provided DB URL or DB URL is empty string."; log.error( msg ); throw new Exception(msg); } if ( StringUtils.isEmpty( dbPort ) ) { dbPort = _DEFAULT_PORT; // set to default port } dataSource = new BasicDataSource(); dataSource.setUrl("jdbc:mysql://" + dbURL + ":" + dbPort + "/" + db + "?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8" ); dataSource.setUsername( username ); dataSource.setPassword( password ); dataSource.setValidationQuery("select 1 from dual"); dataSource.setTestOnBorrow( true ); dataSource.setMinEvictableIdleTimeMillis( 21600000 ); dataSource.setTimeBetweenEvictionRunsMillis( 30000 ); _dataSources.put( db, dataSource ); } return dataSource.getConnection(); } // close them all @Override public void closeAllConnections() throws Exception { if( _dataSources == null ) { return; } if ( _insertControlCommitConnection != null ) { boolean connectionAutoCommit = _insertControlCommitConnection.getAutoCommit(); if ( ! connectionAutoCommit ) { _insertControlCommitConnection.commit(); } _insertControlCommitConnection.close(); } for( Map.Entry<String, BasicDataSource> dataSourcesEntry : _dataSources.entrySet() ) { try { dataSourcesEntry.getValue().close(); } catch( Exception e ) { ; } } _dataSources = null; } }
src/org/yeastrc/proxl/import_xml_to_db/db/ImportDBConnectionFactory.java
package org.yeastrc.proxl.import_xml_to_db.db; import java.sql.Connection; import java.util.HashMap; import java.util.Map; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.yeastrc.xlink.db.DBConnectionFactory; import org.yeastrc.xlink.db.IDBConnectionFactory; /** * Singleton * */ public class ImportDBConnectionFactory implements IDBConnectionFactory { private static Logger log = Logger.getLogger(ImportDBConnectionFactory.class); private static final String _DEFAULT_PORT = "3306"; private static final int COMMIT_AFTER_500_INSERTS = 500; // Singleton private static final ImportDBConnectionFactory _INSTANCE = new ImportDBConnectionFactory(); // private constructor private ImportDBConnectionFactory() { } public static ImportDBConnectionFactory getInstance() { return _INSTANCE; } private Map<String, BasicDataSource> _dataSources = null; private Connection _insertControlCommitConnection = null; private int _insertControlCommitConnectionGetCount = 0; private IDBConnectionParametersProvider dbConnectionParametersProvider = null; /** * Allow setting a value for dbConnectionParametersProvider * * @param dbConnectionParametersProvider */ public void setDbConnectionParametersProvider( IDBConnectionParametersProvider dbConnectionParametersProvider) { this.dbConnectionParametersProvider = dbConnectionParametersProvider; if ( StringUtils.isNotEmpty( dbConnectionParametersProvider.getProxlDbName() ) ) { System.out.println( "Proxl DB Name from Connection Provider: " + dbConnectionParametersProvider.getProxlDbName() ); log.info( "Proxl DB Name from Connection Provider: " + dbConnectionParametersProvider.getProxlDbName() ); } if ( StringUtils.isNotEmpty( dbConnectionParametersProvider.getNrseqDbName() ) ) { System.out.println( "YRC_NRSEQ DB Name from Connection Provider: " + dbConnectionParametersProvider.getNrseqDbName() ); log.info( "YRC_NRSEQ DB Name from Connection Provider: " + dbConnectionParametersProvider.getNrseqDbName() ); } } /** * @return * @throws Exception */ public Connection getInsertControlCommitConnection() throws Exception { if ( _insertControlCommitConnection == null ) { _insertControlCommitConnection = getConnection( DBConnectionFactory.PROXL ); _insertControlCommitConnection.setAutoCommit(false); _insertControlCommitConnectionGetCount = 0; } _insertControlCommitConnectionGetCount++; if ( _insertControlCommitConnectionGetCount > COMMIT_AFTER_500_INSERTS ) { commitInsertControlCommitConnection(); _insertControlCommitConnectionGetCount = 0; } return _insertControlCommitConnection; } /** * call commit() on the insert connection and return the connection to the pool * @throws Exception */ public void commitInsertControlCommitConnection() throws Exception { if ( _insertControlCommitConnection == null ) { return; } _insertControlCommitConnection.commit(); _insertControlCommitConnection.close(); // Return connection to pool _insertControlCommitConnection = null; } // get a connection to the requested database @Override public Connection getConnection( String db ) throws Exception { if ( dbConnectionParametersProvider == null ) { dbConnectionParametersProvider = new DBConnectionParametersProviderFromPropertiesFile(); dbConnectionParametersProvider.init(); if ( StringUtils.isNotEmpty( dbConnectionParametersProvider.getProxlDbName() ) ) { System.out.println( "Proxl DB Name from Connection Provider: " + dbConnectionParametersProvider.getProxlDbName() ); log.info( "Proxl DB Name from Connection Provider: " + dbConnectionParametersProvider.getProxlDbName() ); } if ( StringUtils.isNotEmpty( dbConnectionParametersProvider.getNrseqDbName() ) ) { System.out.println( "YRC_NRSEQ DB Name from Connection Provider: " + dbConnectionParametersProvider.getNrseqDbName() ); log.info( "YRC_NRSEQ DB Name from Connection Provider: " + dbConnectionParametersProvider.getNrseqDbName() ); } } // Allow change of database if ( DBConnectionFactory.PROXL.equals(db) ) { if ( StringUtils.isNotEmpty( dbConnectionParametersProvider.getProxlDbName() ) ) { db = dbConnectionParametersProvider.getProxlDbName(); } } if( _dataSources == null ) { _dataSources = new HashMap<String, BasicDataSource>(); Class.forName("com.mysql.jdbc.Driver"); } BasicDataSource dataSource = _dataSources.get( db ); if ( dataSource == null ) { // create datasource for this db name String username = dbConnectionParametersProvider.getUsername(); String password = dbConnectionParametersProvider.getPassword(); String dbURL = dbConnectionParametersProvider.getDBURL(); String dbPort = dbConnectionParametersProvider.getDBPort(); if ( StringUtils.isEmpty( username ) ) { String msg = "No provided DB username or DB username is empty string."; log.error( msg ); throw new Exception(msg); } if ( StringUtils.isEmpty( password ) ) { String msg = "No provided DB password or DB password is empty string."; log.error( msg ); throw new Exception(msg); } if ( StringUtils.isEmpty( dbURL ) ) { String msg = "No provided DB URL or DB URL is empty string."; log.error( msg ); throw new Exception(msg); } if ( StringUtils.isEmpty( dbPort ) ) { dbPort = _DEFAULT_PORT; // set to default port } dataSource = new BasicDataSource(); dataSource.setUrl("jdbc:mysql://" + dbURL + ":" + dbPort + "/" + db + "?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8" ); dataSource.setUsername( username ); dataSource.setPassword( password ); dataSource.setValidationQuery("select 1 from dual"); dataSource.setTestOnBorrow( true ); dataSource.setMinEvictableIdleTimeMillis( 21600000 ); dataSource.setTimeBetweenEvictionRunsMillis( 30000 ); _dataSources.put( db, dataSource ); } return dataSource.getConnection(); } // close them all @Override public void closeAllConnections() throws Exception { if( _dataSources == null ) { return; } if ( _insertControlCommitConnection != null ) { boolean connectionAutoCommit = _insertControlCommitConnection.getAutoCommit(); if ( ! connectionAutoCommit ) { _insertControlCommitConnection.commit(); } _insertControlCommitConnection.close(); } for( Map.Entry<String, BasicDataSource> dataSourcesEntry : _dataSources.entrySet() ) { try { dataSourcesEntry.getValue().close(); } catch( Exception e ) { ; } } _dataSources = null; } }
Updates for Insert Connection to commit and return it to pool after each block
src/org/yeastrc/proxl/import_xml_to_db/db/ImportDBConnectionFactory.java
Updates for Insert Connection to commit and return it to pool after each block
Java
apache-2.0
d212430af336da3c8bc32fcd90268168df0d42b9
0
SpineEventEngine/gae-java,SpineEventEngine/gae-java
/* * Copyright 2015, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * This package contains Google Cloud Datastore implementation of the storages. * * @see org.spine3.server.storage.AbstractStorage */ @ParametersAreNonnullByDefault package org.spine3.server.storage.datastore; import javax.annotation.ParametersAreNonnullByDefault;
gcd/src/main/java/org/spine3/server/storage/datastore/package-info.java
/* * Copyright 2015, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * This package contains Google Cloud Datastore implementation of storages. * * @see org.spine3.server.storage.AbstractStorage */ @ParametersAreNonnullByDefault package org.spine3.server.storage.datastore; import javax.annotation.ParametersAreNonnullByDefault;
Correct javadoc.
gcd/src/main/java/org/spine3/server/storage/datastore/package-info.java
Correct javadoc.
Java
apache-2.0
ec4f5afbc6d18dbdc87330c545aa92c91dfcef1c
0
md5555/android_packages_services_Telephony
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import android.app.Activity; import android.app.ActivityManagerNative; import android.app.AlertDialog; import android.app.AppOpsManager; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.net.Uri; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.os.SystemProperties; import android.os.UserHandle; import android.telephony.PhoneNumberUtils; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneConstants; import com.android.internal.telephony.TelephonyCapabilities; /** * OutgoingCallBroadcaster receives CALL and CALL_PRIVILEGED Intents, and broadcasts the * ACTION_NEW_OUTGOING_CALL intent. ACTION_NEW_OUTGOING_CALL is an ordered broadcast intent which * contains the phone number being dialed. Applications can use this intent to (1) see which numbers * are being dialed, (2) redirect a call (change the number being dialed), or (3) prevent a call * from being placed. * * After the other applications have had a chance to see the * ACTION_NEW_OUTGOING_CALL intent, it finally reaches the * {@link OutgoingCallReceiver}, which passes the (possibly modified) * intent on to the {@link SipCallOptionHandler}, which will * ultimately start the call using the CallController.placeCall() API. * * Calls where no number is present (like for a CDMA "empty flash" or a nonexistent voicemail * number) are exempt from being broadcast. * Calls to emergency numbers are still broadcast for informative purposes. The call is placed * prior to sending ACTION_NEW_OUTGOING_CALL and cannot be redirected nor prevented. */ public class OutgoingCallBroadcaster extends Activity implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener { private static final String TAG = "OutgoingCallBroadcaster"; private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1); // Do not check in with VDBG = true, since that may write PII to the system log. private static final boolean VDBG = false; /** Required permission for any app that wants to consume ACTION_NEW_OUTGOING_CALL. */ private static final String PERMISSION = android.Manifest.permission.PROCESS_OUTGOING_CALLS; public static final String ACTION_SIP_SELECT_PHONE = "com.android.phone.SIP_SELECT_PHONE"; public static final String EXTRA_ALREADY_CALLED = "android.phone.extra.ALREADY_CALLED"; public static final String EXTRA_ORIGINAL_URI = "android.phone.extra.ORIGINAL_URI"; public static final String EXTRA_NEW_CALL_INTENT = "android.phone.extra.NEW_CALL_INTENT"; public static final String EXTRA_SIP_PHONE_URI = "android.phone.extra.SIP_PHONE_URI"; public static final String EXTRA_ACTUAL_NUMBER_TO_DIAL = "android.phone.extra.ACTUAL_NUMBER_TO_DIAL"; /** * Identifier for intent extra for sending an empty Flash message for * CDMA networks. This message is used by the network to simulate a * press/depress of the "hookswitch" of a landline phone. Aka "empty flash". * * TODO: Receiving an intent extra to tell the phone to send this flash is a * temporary measure. To be replaced with an external ITelephony call in the future. * TODO: Keep in sync with the string defined in TwelveKeyDialer.java in Contacts app * until this is replaced with the ITelephony API. */ public static final String EXTRA_SEND_EMPTY_FLASH = "com.android.phone.extra.SEND_EMPTY_FLASH"; // Dialog IDs private static final int DIALOG_NOT_VOICE_CAPABLE = 1; /** Note message codes < 100 are reserved for the PhoneApp. */ private static final int EVENT_OUTGOING_CALL_TIMEOUT = 101; private static final int EVENT_DELAYED_FINISH = 102; private static final int OUTGOING_CALL_TIMEOUT_THRESHOLD = 2000; // msec private static final int DELAYED_FINISH_TIME = 2000; // msec /** * ProgressBar object with "spinner" style, which will be shown if we take more than * {@link #EVENT_OUTGOING_CALL_TIMEOUT} msec to handle the incoming Intent. */ private ProgressBar mWaitingSpinner; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == EVENT_OUTGOING_CALL_TIMEOUT) { Log.i(TAG, "Outgoing call takes too long. Showing the spinner."); mWaitingSpinner.setVisibility(View.VISIBLE); } else if (msg.what == EVENT_DELAYED_FINISH) { finish(); } else { Log.wtf(TAG, "Unknown message id: " + msg.what); } } }; /** * Starts the delayed finish() of OutgoingCallBroadcaster in order to give the UI * some time to start up. */ private void startDelayedFinish() { mHandler.sendEmptyMessageDelayed(EVENT_DELAYED_FINISH, DELAYED_FINISH_TIME); } /** * OutgoingCallReceiver finishes NEW_OUTGOING_CALL broadcasts, starting * the InCallScreen if the broadcast has not been canceled, possibly with * a modified phone number and optional provider info (uri + package name + remote views.) */ public class OutgoingCallReceiver extends BroadcastReceiver { private static final String TAG = "OutgoingCallReceiver"; @Override public void onReceive(Context context, Intent intent) { mHandler.removeMessages(EVENT_OUTGOING_CALL_TIMEOUT); final boolean isAttemptingCall = doReceive(context, intent); if (DBG) Log.v(TAG, "OutgoingCallReceiver is going to finish the Activity itself."); // We cannot finish the activity immediately here because it would cause the temporary // black screen of OutgoingBroadcaster to go away and we need it to stay up until the // UI (in a different process) has time to come up. // However, if we know we are not attemping a call, we need to finish the activity // immediately so that subsequent CALL intents will retrigger a new // OutgoingCallReceiver. see b/10857203 if (isAttemptingCall) { startDelayedFinish(); } else { finish(); } } /** * Handes receipt of ordered new_outgoing_call intent. Verifies that the return from the * ordered intent is valid. * @return true if the call is being attempted; false if we are canceling the call. */ public boolean doReceive(Context context, Intent intent) { if (DBG) Log.v(TAG, "doReceive: " + intent); boolean alreadyCalled; String number; String originalUri; alreadyCalled = intent.getBooleanExtra( OutgoingCallBroadcaster.EXTRA_ALREADY_CALLED, false); if (alreadyCalled) { if (DBG) Log.v(TAG, "CALL already placed -- returning."); return false; } // Once the NEW_OUTGOING_CALL broadcast is finished, the resultData // is used as the actual number to call. (If null, no call will be // placed.) number = getResultData(); if (VDBG) Log.v(TAG, "- got number from resultData: '" + number + "'"); final PhoneGlobals app = PhoneGlobals.getInstance(); // OTASP-specific checks. // TODO: This should probably all happen in // OutgoingCallBroadcaster.onCreate(), since there's no reason to // even bother with the NEW_OUTGOING_CALL broadcast if we're going // to disallow the outgoing call anyway... if (TelephonyCapabilities.supportsOtasp(app.phone)) { boolean activateState = (app.cdmaOtaScreenState.otaScreenState == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION); boolean dialogState = (app.cdmaOtaScreenState.otaScreenState == OtaUtils.CdmaOtaScreenState.OtaScreenState .OTA_STATUS_SUCCESS_FAILURE_DLG); boolean isOtaCallActive = false; // TODO: Need cleaner way to check if OTA is active. // Also, this check seems to be broken in one obscure case: if // you interrupt an OTASP call by pressing Back then Skip, // otaScreenState somehow gets left in either PROGRESS or // LISTENING. if ((app.cdmaOtaScreenState.otaScreenState == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_PROGRESS) || (app.cdmaOtaScreenState.otaScreenState == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_LISTENING)) { isOtaCallActive = true; } if (activateState || dialogState) { // The OTASP sequence is active, but either (1) the call // hasn't started yet, or (2) the call has ended and we're // showing the success/failure screen. In either of these // cases it's OK to make a new outgoing call, but we need // to take down any OTASP-related UI first. if (dialogState) app.dismissOtaDialogs(); app.clearOtaState(); } else if (isOtaCallActive) { // The actual OTASP call is active. Don't allow new // outgoing calls at all from this state. Log.w(TAG, "OTASP call is active: disallowing a new outgoing call."); return false; } } if (number == null) { if (DBG) Log.v(TAG, "CALL cancelled (null number), returning..."); return false; } else if (TelephonyCapabilities.supportsOtasp(app.phone) && (app.phone.getState() != PhoneConstants.State.IDLE) && (app.phone.isOtaSpNumber(number))) { if (DBG) Log.v(TAG, "Call is active, a 2nd OTA call cancelled -- returning."); return false; } else if (PhoneNumberUtils.isPotentialLocalEmergencyNumber(number, context)) { // Just like 3rd-party apps aren't allowed to place emergency // calls via the ACTION_CALL intent, we also don't allow 3rd // party apps to use the NEW_OUTGOING_CALL broadcast to rewrite // an outgoing call into an emergency number. Log.w(TAG, "Cannot modify outgoing call to emergency number " + number + "."); return false; } originalUri = intent.getStringExtra( OutgoingCallBroadcaster.EXTRA_ORIGINAL_URI); if (originalUri == null) { Log.e(TAG, "Intent is missing EXTRA_ORIGINAL_URI -- returning."); return false; } Uri uri = Uri.parse(originalUri); // We already called convertKeypadLettersToDigits() and // stripSeparators() way back in onCreate(), before we sent out the // NEW_OUTGOING_CALL broadcast. But we need to do it again here // too, since the number might have been modified/rewritten during // the broadcast (and may now contain letters or separators again.) number = PhoneNumberUtils.convertKeypadLettersToDigits(number); number = PhoneNumberUtils.stripSeparators(number); if (DBG) Log.v(TAG, "doReceive: proceeding with call..."); if (VDBG) Log.v(TAG, "- uri: " + uri); if (VDBG) Log.v(TAG, "- actual number to dial: '" + number + "'"); startSipCallOptionHandler(context, intent, uri, number); return true; } } /** * Launch the SipCallOptionHandler, which is the next step(*) in the * outgoing-call sequence after the outgoing call broadcast is * complete. * * (*) We now know exactly what phone number we need to dial, so the next * step is for the SipCallOptionHandler to decide which Phone type (SIP * or PSTN) should be used. (Depending on the user's preferences, this * decision may also involve popping up a dialog to ask the user to * choose what type of call this should be.) * * @param context used for the startActivity() call * * @param intent the intent from the previous step of the outgoing-call * sequence. Normally this will be the NEW_OUTGOING_CALL broadcast intent * that came in to the OutgoingCallReceiver, although it can also be the * original ACTION_CALL intent that started the whole sequence (in cases * where we don't do the NEW_OUTGOING_CALL broadcast at all, like for * emergency numbers or SIP addresses). * * @param uri the data URI from the original CALL intent, presumably either * a tel: or sip: URI. For tel: URIs, note that the scheme-specific part * does *not* necessarily have separators and keypad letters stripped (so * we might see URIs like "tel:(650)%20555-1234" or "tel:1-800-GOOG-411" * here.) * * @param number the actual number (or SIP address) to dial. This is * guaranteed to be either a PSTN phone number with separators stripped * out and keypad letters converted to digits (like "16505551234"), or a * raw SIP address (like "[email protected]"). */ private void startSipCallOptionHandler(Context context, Intent intent, Uri uri, String number) { if (VDBG) { Log.i(TAG, "startSipCallOptionHandler..."); Log.i(TAG, "- intent: " + intent); Log.i(TAG, "- uri: " + uri); Log.i(TAG, "- number: " + number); } // Create a copy of the original CALL intent that started the whole // outgoing-call sequence. This intent will ultimately be passed to // CallController.placeCall() after the SipCallOptionHandler step. Intent newIntent = new Intent(Intent.ACTION_CALL, uri); newIntent.putExtra(EXTRA_ACTUAL_NUMBER_TO_DIAL, number); CallGatewayManager.checkAndCopyPhoneProviderExtras(intent, newIntent); // Finally, launch the SipCallOptionHandler, with the copy of the // original CALL intent stashed away in the EXTRA_NEW_CALL_INTENT // extra. Intent selectPhoneIntent = new Intent(ACTION_SIP_SELECT_PHONE, uri); selectPhoneIntent.setClass(context, SipCallOptionHandler.class); selectPhoneIntent.putExtra(EXTRA_NEW_CALL_INTENT, newIntent); selectPhoneIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (DBG) { Log.v(TAG, "startSipCallOptionHandler(): " + "calling startActivity: " + selectPhoneIntent); } context.startActivity(selectPhoneIntent); // ...and see SipCallOptionHandler.onCreate() for the next step of the sequence. } /** * This method is the single point of entry for the CALL intent, which is used (by built-in * apps like Contacts / Dialer, as well as 3rd-party apps) to initiate an outgoing voice call. * * */ @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.outgoing_call_broadcaster); mWaitingSpinner = (ProgressBar) findViewById(R.id.spinner); Intent intent = getIntent(); if (DBG) { final Configuration configuration = getResources().getConfiguration(); Log.v(TAG, "onCreate: this = " + this + ", icicle = " + icicle); Log.v(TAG, " - getIntent() = " + intent); Log.v(TAG, " - configuration = " + configuration); } if (icicle != null) { // A non-null icicle means that this activity is being // re-initialized after previously being shut down. // // In practice this happens very rarely (because the lifetime // of this activity is so short!), but it *can* happen if the // framework detects a configuration change at exactly the // right moment; see bug 2202413. // // In this case, do nothing. Our onCreate() method has already // run once (with icicle==null the first time), which means // that the NEW_OUTGOING_CALL broadcast for this new call has // already been sent. Log.i(TAG, "onCreate: non-null icicle! " + "Bailing out, not sending NEW_OUTGOING_CALL broadcast..."); // No need to finish() here, since the OutgoingCallReceiver from // our original instance will do that. (It'll actually call // finish() on our original instance, which apparently works fine // even though the ActivityManager has already shut that instance // down. And note that if we *do* call finish() here, that just // results in an "ActivityManager: Duplicate finish request" // warning when the OutgoingCallReceiver runs.) return; } processIntent(intent); // isFinishing() return false when 1. broadcast is still ongoing, or 2. dialog is being // shown. Otherwise finish() is called inside processIntent(), is isFinishing() here will // return true. if (DBG) Log.v(TAG, "At the end of onCreate(). isFinishing(): " + isFinishing()); } /** * Interprets a given Intent and starts something relevant to the Intent. * * This method will handle three kinds of actions: * * - CALL (action for usual outgoing voice calls) * - CALL_PRIVILEGED (can come from built-in apps like contacts / voice dialer / bluetooth) * - CALL_EMERGENCY (from the EmergencyDialer that's reachable from the lockscreen.) * * The exact behavior depends on the intent's data: * * - The most typical is a tel: URI, which we handle by starting the * NEW_OUTGOING_CALL broadcast. That broadcast eventually triggers * the sequence OutgoingCallReceiver -> SipCallOptionHandler -> * InCallScreen. * * - Or, with a sip: URI we skip the NEW_OUTGOING_CALL broadcast and * go directly to SipCallOptionHandler, which then leads to the * InCallScreen. * * - voicemail: URIs take the same path as regular tel: URIs. * * Other special cases: * * - Outgoing calls are totally disallowed on non-voice-capable * devices (see handleNonVoiceCapable()). * * - A CALL intent with the EXTRA_SEND_EMPTY_FLASH extra (and * presumably no data at all) means "send an empty flash" (which * is only meaningful on CDMA devices while a call is already * active.) * */ private void processIntent(Intent intent) { if (DBG) { Log.v(TAG, "processIntent() = " + intent + ", thread: " + Thread.currentThread()); } final Configuration configuration = getResources().getConfiguration(); // Outgoing phone calls are only allowed on "voice-capable" devices. if (!PhoneGlobals.sVoiceCapable) { Log.i(TAG, "This device is detected as non-voice-capable device."); handleNonVoiceCapable(intent); return; } String action = intent.getAction(); String number = PhoneNumberUtils.getNumberFromIntent(intent, this); // Check the number, don't convert for sip uri // TODO put uriNumber under PhoneNumberUtils if (number != null) { if (!PhoneNumberUtils.isUriNumber(number)) { number = PhoneNumberUtils.convertKeypadLettersToDigits(number); number = PhoneNumberUtils.stripSeparators(number); } } else { Log.w(TAG, "The number obtained from Intent is null."); } AppOpsManager appOps = (AppOpsManager)getSystemService(Context.APP_OPS_SERVICE); int launchedFromUid; String launchedFromPackage; try { launchedFromUid = ActivityManagerNative.getDefault().getLaunchedFromUid( getActivityToken()); launchedFromPackage = ActivityManagerNative.getDefault().getLaunchedFromPackage( getActivityToken()); } catch (RemoteException e) { launchedFromUid = -1; launchedFromPackage = null; } if (appOps.noteOpNoThrow(AppOpsManager.OP_CALL_PHONE, launchedFromUid, launchedFromPackage) != AppOpsManager.MODE_ALLOWED) { Log.w(TAG, "Rejecting call from uid " + launchedFromUid + " package " + launchedFromPackage); finish(); return; } // If true, this flag will indicate that the current call is a special kind // of call (most likely an emergency number) that 3rd parties aren't allowed // to intercept or affect in any way. (In that case, we start the call // immediately rather than going through the NEW_OUTGOING_CALL sequence.) boolean callNow; if (getClass().getName().equals(intent.getComponent().getClassName())) { // If we were launched directly from the OutgoingCallBroadcaster, // not one of its more privileged aliases, then make sure that // only the non-privileged actions are allowed. if (!Intent.ACTION_CALL.equals(intent.getAction())) { Log.w(TAG, "Attempt to deliver non-CALL action; forcing to CALL"); intent.setAction(Intent.ACTION_CALL); } } // Check whether or not this is an emergency number, in order to // enforce the restriction that only the CALL_PRIVILEGED and // CALL_EMERGENCY intents are allowed to make emergency calls. // // (Note that the ACTION_CALL check below depends on the result of // isPotentialLocalEmergencyNumber() rather than just plain // isLocalEmergencyNumber(), to be 100% certain that we *don't* // allow 3rd party apps to make emergency calls by passing in an // "invalid" number like "9111234" that isn't technically an // emergency number but might still result in an emergency call // with some networks.) final boolean isExactEmergencyNumber = (number != null) && PhoneNumberUtils.isLocalEmergencyNumber(number, this); final boolean isPotentialEmergencyNumber = (number != null) && PhoneNumberUtils.isPotentialLocalEmergencyNumber(number, this); if (VDBG) { Log.v(TAG, " - Checking restrictions for number '" + number + "':"); Log.v(TAG, " isExactEmergencyNumber = " + isExactEmergencyNumber); Log.v(TAG, " isPotentialEmergencyNumber = " + isPotentialEmergencyNumber); } /* Change CALL_PRIVILEGED into CALL or CALL_EMERGENCY as needed. */ // TODO: This code is redundant with some code in InCallScreen: refactor. if (Intent.ACTION_CALL_PRIVILEGED.equals(action)) { // We're handling a CALL_PRIVILEGED intent, so we know this request came // from a trusted source (like the built-in dialer.) So even a number // that's *potentially* an emergency number can safely be promoted to // CALL_EMERGENCY (since we *should* allow you to dial "91112345" from // the dialer if you really want to.) if (isPotentialEmergencyNumber) { Log.i(TAG, "ACTION_CALL_PRIVILEGED is used while the number is a potential" + " emergency number. Use ACTION_CALL_EMERGENCY as an action instead."); action = Intent.ACTION_CALL_EMERGENCY; } else { action = Intent.ACTION_CALL; } if (DBG) Log.v(TAG, " - updating action from CALL_PRIVILEGED to " + action); intent.setAction(action); } if (Intent.ACTION_CALL.equals(action)) { if (isPotentialEmergencyNumber) { Log.w(TAG, "Cannot call potential emergency number '" + number + "' with CALL Intent " + intent + "."); Log.i(TAG, "Launching default dialer instead..."); Intent invokeFrameworkDialer = new Intent(); // TwelveKeyDialer is in a tab so we really want // DialtactsActivity. Build the intent 'manually' to // use the java resolver to find the dialer class (as // opposed to a Context which look up known android // packages only) final Resources resources = getResources(); invokeFrameworkDialer.setClassName( resources.getString(R.string.ui_default_package), resources.getString(R.string.dialer_default_class)); invokeFrameworkDialer.setAction(Intent.ACTION_DIAL); invokeFrameworkDialer.setData(intent.getData()); if (DBG) Log.v(TAG, "onCreate(): calling startActivity for Dialer: " + invokeFrameworkDialer); startActivity(invokeFrameworkDialer); finish(); return; } callNow = false; } else if (Intent.ACTION_CALL_EMERGENCY.equals(action)) { // ACTION_CALL_EMERGENCY case: this is either a CALL_PRIVILEGED // intent that we just turned into a CALL_EMERGENCY intent (see // above), or else it really is an CALL_EMERGENCY intent that // came directly from some other app (e.g. the EmergencyDialer // activity built in to the Phone app.) // Make sure it's at least *possible* that this is really an // emergency number. if (!isPotentialEmergencyNumber) { Log.w(TAG, "Cannot call non-potential-emergency number " + number + " with EMERGENCY_CALL Intent " + intent + "." + " Finish the Activity immediately."); finish(); return; } callNow = true; } else { Log.e(TAG, "Unhandled Intent " + intent + ". Finish the Activity immediately."); finish(); return; } // Make sure the screen is turned on. This is probably the right // thing to do, and more importantly it works around an issue in the // activity manager where we will not launch activities consistently // when the screen is off (since it is trying to keep them paused // and has... issues). // // Also, this ensures the device stays awake while doing the following // broadcast; technically we should be holding a wake lock here // as well. PhoneGlobals.getInstance().wakeUpScreen(); // If number is null, we're probably trying to call a non-existent voicemail number, // send an empty flash or something else is fishy. Whatever the problem, there's no // number, so there's no point in allowing apps to modify the number. if (TextUtils.isEmpty(number)) { if (intent.getBooleanExtra(EXTRA_SEND_EMPTY_FLASH, false)) { Log.i(TAG, "onCreate: SEND_EMPTY_FLASH..."); PhoneUtils.sendEmptyFlash(PhoneGlobals.getPhone()); finish(); return; } else { Log.i(TAG, "onCreate: null or empty number, setting callNow=true..."); callNow = true; } } if (callNow) { // This is a special kind of call (most likely an emergency number) // that 3rd parties aren't allowed to intercept or affect in any way. // So initiate the outgoing call immediately. Log.i(TAG, "onCreate(): callNow case! Calling placeCall(): " + intent); // Initiate the outgoing call, and simultaneously launch the // InCallScreen to display the in-call UI: PhoneGlobals.getInstance().callController.placeCall(intent); // Note we do *not* "return" here, but instead continue and // send the ACTION_NEW_OUTGOING_CALL broadcast like for any // other outgoing call. (But when the broadcast finally // reaches the OutgoingCallReceiver, we'll know not to // initiate the call again because of the presence of the // EXTRA_ALREADY_CALLED extra.) } // For now, SIP calls will be processed directly without a // NEW_OUTGOING_CALL broadcast. // // TODO: In the future, though, 3rd party apps *should* be allowed to // intercept outgoing calls to SIP addresses as well. To do this, we should // (1) update the NEW_OUTGOING_CALL intent documentation to explain this // case, and (2) pass the outgoing SIP address by *not* overloading the // EXTRA_PHONE_NUMBER extra, but instead using a new separate extra to hold // the outgoing SIP address. (Be sure to document whether it's a URI or just // a plain address, whether it could be a tel: URI, etc.) Uri uri = intent.getData(); String scheme = uri.getScheme(); if (Constants.SCHEME_SIP.equals(scheme) || PhoneNumberUtils.isUriNumber(number)) { Log.i(TAG, "The requested number was detected as SIP call."); startSipCallOptionHandler(this, intent, uri, number); finish(); return; // TODO: if there's ever a way for SIP calls to trigger a // "callNow=true" case (see above), we'll need to handle that // case here too (most likely by just doing nothing at all.) } Intent broadcastIntent = new Intent(Intent.ACTION_NEW_OUTGOING_CALL); if (number != null) { broadcastIntent.putExtra(Intent.EXTRA_PHONE_NUMBER, number); } CallGatewayManager.checkAndCopyPhoneProviderExtras(intent, broadcastIntent); broadcastIntent.putExtra(EXTRA_ALREADY_CALLED, callNow); broadcastIntent.putExtra(EXTRA_ORIGINAL_URI, uri.toString()); // Need to raise foreground in-call UI as soon as possible while allowing 3rd party app // to intercept the outgoing call. broadcastIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); if (DBG) Log.v(TAG, " - Broadcasting intent: " + broadcastIntent + "."); // Set a timer so that we can prepare for unexpected delay introduced by the broadcast. // If it takes too much time, the timer will show "waiting" spinner. // This message will be removed when OutgoingCallReceiver#onReceive() is called before the // timeout. mHandler.sendEmptyMessageDelayed(EVENT_OUTGOING_CALL_TIMEOUT, OUTGOING_CALL_TIMEOUT_THRESHOLD); sendOrderedBroadcastAsUser(broadcastIntent, UserHandle.OWNER, PERMISSION, new OutgoingCallReceiver(), null, // scheduler Activity.RESULT_OK, // initialCode number, // initialData: initial value for the result data null); // initialExtras } @Override protected void onStop() { // Clean up (and dismiss if necessary) any managed dialogs. // // We don't do this in onPause() since we can be paused/resumed // due to orientation changes (in which case we don't want to // disturb the dialog), but we *do* need it here in onStop() to be // sure we clean up if the user hits HOME while the dialog is up. // // Note it's safe to call removeDialog() even if there's no dialog // associated with that ID. removeDialog(DIALOG_NOT_VOICE_CAPABLE); super.onStop(); } /** * Handle the specified CALL or CALL_* intent on a non-voice-capable * device. * * This method may launch a different intent (if there's some useful * alternative action to take), or otherwise display an error dialog, * and in either case will finish() the current activity when done. */ private void handleNonVoiceCapable(Intent intent) { if (DBG) Log.v(TAG, "handleNonVoiceCapable: handling " + intent + " on non-voice-capable device..."); // Just show a generic "voice calling not supported" dialog. showDialog(DIALOG_NOT_VOICE_CAPABLE); // ...and we'll eventually finish() when the user dismisses // or cancels the dialog. } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; switch(id) { case DIALOG_NOT_VOICE_CAPABLE: dialog = new AlertDialog.Builder(this) .setTitle(R.string.not_voice_capable) .setIconAttribute(android.R.attr.alertDialogIcon) .setPositiveButton(android.R.string.ok, this) .setOnCancelListener(this) .create(); break; default: Log.w(TAG, "onCreateDialog: unexpected ID " + id); dialog = null; break; } return dialog; } /** DialogInterface.OnClickListener implementation */ @Override public void onClick(DialogInterface dialog, int id) { // DIALOG_NOT_VOICE_CAPABLE is the only dialog we ever use (so far // at least), and its only button is "OK". finish(); } /** DialogInterface.OnCancelListener implementation */ @Override public void onCancel(DialogInterface dialog) { // DIALOG_NOT_VOICE_CAPABLE is the only dialog we ever use (so far // at least), and canceling it is just like hitting "OK". finish(); } /** * Implement onConfigurationChanged() purely for debugging purposes, * to make sure that the android:configChanges element in our manifest * is working properly. */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (DBG) Log.v(TAG, "onConfigurationChanged: newConfig = " + newConfig); } }
src/com/android/phone/OutgoingCallBroadcaster.java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import android.app.Activity; import android.app.ActivityManagerNative; import android.app.AlertDialog; import android.app.AppOpsManager; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.net.Uri; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.os.SystemProperties; import android.os.UserHandle; import android.telephony.PhoneNumberUtils; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneConstants; import com.android.internal.telephony.TelephonyCapabilities; /** * OutgoingCallBroadcaster receives CALL and CALL_PRIVILEGED Intents, and broadcasts the * ACTION_NEW_OUTGOING_CALL intent. ACTION_NEW_OUTGOING_CALL is an ordered broadcast intent which * contains the phone number being dialed. Applications can use this intent to (1) see which numbers * are being dialed, (2) redirect a call (change the number being dialed), or (3) prevent a call * from being placed. * * After the other applications have had a chance to see the * ACTION_NEW_OUTGOING_CALL intent, it finally reaches the * {@link OutgoingCallReceiver}, which passes the (possibly modified) * intent on to the {@link SipCallOptionHandler}, which will * ultimately start the call using the CallController.placeCall() API. * * Calls where no number is present (like for a CDMA "empty flash" or a nonexistent voicemail * number) are exempt from being broadcast. * Calls to emergency numbers are still broadcast for informative purposes. The call is placed * prior to sending ACTION_NEW_OUTGOING_CALL and cannot be redirected nor prevented. */ public class OutgoingCallBroadcaster extends Activity implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener { private static final String TAG = "OutgoingCallBroadcaster"; private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1); // Do not check in with VDBG = true, since that may write PII to the system log. private static final boolean VDBG = false; /** Required permission for any app that wants to consume ACTION_NEW_OUTGOING_CALL. */ private static final String PERMISSION = android.Manifest.permission.PROCESS_OUTGOING_CALLS; public static final String ACTION_SIP_SELECT_PHONE = "com.android.phone.SIP_SELECT_PHONE"; public static final String EXTRA_ALREADY_CALLED = "android.phone.extra.ALREADY_CALLED"; public static final String EXTRA_ORIGINAL_URI = "android.phone.extra.ORIGINAL_URI"; public static final String EXTRA_NEW_CALL_INTENT = "android.phone.extra.NEW_CALL_INTENT"; public static final String EXTRA_SIP_PHONE_URI = "android.phone.extra.SIP_PHONE_URI"; public static final String EXTRA_ACTUAL_NUMBER_TO_DIAL = "android.phone.extra.ACTUAL_NUMBER_TO_DIAL"; /** * Identifier for intent extra for sending an empty Flash message for * CDMA networks. This message is used by the network to simulate a * press/depress of the "hookswitch" of a landline phone. Aka "empty flash". * * TODO: Receiving an intent extra to tell the phone to send this flash is a * temporary measure. To be replaced with an external ITelephony call in the future. * TODO: Keep in sync with the string defined in TwelveKeyDialer.java in Contacts app * until this is replaced with the ITelephony API. */ public static final String EXTRA_SEND_EMPTY_FLASH = "com.android.phone.extra.SEND_EMPTY_FLASH"; // Dialog IDs private static final int DIALOG_NOT_VOICE_CAPABLE = 1; /** Note message codes < 100 are reserved for the PhoneApp. */ private static final int EVENT_OUTGOING_CALL_TIMEOUT = 101; private static final int EVENT_DELAYED_FINISH = 102; private static final int OUTGOING_CALL_TIMEOUT_THRESHOLD = 2000; // msec private static final int DELAYED_FINISH_TIME = 2000; // msec /** * ProgressBar object with "spinner" style, which will be shown if we take more than * {@link #EVENT_OUTGOING_CALL_TIMEOUT} msec to handle the incoming Intent. */ private ProgressBar mWaitingSpinner; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == EVENT_OUTGOING_CALL_TIMEOUT) { Log.i(TAG, "Outgoing call takes too long. Showing the spinner."); mWaitingSpinner.setVisibility(View.VISIBLE); } else if (msg.what == EVENT_DELAYED_FINISH) { finish(); } else { Log.wtf(TAG, "Unknown message id: " + msg.what); } } }; /** * Starts the delayed finish() of OutgoingCallBroadcaster in order to give the UI * some time to start up. */ private void startDelayedFinish() { mHandler.sendEmptyMessageDelayed(EVENT_DELAYED_FINISH, DELAYED_FINISH_TIME); } /** * OutgoingCallReceiver finishes NEW_OUTGOING_CALL broadcasts, starting * the InCallScreen if the broadcast has not been canceled, possibly with * a modified phone number and optional provider info (uri + package name + remote views.) */ public class OutgoingCallReceiver extends BroadcastReceiver { private static final String TAG = "OutgoingCallReceiver"; @Override public void onReceive(Context context, Intent intent) { mHandler.removeMessages(EVENT_OUTGOING_CALL_TIMEOUT); final boolean isAttemptingCall = doReceive(context, intent); if (DBG) Log.v(TAG, "OutgoingCallReceiver is going to finish the Activity itself."); // We cannot finish the activity immediately here because it would cause the temporary // black screen of OutgoingBroadcaster to go away and we need it to stay up until the // UI (in a different process) has time to come up. // However, if we know we are not attemping a call, we need to finish the activity // immediately so that subsequent CALL intents will retrigger a new // OutgoingCallReceiver. see b/10857203 if (isAttemptingCall) { startDelayedFinish(); } else { finish(); } } /** * Handes receipt of ordered new_outgoing_call intent. Verifies that the return from the * ordered intent is valid. * @return true if the call is being attempted; false if we are canceling the call. */ public boolean doReceive(Context context, Intent intent) { if (DBG) Log.v(TAG, "doReceive: " + intent); boolean alreadyCalled; String number; String originalUri; alreadyCalled = intent.getBooleanExtra( OutgoingCallBroadcaster.EXTRA_ALREADY_CALLED, false); if (alreadyCalled) { if (DBG) Log.v(TAG, "CALL already placed -- returning."); return false; } // Once the NEW_OUTGOING_CALL broadcast is finished, the resultData // is used as the actual number to call. (If null, no call will be // placed.) number = getResultData(); if (VDBG) Log.v(TAG, "- got number from resultData: '" + number + "'"); final PhoneGlobals app = PhoneGlobals.getInstance(); // OTASP-specific checks. // TODO: This should probably all happen in // OutgoingCallBroadcaster.onCreate(), since there's no reason to // even bother with the NEW_OUTGOING_CALL broadcast if we're going // to disallow the outgoing call anyway... if (TelephonyCapabilities.supportsOtasp(app.phone)) { boolean activateState = (app.cdmaOtaScreenState.otaScreenState == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION); boolean dialogState = (app.cdmaOtaScreenState.otaScreenState == OtaUtils.CdmaOtaScreenState.OtaScreenState .OTA_STATUS_SUCCESS_FAILURE_DLG); boolean isOtaCallActive = false; // TODO: Need cleaner way to check if OTA is active. // Also, this check seems to be broken in one obscure case: if // you interrupt an OTASP call by pressing Back then Skip, // otaScreenState somehow gets left in either PROGRESS or // LISTENING. if ((app.cdmaOtaScreenState.otaScreenState == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_PROGRESS) || (app.cdmaOtaScreenState.otaScreenState == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_LISTENING)) { isOtaCallActive = true; } if (activateState || dialogState) { // The OTASP sequence is active, but either (1) the call // hasn't started yet, or (2) the call has ended and we're // showing the success/failure screen. In either of these // cases it's OK to make a new outgoing call, but we need // to take down any OTASP-related UI first. if (dialogState) app.dismissOtaDialogs(); app.clearOtaState(); } else if (isOtaCallActive) { // The actual OTASP call is active. Don't allow new // outgoing calls at all from this state. Log.w(TAG, "OTASP call is active: disallowing a new outgoing call."); return false; } } if (number == null) { if (DBG) Log.v(TAG, "CALL cancelled (null number), returning..."); return false; } else if (TelephonyCapabilities.supportsOtasp(app.phone) && (app.phone.getState() != PhoneConstants.State.IDLE) && (app.phone.isOtaSpNumber(number))) { if (DBG) Log.v(TAG, "Call is active, a 2nd OTA call cancelled -- returning."); return false; } else if (PhoneNumberUtils.isPotentialLocalEmergencyNumber(number, context)) { // Just like 3rd-party apps aren't allowed to place emergency // calls via the ACTION_CALL intent, we also don't allow 3rd // party apps to use the NEW_OUTGOING_CALL broadcast to rewrite // an outgoing call into an emergency number. Log.w(TAG, "Cannot modify outgoing call to emergency number " + number + "."); return false; } originalUri = intent.getStringExtra( OutgoingCallBroadcaster.EXTRA_ORIGINAL_URI); if (originalUri == null) { Log.e(TAG, "Intent is missing EXTRA_ORIGINAL_URI -- returning."); return false; } Uri uri = Uri.parse(originalUri); // We already called convertKeypadLettersToDigits() and // stripSeparators() way back in onCreate(), before we sent out the // NEW_OUTGOING_CALL broadcast. But we need to do it again here // too, since the number might have been modified/rewritten during // the broadcast (and may now contain letters or separators again.) number = PhoneNumberUtils.convertKeypadLettersToDigits(number); number = PhoneNumberUtils.stripSeparators(number); if (DBG) Log.v(TAG, "doReceive: proceeding with call..."); if (VDBG) Log.v(TAG, "- uri: " + uri); if (VDBG) Log.v(TAG, "- actual number to dial: '" + number + "'"); startSipCallOptionHandler(context, intent, uri, number); return true; } } /** * Launch the SipCallOptionHandler, which is the next step(*) in the * outgoing-call sequence after the outgoing call broadcast is * complete. * * (*) We now know exactly what phone number we need to dial, so the next * step is for the SipCallOptionHandler to decide which Phone type (SIP * or PSTN) should be used. (Depending on the user's preferences, this * decision may also involve popping up a dialog to ask the user to * choose what type of call this should be.) * * @param context used for the startActivity() call * * @param intent the intent from the previous step of the outgoing-call * sequence. Normally this will be the NEW_OUTGOING_CALL broadcast intent * that came in to the OutgoingCallReceiver, although it can also be the * original ACTION_CALL intent that started the whole sequence (in cases * where we don't do the NEW_OUTGOING_CALL broadcast at all, like for * emergency numbers or SIP addresses). * * @param uri the data URI from the original CALL intent, presumably either * a tel: or sip: URI. For tel: URIs, note that the scheme-specific part * does *not* necessarily have separators and keypad letters stripped (so * we might see URIs like "tel:(650)%20555-1234" or "tel:1-800-GOOG-411" * here.) * * @param number the actual number (or SIP address) to dial. This is * guaranteed to be either a PSTN phone number with separators stripped * out and keypad letters converted to digits (like "16505551234"), or a * raw SIP address (like "[email protected]"). */ private void startSipCallOptionHandler(Context context, Intent intent, Uri uri, String number) { if (VDBG) { Log.i(TAG, "startSipCallOptionHandler..."); Log.i(TAG, "- intent: " + intent); Log.i(TAG, "- uri: " + uri); Log.i(TAG, "- number: " + number); } // Create a copy of the original CALL intent that started the whole // outgoing-call sequence. This intent will ultimately be passed to // CallController.placeCall() after the SipCallOptionHandler step. Intent newIntent = new Intent(Intent.ACTION_CALL, uri); newIntent.putExtra(EXTRA_ACTUAL_NUMBER_TO_DIAL, number); CallGatewayManager.checkAndCopyPhoneProviderExtras(intent, newIntent); // Finally, launch the SipCallOptionHandler, with the copy of the // original CALL intent stashed away in the EXTRA_NEW_CALL_INTENT // extra. Intent selectPhoneIntent = new Intent(ACTION_SIP_SELECT_PHONE, uri); selectPhoneIntent.setClass(context, SipCallOptionHandler.class); selectPhoneIntent.putExtra(EXTRA_NEW_CALL_INTENT, newIntent); selectPhoneIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (DBG) { Log.v(TAG, "startSipCallOptionHandler(): " + "calling startActivity: " + selectPhoneIntent); } context.startActivity(selectPhoneIntent); // ...and see SipCallOptionHandler.onCreate() for the next step of the sequence. } /** * This method is the single point of entry for the CALL intent, which is used (by built-in * apps like Contacts / Dialer, as well as 3rd-party apps) to initiate an outgoing voice call. * * */ @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.outgoing_call_broadcaster); mWaitingSpinner = (ProgressBar) findViewById(R.id.spinner); Intent intent = getIntent(); if (DBG) { final Configuration configuration = getResources().getConfiguration(); Log.v(TAG, "onCreate: this = " + this + ", icicle = " + icicle); Log.v(TAG, " - getIntent() = " + intent); Log.v(TAG, " - configuration = " + configuration); } if (icicle != null) { // A non-null icicle means that this activity is being // re-initialized after previously being shut down. // // In practice this happens very rarely (because the lifetime // of this activity is so short!), but it *can* happen if the // framework detects a configuration change at exactly the // right moment; see bug 2202413. // // In this case, do nothing. Our onCreate() method has already // run once (with icicle==null the first time), which means // that the NEW_OUTGOING_CALL broadcast for this new call has // already been sent. Log.i(TAG, "onCreate: non-null icicle! " + "Bailing out, not sending NEW_OUTGOING_CALL broadcast..."); // No need to finish() here, since the OutgoingCallReceiver from // our original instance will do that. (It'll actually call // finish() on our original instance, which apparently works fine // even though the ActivityManager has already shut that instance // down. And note that if we *do* call finish() here, that just // results in an "ActivityManager: Duplicate finish request" // warning when the OutgoingCallReceiver runs.) return; } processIntent(intent); // isFinishing() return false when 1. broadcast is still ongoing, or 2. dialog is being // shown. Otherwise finish() is called inside processIntent(), is isFinishing() here will // return true. if (DBG) Log.v(TAG, "At the end of onCreate(). isFinishing(): " + isFinishing()); } /** * Interprets a given Intent and starts something relevant to the Intent. * * This method will handle three kinds of actions: * * - CALL (action for usual outgoing voice calls) * - CALL_PRIVILEGED (can come from built-in apps like contacts / voice dialer / bluetooth) * - CALL_EMERGENCY (from the EmergencyDialer that's reachable from the lockscreen.) * * The exact behavior depends on the intent's data: * * - The most typical is a tel: URI, which we handle by starting the * NEW_OUTGOING_CALL broadcast. That broadcast eventually triggers * the sequence OutgoingCallReceiver -> SipCallOptionHandler -> * InCallScreen. * * - Or, with a sip: URI we skip the NEW_OUTGOING_CALL broadcast and * go directly to SipCallOptionHandler, which then leads to the * InCallScreen. * * - voicemail: URIs take the same path as regular tel: URIs. * * Other special cases: * * - Outgoing calls are totally disallowed on non-voice-capable * devices (see handleNonVoiceCapable()). * * - A CALL intent with the EXTRA_SEND_EMPTY_FLASH extra (and * presumably no data at all) means "send an empty flash" (which * is only meaningful on CDMA devices while a call is already * active.) * */ private void processIntent(Intent intent) { if (DBG) { Log.v(TAG, "processIntent() = " + intent + ", thread: " + Thread.currentThread()); } final Configuration configuration = getResources().getConfiguration(); // Outgoing phone calls are only allowed on "voice-capable" devices. if (!PhoneGlobals.sVoiceCapable) { Log.i(TAG, "This device is detected as non-voice-capable device."); handleNonVoiceCapable(intent); return; } String action = intent.getAction(); String number = PhoneNumberUtils.getNumberFromIntent(intent, this); // Check the number, don't convert for sip uri // TODO put uriNumber under PhoneNumberUtils if (number != null) { if (!PhoneNumberUtils.isUriNumber(number)) { number = PhoneNumberUtils.convertKeypadLettersToDigits(number); number = PhoneNumberUtils.stripSeparators(number); } } else { Log.w(TAG, "The number obtained from Intent is null."); } AppOpsManager appOps = (AppOpsManager)getSystemService(Context.APP_OPS_SERVICE); int launchedFromUid; String launchedFromPackage; try { launchedFromUid = ActivityManagerNative.getDefault().getLaunchedFromUid( getActivityToken()); launchedFromPackage = ActivityManagerNative.getDefault().getLaunchedFromPackage( getActivityToken()); } catch (RemoteException e) { launchedFromUid = -1; launchedFromPackage = null; } if (appOps.noteOp(AppOpsManager.OP_CALL_PHONE, launchedFromUid, launchedFromPackage) != AppOpsManager.MODE_ALLOWED) { Log.w(TAG, "Rejecting call from uid " + launchedFromUid + " package " + launchedFromPackage); finish(); return; } // If true, this flag will indicate that the current call is a special kind // of call (most likely an emergency number) that 3rd parties aren't allowed // to intercept or affect in any way. (In that case, we start the call // immediately rather than going through the NEW_OUTGOING_CALL sequence.) boolean callNow; if (getClass().getName().equals(intent.getComponent().getClassName())) { // If we were launched directly from the OutgoingCallBroadcaster, // not one of its more privileged aliases, then make sure that // only the non-privileged actions are allowed. if (!Intent.ACTION_CALL.equals(intent.getAction())) { Log.w(TAG, "Attempt to deliver non-CALL action; forcing to CALL"); intent.setAction(Intent.ACTION_CALL); } } // Check whether or not this is an emergency number, in order to // enforce the restriction that only the CALL_PRIVILEGED and // CALL_EMERGENCY intents are allowed to make emergency calls. // // (Note that the ACTION_CALL check below depends on the result of // isPotentialLocalEmergencyNumber() rather than just plain // isLocalEmergencyNumber(), to be 100% certain that we *don't* // allow 3rd party apps to make emergency calls by passing in an // "invalid" number like "9111234" that isn't technically an // emergency number but might still result in an emergency call // with some networks.) final boolean isExactEmergencyNumber = (number != null) && PhoneNumberUtils.isLocalEmergencyNumber(number, this); final boolean isPotentialEmergencyNumber = (number != null) && PhoneNumberUtils.isPotentialLocalEmergencyNumber(number, this); if (VDBG) { Log.v(TAG, " - Checking restrictions for number '" + number + "':"); Log.v(TAG, " isExactEmergencyNumber = " + isExactEmergencyNumber); Log.v(TAG, " isPotentialEmergencyNumber = " + isPotentialEmergencyNumber); } /* Change CALL_PRIVILEGED into CALL or CALL_EMERGENCY as needed. */ // TODO: This code is redundant with some code in InCallScreen: refactor. if (Intent.ACTION_CALL_PRIVILEGED.equals(action)) { // We're handling a CALL_PRIVILEGED intent, so we know this request came // from a trusted source (like the built-in dialer.) So even a number // that's *potentially* an emergency number can safely be promoted to // CALL_EMERGENCY (since we *should* allow you to dial "91112345" from // the dialer if you really want to.) if (isPotentialEmergencyNumber) { Log.i(TAG, "ACTION_CALL_PRIVILEGED is used while the number is a potential" + " emergency number. Use ACTION_CALL_EMERGENCY as an action instead."); action = Intent.ACTION_CALL_EMERGENCY; } else { action = Intent.ACTION_CALL; } if (DBG) Log.v(TAG, " - updating action from CALL_PRIVILEGED to " + action); intent.setAction(action); } if (Intent.ACTION_CALL.equals(action)) { if (isPotentialEmergencyNumber) { Log.w(TAG, "Cannot call potential emergency number '" + number + "' with CALL Intent " + intent + "."); Log.i(TAG, "Launching default dialer instead..."); Intent invokeFrameworkDialer = new Intent(); // TwelveKeyDialer is in a tab so we really want // DialtactsActivity. Build the intent 'manually' to // use the java resolver to find the dialer class (as // opposed to a Context which look up known android // packages only) final Resources resources = getResources(); invokeFrameworkDialer.setClassName( resources.getString(R.string.ui_default_package), resources.getString(R.string.dialer_default_class)); invokeFrameworkDialer.setAction(Intent.ACTION_DIAL); invokeFrameworkDialer.setData(intent.getData()); if (DBG) Log.v(TAG, "onCreate(): calling startActivity for Dialer: " + invokeFrameworkDialer); startActivity(invokeFrameworkDialer); finish(); return; } callNow = false; } else if (Intent.ACTION_CALL_EMERGENCY.equals(action)) { // ACTION_CALL_EMERGENCY case: this is either a CALL_PRIVILEGED // intent that we just turned into a CALL_EMERGENCY intent (see // above), or else it really is an CALL_EMERGENCY intent that // came directly from some other app (e.g. the EmergencyDialer // activity built in to the Phone app.) // Make sure it's at least *possible* that this is really an // emergency number. if (!isPotentialEmergencyNumber) { Log.w(TAG, "Cannot call non-potential-emergency number " + number + " with EMERGENCY_CALL Intent " + intent + "." + " Finish the Activity immediately."); finish(); return; } callNow = true; } else { Log.e(TAG, "Unhandled Intent " + intent + ". Finish the Activity immediately."); finish(); return; } // Make sure the screen is turned on. This is probably the right // thing to do, and more importantly it works around an issue in the // activity manager where we will not launch activities consistently // when the screen is off (since it is trying to keep them paused // and has... issues). // // Also, this ensures the device stays awake while doing the following // broadcast; technically we should be holding a wake lock here // as well. PhoneGlobals.getInstance().wakeUpScreen(); // If number is null, we're probably trying to call a non-existent voicemail number, // send an empty flash or something else is fishy. Whatever the problem, there's no // number, so there's no point in allowing apps to modify the number. if (TextUtils.isEmpty(number)) { if (intent.getBooleanExtra(EXTRA_SEND_EMPTY_FLASH, false)) { Log.i(TAG, "onCreate: SEND_EMPTY_FLASH..."); PhoneUtils.sendEmptyFlash(PhoneGlobals.getPhone()); finish(); return; } else { Log.i(TAG, "onCreate: null or empty number, setting callNow=true..."); callNow = true; } } if (callNow) { // This is a special kind of call (most likely an emergency number) // that 3rd parties aren't allowed to intercept or affect in any way. // So initiate the outgoing call immediately. Log.i(TAG, "onCreate(): callNow case! Calling placeCall(): " + intent); // Initiate the outgoing call, and simultaneously launch the // InCallScreen to display the in-call UI: PhoneGlobals.getInstance().callController.placeCall(intent); // Note we do *not* "return" here, but instead continue and // send the ACTION_NEW_OUTGOING_CALL broadcast like for any // other outgoing call. (But when the broadcast finally // reaches the OutgoingCallReceiver, we'll know not to // initiate the call again because of the presence of the // EXTRA_ALREADY_CALLED extra.) } // For now, SIP calls will be processed directly without a // NEW_OUTGOING_CALL broadcast. // // TODO: In the future, though, 3rd party apps *should* be allowed to // intercept outgoing calls to SIP addresses as well. To do this, we should // (1) update the NEW_OUTGOING_CALL intent documentation to explain this // case, and (2) pass the outgoing SIP address by *not* overloading the // EXTRA_PHONE_NUMBER extra, but instead using a new separate extra to hold // the outgoing SIP address. (Be sure to document whether it's a URI or just // a plain address, whether it could be a tel: URI, etc.) Uri uri = intent.getData(); String scheme = uri.getScheme(); if (Constants.SCHEME_SIP.equals(scheme) || PhoneNumberUtils.isUriNumber(number)) { Log.i(TAG, "The requested number was detected as SIP call."); startSipCallOptionHandler(this, intent, uri, number); finish(); return; // TODO: if there's ever a way for SIP calls to trigger a // "callNow=true" case (see above), we'll need to handle that // case here too (most likely by just doing nothing at all.) } Intent broadcastIntent = new Intent(Intent.ACTION_NEW_OUTGOING_CALL); if (number != null) { broadcastIntent.putExtra(Intent.EXTRA_PHONE_NUMBER, number); } CallGatewayManager.checkAndCopyPhoneProviderExtras(intent, broadcastIntent); broadcastIntent.putExtra(EXTRA_ALREADY_CALLED, callNow); broadcastIntent.putExtra(EXTRA_ORIGINAL_URI, uri.toString()); // Need to raise foreground in-call UI as soon as possible while allowing 3rd party app // to intercept the outgoing call. broadcastIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); if (DBG) Log.v(TAG, " - Broadcasting intent: " + broadcastIntent + "."); // Set a timer so that we can prepare for unexpected delay introduced by the broadcast. // If it takes too much time, the timer will show "waiting" spinner. // This message will be removed when OutgoingCallReceiver#onReceive() is called before the // timeout. mHandler.sendEmptyMessageDelayed(EVENT_OUTGOING_CALL_TIMEOUT, OUTGOING_CALL_TIMEOUT_THRESHOLD); sendOrderedBroadcastAsUser(broadcastIntent, UserHandle.OWNER, PERMISSION, new OutgoingCallReceiver(), null, // scheduler Activity.RESULT_OK, // initialCode number, // initialData: initial value for the result data null); // initialExtras } @Override protected void onStop() { // Clean up (and dismiss if necessary) any managed dialogs. // // We don't do this in onPause() since we can be paused/resumed // due to orientation changes (in which case we don't want to // disturb the dialog), but we *do* need it here in onStop() to be // sure we clean up if the user hits HOME while the dialog is up. // // Note it's safe to call removeDialog() even if there's no dialog // associated with that ID. removeDialog(DIALOG_NOT_VOICE_CAPABLE); super.onStop(); } /** * Handle the specified CALL or CALL_* intent on a non-voice-capable * device. * * This method may launch a different intent (if there's some useful * alternative action to take), or otherwise display an error dialog, * and in either case will finish() the current activity when done. */ private void handleNonVoiceCapable(Intent intent) { if (DBG) Log.v(TAG, "handleNonVoiceCapable: handling " + intent + " on non-voice-capable device..."); // Just show a generic "voice calling not supported" dialog. showDialog(DIALOG_NOT_VOICE_CAPABLE); // ...and we'll eventually finish() when the user dismisses // or cancels the dialog. } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; switch(id) { case DIALOG_NOT_VOICE_CAPABLE: dialog = new AlertDialog.Builder(this) .setTitle(R.string.not_voice_capable) .setIconAttribute(android.R.attr.alertDialogIcon) .setPositiveButton(android.R.string.ok, this) .setOnCancelListener(this) .create(); break; default: Log.w(TAG, "onCreateDialog: unexpected ID " + id); dialog = null; break; } return dialog; } /** DialogInterface.OnClickListener implementation */ @Override public void onClick(DialogInterface dialog, int id) { // DIALOG_NOT_VOICE_CAPABLE is the only dialog we ever use (so far // at least), and its only button is "OK". finish(); } /** DialogInterface.OnCancelListener implementation */ @Override public void onCancel(DialogInterface dialog) { // DIALOG_NOT_VOICE_CAPABLE is the only dialog we ever use (so far // at least), and canceling it is just like hitting "OK". finish(); } /** * Implement onConfigurationChanged() purely for debugging purposes, * to make sure that the android:configChanges element in our manifest * is working properly. */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (DBG) Log.v(TAG, "onConfigurationChanged: newConfig = " + newConfig); } }
am 069a51d6: am a7eadfa5: am 468aefd4: am 829b26ee: Fix issue #11965706: Calls using IntentChooser are now Broken in 4.3 and 4.4 * commit '069a51d65c2295cd1677f8bec79a82365ce8a9e7': Fix issue #11965706: Calls using IntentChooser are now Broken in 4.3 and 4.4
src/com/android/phone/OutgoingCallBroadcaster.java
am 069a51d6: am a7eadfa5: am 468aefd4: am 829b26ee: Fix issue #11965706: Calls using IntentChooser are now Broken in 4.3 and 4.4
Java
apache-2.0
b04cce1638f6a79217e7258a47cbd90f0c9b86f4
0
smartnews/presto,smartnews/presto,smartnews/presto,smartnews/presto,smartnews/presto
/* * 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.trino.plugin.singlestore; import com.google.common.collect.ImmutableSet; import io.trino.plugin.jdbc.BaseJdbcClient; import io.trino.plugin.jdbc.BaseJdbcConfig; import io.trino.plugin.jdbc.ColumnMapping; import io.trino.plugin.jdbc.ConnectionFactory; import io.trino.plugin.jdbc.JdbcColumnHandle; import io.trino.plugin.jdbc.JdbcJoinCondition; import io.trino.plugin.jdbc.JdbcSortItem; import io.trino.plugin.jdbc.JdbcTableHandle; import io.trino.plugin.jdbc.JdbcTypeHandle; import io.trino.plugin.jdbc.LongReadFunction; import io.trino.plugin.jdbc.LongWriteFunction; import io.trino.plugin.jdbc.PreparedQuery; import io.trino.plugin.jdbc.QueryBuilder; import io.trino.plugin.jdbc.WriteMapping; import io.trino.plugin.jdbc.mapping.IdentifierMapping; import io.trino.spi.TrinoException; import io.trino.spi.connector.AggregateFunction; import io.trino.spi.connector.ColumnHandle; import io.trino.spi.connector.ConnectorSession; import io.trino.spi.connector.JoinCondition; import io.trino.spi.connector.JoinStatistics; import io.trino.spi.connector.JoinType; import io.trino.spi.connector.SchemaTableName; import io.trino.spi.type.CharType; import io.trino.spi.type.DecimalType; import io.trino.spi.type.Decimals; import io.trino.spi.type.StandardTypes; import io.trino.spi.type.TimeType; import io.trino.spi.type.TimestampType; import io.trino.spi.type.Type; import io.trino.spi.type.TypeManager; import io.trino.spi.type.TypeSignature; import io.trino.spi.type.VarcharType; import javax.inject.Inject; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiFunction; import java.util.regex.Pattern; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Verify.verify; import static io.airlift.slice.Slices.utf8Slice; import static io.trino.plugin.base.util.JsonTypeUtil.jsonParse; import static io.trino.plugin.jdbc.DecimalConfig.DecimalMapping.ALLOW_OVERFLOW; import static io.trino.plugin.jdbc.DecimalSessionSessionProperties.getDecimalDefaultScale; import static io.trino.plugin.jdbc.DecimalSessionSessionProperties.getDecimalRounding; import static io.trino.plugin.jdbc.DecimalSessionSessionProperties.getDecimalRoundingMode; import static io.trino.plugin.jdbc.JdbcErrorCode.JDBC_ERROR; import static io.trino.plugin.jdbc.PredicatePushdownController.DISABLE_PUSHDOWN; import static io.trino.plugin.jdbc.StandardColumnMappings.bigintColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.bigintWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.booleanColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.booleanWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.charWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.dateReadFunctionUsingLocalDate; import static io.trino.plugin.jdbc.StandardColumnMappings.decimalColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.defaultCharColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.defaultVarcharColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.doubleColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.doubleWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.integerColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.integerWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.longDecimalWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.realWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.shortDecimalWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.smallintColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.smallintWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.timeWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.timestampColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.timestampWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.tinyintColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.tinyintWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.varbinaryColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.varbinaryWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.varcharWriteFunction; import static io.trino.plugin.jdbc.TypeHandlingJdbcSessionProperties.getUnsupportedTypeHandling; import static io.trino.plugin.jdbc.UnsupportedTypeHandling.CONVERT_TO_VARCHAR; import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED; import static io.trino.spi.type.BigintType.BIGINT; import static io.trino.spi.type.BooleanType.BOOLEAN; import static io.trino.spi.type.DateType.DATE; import static io.trino.spi.type.DecimalType.createDecimalType; import static io.trino.spi.type.DoubleType.DOUBLE; import static io.trino.spi.type.IntegerType.INTEGER; import static io.trino.spi.type.RealType.REAL; import static io.trino.spi.type.SmallintType.SMALLINT; import static io.trino.spi.type.TimeType.createTimeType; import static io.trino.spi.type.TimestampType.TIMESTAMP_MICROS; import static io.trino.spi.type.TimestampType.createTimestampType; import static io.trino.spi.type.Timestamps.NANOSECONDS_PER_DAY; import static io.trino.spi.type.Timestamps.PICOSECONDS_PER_DAY; import static io.trino.spi.type.Timestamps.PICOSECONDS_PER_NANOSECOND; import static io.trino.spi.type.Timestamps.round; import static io.trino.spi.type.TinyintType.TINYINT; import static io.trino.spi.type.VarbinaryType.VARBINARY; import static java.lang.Float.floatToRawIntBits; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.String.format; import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class SingleStoreClient extends BaseJdbcClient { static final int MEMSQL_DATE_TIME_MAX_PRECISION = 6; static final int MEMSQL_VARCHAR_MAX_LENGTH = 21844; static final int MEMSQL_TEXT_MAX_LENGTH = 65535; static final int MEMSQL_MEDIUMTEXT_MAX_LENGTH = 16777215; // Singlestore driver returns width of timestamp types instead of precision. // 19 characters are used for zero-precision timestamps while others // require 19 + precision + 1 characters with the additional character for decimal separator private static final int ZERO_PRECISION_TIMESTAMP_COLUMN_SIZE = 19; // Singlestore driver returns width of time types instead of precision, same as the above timestamp type. // 10 characters are used for zero-precision time private static final int ZERO_PRECISION_TIME_COLUMN_SIZE = 10; private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("uuuu-MM-dd"); private static final Pattern UNSIGNED_TYPE_REGEX = Pattern.compile("(?i).*unsigned$"); private final Type jsonType; @Inject public SingleStoreClient(BaseJdbcConfig config, ConnectionFactory connectionFactory, QueryBuilder queryBuilder, TypeManager typeManager, IdentifierMapping identifierMapping) { super(config, "`", connectionFactory, queryBuilder, identifierMapping); requireNonNull(typeManager, "typeManager is null"); this.jsonType = typeManager.getType(new TypeSignature(StandardTypes.JSON)); } @Override public boolean supportsAggregationPushdown(ConnectorSession session, JdbcTableHandle table, List<AggregateFunction> aggregates, Map<String, ColumnHandle> assignments, List<List<ColumnHandle>> groupingSets) { // Remote database can be case insensitive. return preventTextualTypeAggregationPushdown(groupingSets); } @Override public Collection<String> listSchemas(Connection connection) { // for MemSQL, we need to list catalogs instead of schemas try (ResultSet resultSet = connection.getMetaData().getCatalogs()) { ImmutableSet.Builder<String> schemaNames = ImmutableSet.builder(); while (resultSet.next()) { String schemaName = resultSet.getString("TABLE_CAT"); // skip internal schemas if (filterSchema(schemaName)) { schemaNames.add(schemaName); } } return schemaNames.build(); } catch (SQLException e) { throw new RuntimeException(e); } } @Override protected boolean filterSchema(String schemaName) { if (schemaName.equalsIgnoreCase("memsql")) { return false; } return super.filterSchema(schemaName); } @Override public Optional<ColumnMapping> toColumnMapping(ConnectorSession session, Connection connection, JdbcTypeHandle typeHandle) { String jdbcTypeName = typeHandle.getJdbcTypeName() .orElseThrow(() -> new TrinoException(JDBC_ERROR, "Type name is missing: " + typeHandle)); Optional<ColumnMapping> mapping = getForcedMappingToVarchar(typeHandle); if (mapping.isPresent()) { return mapping; } Optional<ColumnMapping> unsignedMapping = getUnsignedMapping(typeHandle); if (unsignedMapping.isPresent()) { return unsignedMapping; } if (jdbcTypeName.equalsIgnoreCase("json")) { return Optional.of(jsonColumnMapping()); } switch (typeHandle.getJdbcType()) { case Types.BIT: case Types.BOOLEAN: return Optional.of(booleanColumnMapping()); case Types.TINYINT: return Optional.of(tinyintColumnMapping()); case Types.SMALLINT: return Optional.of(smallintColumnMapping()); case Types.INTEGER: return Optional.of(integerColumnMapping()); case Types.BIGINT: return Optional.of(bigintColumnMapping()); case Types.REAL: // Disable pushdown because floating-point values are approximate and not stored as exact values, // attempts to treat them as exact in comparisons may lead to problems return Optional.of(ColumnMapping.longMapping( REAL, (resultSet, columnIndex) -> floatToRawIntBits(resultSet.getFloat(columnIndex)), realWriteFunction(), DISABLE_PUSHDOWN)); case Types.DOUBLE: return Optional.of(doubleColumnMapping()); case Types.CHAR: case Types.NCHAR: // TODO it it is dummy copied from StandardColumnMappings, verify if it is proper mapping return Optional.of(defaultCharColumnMapping(typeHandle.getRequiredColumnSize(), false)); case Types.VARCHAR: case Types.LONGVARCHAR: return Optional.of(defaultVarcharColumnMapping(typeHandle.getRequiredColumnSize(), false)); case Types.DECIMAL: int precision = typeHandle.getRequiredColumnSize(); int decimalDigits = typeHandle.getRequiredDecimalDigits(); if (getDecimalRounding(session) == ALLOW_OVERFLOW && precision > Decimals.MAX_PRECISION) { int scale = min(decimalDigits, getDecimalDefaultScale(session)); return Optional.of(decimalColumnMapping(createDecimalType(Decimals.MAX_PRECISION, scale), getDecimalRoundingMode(session))); } if (precision > Decimals.MAX_PRECISION) { break; } return Optional.of(decimalColumnMapping(createDecimalType(precision, max(decimalDigits, 0)))); case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: return Optional.of(varbinaryColumnMapping()); case Types.DATE: return Optional.of(ColumnMapping.longMapping( DATE, dateReadFunctionUsingLocalDate(), dateWriteFunction())); case Types.TIME: TimeType timeType = createTimeType(getTimePrecision(typeHandle.getRequiredColumnSize())); return Optional.of(ColumnMapping.longMapping( timeType, memsqlTimeReadFunction(timeType), timeWriteFunction(timeType.getPrecision()))); case Types.TIMESTAMP: // TODO (https://github.com/trinodb/trino/issues/5450) Fix DST handling TimestampType timestampType = createTimestampType(getTimestampPrecision(typeHandle.getRequiredColumnSize())); return Optional.of(timestampColumnMapping(timestampType)); } if (getUnsupportedTypeHandling(session) == CONVERT_TO_VARCHAR) { return mapToUnboundedVarchar(typeHandle); } return Optional.empty(); } private static int getTimePrecision(int timeColumnSize) { if (timeColumnSize == ZERO_PRECISION_TIME_COLUMN_SIZE) { return 0; } int timePrecision = timeColumnSize - ZERO_PRECISION_TIME_COLUMN_SIZE - 1; verify(1 <= timePrecision && timePrecision <= MEMSQL_DATE_TIME_MAX_PRECISION, "Unexpected time precision %s calculated from time column size %s", timePrecision, timeColumnSize); return timePrecision; } private static int getTimestampPrecision(int timestampColumnSize) { if (timestampColumnSize == ZERO_PRECISION_TIMESTAMP_COLUMN_SIZE) { return 0; } int timestampPrecision = timestampColumnSize - ZERO_PRECISION_TIMESTAMP_COLUMN_SIZE - 1; verify(1 <= timestampPrecision && timestampPrecision <= MEMSQL_DATE_TIME_MAX_PRECISION, "Unexpected timestamp precision %s calculated from timestamp column size %s", timestampPrecision, timestampColumnSize); return timestampPrecision; } @Override public ResultSet getTables(Connection connection, Optional<String> schemaName, Optional<String> tableName) throws SQLException { // MemSQL maps their "database" to SQL catalogs and does not have schemas DatabaseMetaData metadata = connection.getMetaData(); return metadata.getTables( schemaName.orElse(null), null, escapeNamePattern(tableName, metadata.getSearchStringEscape()).orElse(null), getTableTypes().map(types -> types.toArray(String[]::new)).orElse(null)); } @Override public void renameTable(ConnectorSession session, JdbcTableHandle handle, SchemaTableName newTableName) { verify(handle.getSchemaName() == null); String catalogName = handle.getCatalogName(); if (catalogName != null && !catalogName.equalsIgnoreCase(newTableName.getSchemaName())) { throw new TrinoException(NOT_SUPPORTED, "This connector does not support renaming tables across schemas"); } // MemSQL doesn't support specifying the catalog name in a rename. By setting the // catalogName parameter to null, it will be omitted in the ALTER TABLE statement. renameTable(session, null, handle.getCatalogName(), handle.getTableName(), newTableName); } @Override public void renameColumn(ConnectorSession session, JdbcTableHandle handle, JdbcColumnHandle jdbcColumn, String newColumnName) { try (Connection connection = connectionFactory.openConnection(session)) { String newRemoteColumnName = getIdentifierMapping().toRemoteColumnName(connection, newColumnName); // MemSQL versions earlier than 5.7 do not support the CHANGE syntax String sql = format( "ALTER TABLE %s CHANGE %s %s", quoted(handle.getCatalogName(), handle.getSchemaName(), handle.getTableName()), quoted(jdbcColumn.getColumnName()), quoted(newRemoteColumnName)); execute(connection, sql); } catch (SQLException e) { throw new TrinoException(JDBC_ERROR, e); } } @Override public void renameSchema(ConnectorSession session, String schemaName, String newSchemaName) { throw new TrinoException(NOT_SUPPORTED, "This connector does not support renaming schemas"); } @Override protected String getTableSchemaName(ResultSet resultSet) throws SQLException { // MemSQL uses catalogs instead of schemas return resultSet.getString("TABLE_CAT"); } @Override public WriteMapping toWriteMapping(ConnectorSession session, Type type) { if (type == BOOLEAN) { return WriteMapping.booleanMapping("boolean", booleanWriteFunction()); } if (type == TINYINT) { return WriteMapping.longMapping("tinyint", tinyintWriteFunction()); } if (type == SMALLINT) { return WriteMapping.longMapping("smallint", smallintWriteFunction()); } if (type == INTEGER) { return WriteMapping.longMapping("integer", integerWriteFunction()); } if (type == BIGINT) { return WriteMapping.longMapping("bigint", bigintWriteFunction()); } if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; String dataType = format("decimal(%s, %s)", decimalType.getPrecision(), decimalType.getScale()); if (decimalType.isShort()) { return WriteMapping.longMapping(dataType, shortDecimalWriteFunction(decimalType)); } return WriteMapping.objectMapping(dataType, longDecimalWriteFunction(decimalType)); } if (REAL.equals(type)) { return WriteMapping.longMapping("float", realWriteFunction()); } if (type == DOUBLE) { return WriteMapping.doubleMapping("double precision", doubleWriteFunction()); } if (type instanceof CharType) { return WriteMapping.sliceMapping("char(" + ((CharType) type).getLength() + ")", charWriteFunction()); } if (type instanceof VarcharType) { VarcharType varcharType = (VarcharType) type; String dataType; if (varcharType.isUnbounded()) { dataType = "longtext"; } else if (varcharType.getBoundedLength() <= MEMSQL_VARCHAR_MAX_LENGTH) { dataType = "varchar(" + varcharType.getBoundedLength() + ")"; } else if (varcharType.getBoundedLength() <= MEMSQL_TEXT_MAX_LENGTH) { dataType = "text"; } else if (varcharType.getBoundedLength() <= MEMSQL_MEDIUMTEXT_MAX_LENGTH) { dataType = "mediumtext"; } else { dataType = "longtext"; } return WriteMapping.sliceMapping(dataType, varcharWriteFunction()); } if (VARBINARY.equals(type)) { return WriteMapping.sliceMapping("longblob", varbinaryWriteFunction()); } if (type == DATE) { return WriteMapping.longMapping("date", dateWriteFunction()); } if (type instanceof TimeType) { TimeType timeType = (TimeType) type; checkArgument(timeType.getPrecision() <= MEMSQL_DATE_TIME_MAX_PRECISION, "The max time precision in MemSQL is 6"); if (timeType.getPrecision() == 0) { return WriteMapping.longMapping("time", timeWriteFunction(0)); } return WriteMapping.longMapping("time(6)", timeWriteFunction(6)); } // TODO implement TIME type if (type instanceof TimestampType) { TimestampType timestampType = (TimestampType) type; checkArgument(timestampType.getPrecision() <= MEMSQL_DATE_TIME_MAX_PRECISION, "The max timestamp precision in MemSQL is 6"); if (timestampType.getPrecision() == 0) { return WriteMapping.longMapping("datetime", timestampWriteFunction(timestampType)); } return WriteMapping.longMapping(format("datetime(%s)", MEMSQL_DATE_TIME_MAX_PRECISION), timestampWriteFunction(TIMESTAMP_MICROS)); } if (type.equals(jsonType)) { return WriteMapping.sliceMapping("json", varcharWriteFunction()); } throw new TrinoException(NOT_SUPPORTED, "Unsupported column type: " + type.getDisplayName()); } @Override protected Optional<BiFunction<String, Long, String>> limitFunction() { return Optional.of((sql, limit) -> sql + " LIMIT " + limit); } @Override public boolean isLimitGuaranteed(ConnectorSession session) { return true; } @Override public boolean supportsTopN(ConnectorSession session, JdbcTableHandle handle, List<JdbcSortItem> sortOrder) { for (JdbcSortItem sortItem : sortOrder) { Type sortItemType = sortItem.getColumn().getColumnType(); if (sortItemType instanceof CharType || sortItemType instanceof VarcharType) { // Remote database can be case insensitive. return false; } } return true; } @Override protected Optional<TopNFunction> topNFunction() { return Optional.of((query, sortItems, limit) -> { String orderBy = sortItems.stream() .flatMap(sortItem -> { String ordering = sortItem.getSortOrder().isAscending() ? "ASC" : "DESC"; String columnSorting = format("%s %s", quoted(sortItem.getColumn().getColumnName()), ordering); switch (sortItem.getSortOrder()) { case ASC_NULLS_FIRST: // In MemSQL ASC implies NULLS FIRST case DESC_NULLS_LAST: // In MemSQL DESC implies NULLS LAST return Stream.of(columnSorting); case ASC_NULLS_LAST: return Stream.of( format("ISNULL(%s) ASC", quoted(sortItem.getColumn().getColumnName())), columnSorting); case DESC_NULLS_FIRST: return Stream.of( format("ISNULL(%s) DESC", quoted(sortItem.getColumn().getColumnName())), columnSorting); } throw new UnsupportedOperationException("Unsupported sort order: " + sortItem.getSortOrder()); }) .collect(joining(", ")); return format("%s ORDER BY %s LIMIT %s", query, orderBy, limit); }); } @Override public boolean isTopNGuaranteed(ConnectorSession session) { return true; } @Override public Optional<PreparedQuery> implementJoin( ConnectorSession session, JoinType joinType, PreparedQuery leftSource, PreparedQuery rightSource, List<JdbcJoinCondition> joinConditions, Map<JdbcColumnHandle, String> rightAssignments, Map<JdbcColumnHandle, String> leftAssignments, JoinStatistics statistics) { if (joinType == JoinType.FULL_OUTER) { // Not supported in MemSQL return Optional.empty(); } return super.implementJoin(session, joinType, leftSource, rightSource, joinConditions, rightAssignments, leftAssignments, statistics); } @Override protected boolean isSupportedJoinCondition(ConnectorSession session, JdbcJoinCondition joinCondition) { if (joinCondition.getOperator() == JoinCondition.Operator.IS_DISTINCT_FROM) { // Not supported in MemSQL return false; } // Remote database can be case insensitive. return Stream.of(joinCondition.getLeftColumn(), joinCondition.getRightColumn()) .map(JdbcColumnHandle::getColumnType) .noneMatch(type -> type instanceof CharType || type instanceof VarcharType); } private static Optional<ColumnMapping> getUnsignedMapping(JdbcTypeHandle typeHandle) { if (typeHandle.getJdbcTypeName().isEmpty()) { return Optional.empty(); } String typeName = typeHandle.getJdbcTypeName().get(); if (UNSIGNED_TYPE_REGEX.matcher(typeName).matches()) { switch (typeHandle.getJdbcType()) { case Types.BIT: return Optional.of(booleanColumnMapping()); case Types.TINYINT: return Optional.of(smallintColumnMapping()); case Types.SMALLINT: return Optional.of(integerColumnMapping()); case Types.INTEGER: return Optional.of(bigintColumnMapping()); case Types.BIGINT: return Optional.of(decimalColumnMapping(createDecimalType(20))); } } return Optional.empty(); } private static LongReadFunction memsqlTimeReadFunction(TimeType timeType) { requireNonNull(timeType, "timeType is null"); checkArgument(timeType.getPrecision() <= 9, "Unsupported type precision: %s", timeType); return (resultSet, columnIndex) -> { // SingleStore JDBC driver wraps time to be within LocalTime range, which results in values which differ from what is stored, so we verify them String timeString = resultSet.getString(columnIndex); try { long nanosOfDay = LocalTime.from(ISO_LOCAL_TIME.parse(timeString)).toNanoOfDay(); verify(nanosOfDay < NANOSECONDS_PER_DAY, "Invalid value of nanosOfDay: %s", nanosOfDay); long picosOfDay = nanosOfDay * PICOSECONDS_PER_NANOSECOND; long rounded = round(picosOfDay, 12 - timeType.getPrecision()); if (rounded == PICOSECONDS_PER_DAY) { rounded = 0; } return rounded; } catch (DateTimeParseException e) { throw new IllegalStateException(format("Supported Trino TIME type range is between 00:00:00 and 23:59:59.999999 but got %s", timeString), e); } }; } private static LongWriteFunction dateWriteFunction() { return (statement, index, day) -> statement.setString(index, DATE_FORMATTER.format(LocalDate.ofEpochDay(day))); } private ColumnMapping jsonColumnMapping() { return ColumnMapping.sliceMapping( jsonType, (resultSet, columnIndex) -> jsonParse(utf8Slice(resultSet.getString(columnIndex))), varcharWriteFunction(), DISABLE_PUSHDOWN); } }
plugin/trino-singlestore/src/main/java/io/trino/plugin/singlestore/SingleStoreClient.java
/* * 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.trino.plugin.singlestore; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import io.airlift.log.Logger; import io.trino.plugin.jdbc.BaseJdbcClient; import io.trino.plugin.jdbc.BaseJdbcConfig; import io.trino.plugin.jdbc.ColumnMapping; import io.trino.plugin.jdbc.ConnectionFactory; import io.trino.plugin.jdbc.JdbcColumnHandle; import io.trino.plugin.jdbc.JdbcJoinCondition; import io.trino.plugin.jdbc.JdbcSortItem; import io.trino.plugin.jdbc.JdbcTableHandle; import io.trino.plugin.jdbc.JdbcTypeHandle; import io.trino.plugin.jdbc.LongReadFunction; import io.trino.plugin.jdbc.LongWriteFunction; import io.trino.plugin.jdbc.PreparedQuery; import io.trino.plugin.jdbc.QueryBuilder; import io.trino.plugin.jdbc.RemoteTableName; import io.trino.plugin.jdbc.UnsupportedTypeHandling; import io.trino.plugin.jdbc.WriteMapping; import io.trino.plugin.jdbc.mapping.IdentifierMapping; import io.trino.spi.TrinoException; import io.trino.spi.connector.AggregateFunction; import io.trino.spi.connector.ColumnHandle; import io.trino.spi.connector.ConnectorSession; import io.trino.spi.connector.JoinCondition; import io.trino.spi.connector.JoinStatistics; import io.trino.spi.connector.JoinType; import io.trino.spi.connector.SchemaTableName; import io.trino.spi.connector.TableNotFoundException; import io.trino.spi.type.CharType; import io.trino.spi.type.DecimalType; import io.trino.spi.type.Decimals; import io.trino.spi.type.StandardTypes; import io.trino.spi.type.TimeType; import io.trino.spi.type.TimestampType; import io.trino.spi.type.Type; import io.trino.spi.type.TypeManager; import io.trino.spi.type.TypeSignature; import io.trino.spi.type.VarcharType; import javax.inject.Inject; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.BiFunction; import java.util.regex.Pattern; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.emptyToNull; import static com.google.common.base.Verify.verify; import static io.airlift.slice.Slices.utf8Slice; import static io.trino.plugin.base.util.JsonTypeUtil.jsonParse; import static io.trino.plugin.jdbc.DecimalConfig.DecimalMapping.ALLOW_OVERFLOW; import static io.trino.plugin.jdbc.DecimalSessionSessionProperties.getDecimalDefaultScale; import static io.trino.plugin.jdbc.DecimalSessionSessionProperties.getDecimalRounding; import static io.trino.plugin.jdbc.DecimalSessionSessionProperties.getDecimalRoundingMode; import static io.trino.plugin.jdbc.JdbcErrorCode.JDBC_ERROR; import static io.trino.plugin.jdbc.PredicatePushdownController.DISABLE_PUSHDOWN; import static io.trino.plugin.jdbc.StandardColumnMappings.bigintColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.bigintWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.booleanColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.booleanWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.charWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.dateReadFunctionUsingLocalDate; import static io.trino.plugin.jdbc.StandardColumnMappings.decimalColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.defaultCharColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.defaultVarcharColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.doubleColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.doubleWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.integerColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.integerWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.longDecimalWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.realWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.shortDecimalWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.smallintColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.smallintWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.timeWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.timestampColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.timestampWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.tinyintColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.tinyintWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.varbinaryColumnMapping; import static io.trino.plugin.jdbc.StandardColumnMappings.varbinaryWriteFunction; import static io.trino.plugin.jdbc.StandardColumnMappings.varcharWriteFunction; import static io.trino.plugin.jdbc.TypeHandlingJdbcSessionProperties.getUnsupportedTypeHandling; import static io.trino.plugin.jdbc.UnsupportedTypeHandling.CONVERT_TO_VARCHAR; import static io.trino.plugin.jdbc.UnsupportedTypeHandling.IGNORE; import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED; import static io.trino.spi.type.BigintType.BIGINT; import static io.trino.spi.type.BooleanType.BOOLEAN; import static io.trino.spi.type.DateType.DATE; import static io.trino.spi.type.DecimalType.createDecimalType; import static io.trino.spi.type.DoubleType.DOUBLE; import static io.trino.spi.type.IntegerType.INTEGER; import static io.trino.spi.type.RealType.REAL; import static io.trino.spi.type.SmallintType.SMALLINT; import static io.trino.spi.type.TimeType.createTimeType; import static io.trino.spi.type.TimestampType.TIMESTAMP_MICROS; import static io.trino.spi.type.TimestampType.createTimestampType; import static io.trino.spi.type.Timestamps.NANOSECONDS_PER_DAY; import static io.trino.spi.type.Timestamps.PICOSECONDS_PER_DAY; import static io.trino.spi.type.Timestamps.PICOSECONDS_PER_NANOSECOND; import static io.trino.spi.type.Timestamps.round; import static io.trino.spi.type.TinyintType.TINYINT; import static io.trino.spi.type.VarbinaryType.VARBINARY; import static java.lang.Float.floatToRawIntBits; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.String.format; import static java.sql.DatabaseMetaData.columnNoNulls; import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class SingleStoreClient extends BaseJdbcClient { private static final Logger log = Logger.get(SingleStoreClient.class); static final int MEMSQL_DATE_TIME_MAX_PRECISION = 6; static final int MEMSQL_VARCHAR_MAX_LENGTH = 21844; static final int MEMSQL_TEXT_MAX_LENGTH = 65535; static final int MEMSQL_MEDIUMTEXT_MAX_LENGTH = 16777215; private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("uuuu-MM-dd"); private static final Pattern UNSIGNED_TYPE_REGEX = Pattern.compile("(?i).*unsigned$"); private final Type jsonType; @Inject public SingleStoreClient(BaseJdbcConfig config, ConnectionFactory connectionFactory, QueryBuilder queryBuilder, TypeManager typeManager, IdentifierMapping identifierMapping) { super(config, "`", connectionFactory, queryBuilder, identifierMapping); requireNonNull(typeManager, "typeManager is null"); this.jsonType = typeManager.getType(new TypeSignature(StandardTypes.JSON)); } @Override public boolean supportsAggregationPushdown(ConnectorSession session, JdbcTableHandle table, List<AggregateFunction> aggregates, Map<String, ColumnHandle> assignments, List<List<ColumnHandle>> groupingSets) { // Remote database can be case insensitive. return preventTextualTypeAggregationPushdown(groupingSets); } @Override public Collection<String> listSchemas(Connection connection) { // for MemSQL, we need to list catalogs instead of schemas try (ResultSet resultSet = connection.getMetaData().getCatalogs()) { ImmutableSet.Builder<String> schemaNames = ImmutableSet.builder(); while (resultSet.next()) { String schemaName = resultSet.getString("TABLE_CAT"); // skip internal schemas if (filterSchema(schemaName)) { schemaNames.add(schemaName); } } return schemaNames.build(); } catch (SQLException e) { throw new RuntimeException(e); } } @Override protected boolean filterSchema(String schemaName) { if (schemaName.equalsIgnoreCase("memsql")) { return false; } return super.filterSchema(schemaName); } @Override public List<JdbcColumnHandle> getColumns(ConnectorSession session, JdbcTableHandle tableHandle) { if (tableHandle.getColumns().isPresent()) { return tableHandle.getColumns().get(); } checkArgument(tableHandle.isNamedRelation(), "Cannot get columns for %s", tableHandle); SchemaTableName schemaTableName = tableHandle.getRequiredNamedRelation().getSchemaTableName(); RemoteTableName remoteTableName = tableHandle.getRequiredNamedRelation().getRemoteTableName(); try (Connection connection = connectionFactory.openConnection(session); ResultSet resultSet = getColumns(tableHandle, connection.getMetaData())) { Map<String, Integer> timestampPrecisions = getTimestampPrecisions(connection, tableHandle); int allColumns = 0; List<JdbcColumnHandle> columns = new ArrayList<>(); while (resultSet.next()) { // skip if table doesn't match expected if (!(Objects.equals(remoteTableName, getRemoteTable(resultSet)))) { continue; } allColumns++; String columnName = resultSet.getString("COLUMN_NAME"); Optional<Integer> decimalDigits = getInteger(resultSet, "DECIMAL_DIGITS"); if (timestampPrecisions.containsKey(columnName)) { decimalDigits = Optional.of(timestampPrecisions.get(columnName)); } JdbcTypeHandle typeHandle = new JdbcTypeHandle( getInteger(resultSet, "DATA_TYPE").orElseThrow(() -> new IllegalStateException("DATA_TYPE is null")), Optional.ofNullable(resultSet.getString("TYPE_NAME")), getInteger(resultSet, "COLUMN_SIZE"), decimalDigits, Optional.empty(), Optional.empty()); Optional<ColumnMapping> columnMapping = toColumnMapping(session, connection, typeHandle); log.debug("Mapping data type of '%s' column '%s': %s mapped to %s", schemaTableName, columnName, typeHandle, columnMapping); // skip unsupported column types boolean nullable = (resultSet.getInt("NULLABLE") != columnNoNulls); Optional<String> comment = Optional.ofNullable(emptyToNull(resultSet.getString("REMARKS"))); if (columnMapping.isPresent()) { columns.add(JdbcColumnHandle.builder() .setColumnName(columnName) .setJdbcTypeHandle(typeHandle) .setColumnType(columnMapping.get().getType()) .setNullable(nullable) .setComment(comment) .build()); } if (columnMapping.isEmpty()) { UnsupportedTypeHandling unsupportedTypeHandling = getUnsupportedTypeHandling(session); verify( unsupportedTypeHandling == IGNORE, "Unsupported type handling is set to %s, but toColumnMapping() returned empty for %s", unsupportedTypeHandling, typeHandle); } } if (columns.isEmpty()) { throw new TableNotFoundException( schemaTableName, format("Table '%s' has no supported columns (all %s columns are not supported)", schemaTableName, allColumns)); } return ImmutableList.copyOf(columns); } catch (SQLException e) { throw new TrinoException(JDBC_ERROR, e); } } private static RemoteTableName getRemoteTable(ResultSet resultSet) throws SQLException { return new RemoteTableName( Optional.ofNullable(resultSet.getString("TABLE_CAT")), Optional.ofNullable(resultSet.getString("TABLE_SCHEM")), resultSet.getString("TABLE_NAME")); } private static Map<String, Integer> getTimestampPrecisions(Connection connection, JdbcTableHandle tableHandle) throws SQLException { // SingleStore JDBC driver doesn't expose timestamp precision when connecting to MemSQL cluster String sql = "" + "SELECT column_name, column_type " + "FROM information_schema.columns " + "WHERE table_schema = ? " + "AND table_name = ? " + "AND column_type IN ('datetime', 'datetime(6)', 'time', 'time(6)', 'timestamp', 'timestamp(6)')"; try (PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, tableHandle.getCatalogName()); statement.setString(2, tableHandle.getTableName()); Map<String, Integer> timestampColumnPrecisions = new HashMap<>(); try (ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { String columnType = resultSet.getString("column_type"); int size = columnType.equals("datetime") || columnType.equals("time") || columnType.equals("timestamp") ? 0 : 6; timestampColumnPrecisions.put(resultSet.getString("column_name"), size); } } return timestampColumnPrecisions; } } @Override public Optional<ColumnMapping> toColumnMapping(ConnectorSession session, Connection connection, JdbcTypeHandle typeHandle) { String jdbcTypeName = typeHandle.getJdbcTypeName() .orElseThrow(() -> new TrinoException(JDBC_ERROR, "Type name is missing: " + typeHandle)); Optional<ColumnMapping> mapping = getForcedMappingToVarchar(typeHandle); if (mapping.isPresent()) { return mapping; } Optional<ColumnMapping> unsignedMapping = getUnsignedMapping(typeHandle); if (unsignedMapping.isPresent()) { return unsignedMapping; } if (jdbcTypeName.equalsIgnoreCase("json")) { return Optional.of(jsonColumnMapping()); } switch (typeHandle.getJdbcType()) { case Types.BIT: case Types.BOOLEAN: return Optional.of(booleanColumnMapping()); case Types.TINYINT: return Optional.of(tinyintColumnMapping()); case Types.SMALLINT: return Optional.of(smallintColumnMapping()); case Types.INTEGER: return Optional.of(integerColumnMapping()); case Types.BIGINT: return Optional.of(bigintColumnMapping()); case Types.REAL: // Disable pushdown because floating-point values are approximate and not stored as exact values, // attempts to treat them as exact in comparisons may lead to problems return Optional.of(ColumnMapping.longMapping( REAL, (resultSet, columnIndex) -> floatToRawIntBits(resultSet.getFloat(columnIndex)), realWriteFunction(), DISABLE_PUSHDOWN)); case Types.DOUBLE: return Optional.of(doubleColumnMapping()); case Types.CHAR: case Types.NCHAR: // TODO it it is dummy copied from StandardColumnMappings, verify if it is proper mapping return Optional.of(defaultCharColumnMapping(typeHandle.getRequiredColumnSize(), false)); case Types.VARCHAR: case Types.LONGVARCHAR: return Optional.of(defaultVarcharColumnMapping(typeHandle.getRequiredColumnSize(), false)); case Types.DECIMAL: int precision = typeHandle.getRequiredColumnSize(); int decimalDigits = typeHandle.getRequiredDecimalDigits(); if (getDecimalRounding(session) == ALLOW_OVERFLOW && precision > Decimals.MAX_PRECISION) { int scale = min(decimalDigits, getDecimalDefaultScale(session)); return Optional.of(decimalColumnMapping(createDecimalType(Decimals.MAX_PRECISION, scale), getDecimalRoundingMode(session))); } if (precision > Decimals.MAX_PRECISION) { break; } return Optional.of(decimalColumnMapping(createDecimalType(precision, max(decimalDigits, 0)))); case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: return Optional.of(varbinaryColumnMapping()); case Types.DATE: return Optional.of(ColumnMapping.longMapping( DATE, dateReadFunctionUsingLocalDate(), dateWriteFunction())); case Types.TIME: TimeType timeType = createTimeType(typeHandle.getRequiredDecimalDigits()); return Optional.of(ColumnMapping.longMapping( timeType, memsqlTimeReadFunction(timeType), timeWriteFunction(timeType.getPrecision()))); case Types.TIMESTAMP: // TODO (https://github.com/trinodb/trino/issues/5450) Fix DST handling TimestampType timestampType = createTimestampType(typeHandle.getRequiredDecimalDigits()); return Optional.of(timestampColumnMapping(timestampType)); } if (getUnsupportedTypeHandling(session) == CONVERT_TO_VARCHAR) { return mapToUnboundedVarchar(typeHandle); } return Optional.empty(); } @Override public ResultSet getTables(Connection connection, Optional<String> schemaName, Optional<String> tableName) throws SQLException { // MemSQL maps their "database" to SQL catalogs and does not have schemas DatabaseMetaData metadata = connection.getMetaData(); return metadata.getTables( schemaName.orElse(null), null, escapeNamePattern(tableName, metadata.getSearchStringEscape()).orElse(null), getTableTypes().map(types -> types.toArray(String[]::new)).orElse(null)); } @Override public void renameTable(ConnectorSession session, JdbcTableHandle handle, SchemaTableName newTableName) { verify(handle.getSchemaName() == null); String catalogName = handle.getCatalogName(); if (catalogName != null && !catalogName.equalsIgnoreCase(newTableName.getSchemaName())) { throw new TrinoException(NOT_SUPPORTED, "This connector does not support renaming tables across schemas"); } // MemSQL doesn't support specifying the catalog name in a rename. By setting the // catalogName parameter to null, it will be omitted in the ALTER TABLE statement. renameTable(session, null, handle.getCatalogName(), handle.getTableName(), newTableName); } @Override public void renameColumn(ConnectorSession session, JdbcTableHandle handle, JdbcColumnHandle jdbcColumn, String newColumnName) { try (Connection connection = connectionFactory.openConnection(session)) { String newRemoteColumnName = getIdentifierMapping().toRemoteColumnName(connection, newColumnName); // MemSQL versions earlier than 5.7 do not support the CHANGE syntax String sql = format( "ALTER TABLE %s CHANGE %s %s", quoted(handle.getCatalogName(), handle.getSchemaName(), handle.getTableName()), quoted(jdbcColumn.getColumnName()), quoted(newRemoteColumnName)); execute(connection, sql); } catch (SQLException e) { throw new TrinoException(JDBC_ERROR, e); } } @Override public void renameSchema(ConnectorSession session, String schemaName, String newSchemaName) { throw new TrinoException(NOT_SUPPORTED, "This connector does not support renaming schemas"); } @Override protected String getTableSchemaName(ResultSet resultSet) throws SQLException { // MemSQL uses catalogs instead of schemas return resultSet.getString("TABLE_CAT"); } @Override public WriteMapping toWriteMapping(ConnectorSession session, Type type) { if (type == BOOLEAN) { return WriteMapping.booleanMapping("boolean", booleanWriteFunction()); } if (type == TINYINT) { return WriteMapping.longMapping("tinyint", tinyintWriteFunction()); } if (type == SMALLINT) { return WriteMapping.longMapping("smallint", smallintWriteFunction()); } if (type == INTEGER) { return WriteMapping.longMapping("integer", integerWriteFunction()); } if (type == BIGINT) { return WriteMapping.longMapping("bigint", bigintWriteFunction()); } if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; String dataType = format("decimal(%s, %s)", decimalType.getPrecision(), decimalType.getScale()); if (decimalType.isShort()) { return WriteMapping.longMapping(dataType, shortDecimalWriteFunction(decimalType)); } return WriteMapping.objectMapping(dataType, longDecimalWriteFunction(decimalType)); } if (REAL.equals(type)) { return WriteMapping.longMapping("float", realWriteFunction()); } if (type == DOUBLE) { return WriteMapping.doubleMapping("double precision", doubleWriteFunction()); } if (type instanceof CharType) { return WriteMapping.sliceMapping("char(" + ((CharType) type).getLength() + ")", charWriteFunction()); } if (type instanceof VarcharType) { VarcharType varcharType = (VarcharType) type; String dataType; if (varcharType.isUnbounded()) { dataType = "longtext"; } else if (varcharType.getBoundedLength() <= MEMSQL_VARCHAR_MAX_LENGTH) { dataType = "varchar(" + varcharType.getBoundedLength() + ")"; } else if (varcharType.getBoundedLength() <= MEMSQL_TEXT_MAX_LENGTH) { dataType = "text"; } else if (varcharType.getBoundedLength() <= MEMSQL_MEDIUMTEXT_MAX_LENGTH) { dataType = "mediumtext"; } else { dataType = "longtext"; } return WriteMapping.sliceMapping(dataType, varcharWriteFunction()); } if (VARBINARY.equals(type)) { return WriteMapping.sliceMapping("longblob", varbinaryWriteFunction()); } if (type == DATE) { return WriteMapping.longMapping("date", dateWriteFunction()); } if (type instanceof TimeType) { TimeType timeType = (TimeType) type; checkArgument(timeType.getPrecision() <= MEMSQL_DATE_TIME_MAX_PRECISION, "The max time precision in MemSQL is 6"); if (timeType.getPrecision() == 0) { return WriteMapping.longMapping("time", timeWriteFunction(0)); } return WriteMapping.longMapping("time(6)", timeWriteFunction(6)); } // TODO implement TIME type if (type instanceof TimestampType) { TimestampType timestampType = (TimestampType) type; checkArgument(timestampType.getPrecision() <= MEMSQL_DATE_TIME_MAX_PRECISION, "The max timestamp precision in MemSQL is 6"); if (timestampType.getPrecision() == 0) { return WriteMapping.longMapping("datetime", timestampWriteFunction(timestampType)); } return WriteMapping.longMapping(format("datetime(%s)", MEMSQL_DATE_TIME_MAX_PRECISION), timestampWriteFunction(TIMESTAMP_MICROS)); } if (type.equals(jsonType)) { return WriteMapping.sliceMapping("json", varcharWriteFunction()); } throw new TrinoException(NOT_SUPPORTED, "Unsupported column type: " + type.getDisplayName()); } @Override protected Optional<BiFunction<String, Long, String>> limitFunction() { return Optional.of((sql, limit) -> sql + " LIMIT " + limit); } @Override public boolean isLimitGuaranteed(ConnectorSession session) { return true; } @Override public boolean supportsTopN(ConnectorSession session, JdbcTableHandle handle, List<JdbcSortItem> sortOrder) { for (JdbcSortItem sortItem : sortOrder) { Type sortItemType = sortItem.getColumn().getColumnType(); if (sortItemType instanceof CharType || sortItemType instanceof VarcharType) { // Remote database can be case insensitive. return false; } } return true; } @Override protected Optional<TopNFunction> topNFunction() { return Optional.of((query, sortItems, limit) -> { String orderBy = sortItems.stream() .flatMap(sortItem -> { String ordering = sortItem.getSortOrder().isAscending() ? "ASC" : "DESC"; String columnSorting = format("%s %s", quoted(sortItem.getColumn().getColumnName()), ordering); switch (sortItem.getSortOrder()) { case ASC_NULLS_FIRST: // In MemSQL ASC implies NULLS FIRST case DESC_NULLS_LAST: // In MemSQL DESC implies NULLS LAST return Stream.of(columnSorting); case ASC_NULLS_LAST: return Stream.of( format("ISNULL(%s) ASC", quoted(sortItem.getColumn().getColumnName())), columnSorting); case DESC_NULLS_FIRST: return Stream.of( format("ISNULL(%s) DESC", quoted(sortItem.getColumn().getColumnName())), columnSorting); } throw new UnsupportedOperationException("Unsupported sort order: " + sortItem.getSortOrder()); }) .collect(joining(", ")); return format("%s ORDER BY %s LIMIT %s", query, orderBy, limit); }); } @Override public boolean isTopNGuaranteed(ConnectorSession session) { return true; } @Override public Optional<PreparedQuery> implementJoin( ConnectorSession session, JoinType joinType, PreparedQuery leftSource, PreparedQuery rightSource, List<JdbcJoinCondition> joinConditions, Map<JdbcColumnHandle, String> rightAssignments, Map<JdbcColumnHandle, String> leftAssignments, JoinStatistics statistics) { if (joinType == JoinType.FULL_OUTER) { // Not supported in MemSQL return Optional.empty(); } return super.implementJoin(session, joinType, leftSource, rightSource, joinConditions, rightAssignments, leftAssignments, statistics); } @Override protected boolean isSupportedJoinCondition(ConnectorSession session, JdbcJoinCondition joinCondition) { if (joinCondition.getOperator() == JoinCondition.Operator.IS_DISTINCT_FROM) { // Not supported in MemSQL return false; } // Remote database can be case insensitive. return Stream.of(joinCondition.getLeftColumn(), joinCondition.getRightColumn()) .map(JdbcColumnHandle::getColumnType) .noneMatch(type -> type instanceof CharType || type instanceof VarcharType); } private static Optional<ColumnMapping> getUnsignedMapping(JdbcTypeHandle typeHandle) { if (typeHandle.getJdbcTypeName().isEmpty()) { return Optional.empty(); } String typeName = typeHandle.getJdbcTypeName().get(); if (UNSIGNED_TYPE_REGEX.matcher(typeName).matches()) { switch (typeHandle.getJdbcType()) { case Types.BIT: return Optional.of(booleanColumnMapping()); case Types.TINYINT: return Optional.of(smallintColumnMapping()); case Types.SMALLINT: return Optional.of(integerColumnMapping()); case Types.INTEGER: return Optional.of(bigintColumnMapping()); case Types.BIGINT: return Optional.of(decimalColumnMapping(createDecimalType(20))); } } return Optional.empty(); } private static LongReadFunction memsqlTimeReadFunction(TimeType timeType) { requireNonNull(timeType, "timeType is null"); checkArgument(timeType.getPrecision() <= 9, "Unsupported type precision: %s", timeType); return (resultSet, columnIndex) -> { // SingleStore JDBC driver wraps time to be within LocalTime range, which results in values which differ from what is stored, so we verify them String timeString = resultSet.getString(columnIndex); try { long nanosOfDay = LocalTime.from(ISO_LOCAL_TIME.parse(timeString)).toNanoOfDay(); verify(nanosOfDay < NANOSECONDS_PER_DAY, "Invalid value of nanosOfDay: %s", nanosOfDay); long picosOfDay = nanosOfDay * PICOSECONDS_PER_NANOSECOND; long rounded = round(picosOfDay, 12 - timeType.getPrecision()); if (rounded == PICOSECONDS_PER_DAY) { rounded = 0; } return rounded; } catch (DateTimeParseException e) { throw new IllegalStateException(format("Supported Trino TIME type range is between 00:00:00 and 23:59:59.999999 but got %s", timeString), e); } }; } private static LongWriteFunction dateWriteFunction() { return (statement, index, day) -> statement.setString(index, DATE_FORMATTER.format(LocalDate.ofEpochDay(day))); } private ColumnMapping jsonColumnMapping() { return ColumnMapping.sliceMapping( jsonType, (resultSet, columnIndex) -> jsonParse(utf8Slice(resultSet.getString(columnIndex))), varcharWriteFunction(), DISABLE_PUSHDOWN); } }
Improve singlestore timestamp precision mapping
plugin/trino-singlestore/src/main/java/io/trino/plugin/singlestore/SingleStoreClient.java
Improve singlestore timestamp precision mapping
Java
apache-2.0
2763d7615b18b3c1decf6e1afb6c7d541f1ec686
0
gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.integtests.fixtures.executer; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.google.common.io.CharSource; import groovy.lang.Closure; import groovy.lang.DelegatesTo; import org.gradle.api.Action; import org.gradle.api.JavaVersion; import org.gradle.api.Transformer; import org.gradle.api.UncheckedIOException; import org.gradle.api.internal.initialization.DefaultClassLoaderScope; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import org.gradle.api.logging.configuration.ConsoleOutput; import org.gradle.api.logging.configuration.WarningMode; import org.gradle.cache.internal.DefaultGeneratedGradleJarCache; import org.gradle.integtests.fixtures.RepoScriptBlockUtil; import org.gradle.integtests.fixtures.daemon.DaemonLogsAnalyzer; import org.gradle.internal.ImmutableActionSet; import org.gradle.internal.MutableActionSet; import org.gradle.internal.UncheckedException; import org.gradle.internal.featurelifecycle.LoggingDeprecatedFeatureHandler; import org.gradle.internal.jvm.Jvm; import org.gradle.internal.jvm.inspection.JvmVersionDetector; import org.gradle.internal.logging.LoggingManagerInternal; import org.gradle.internal.logging.services.DefaultLoggingManagerFactory; import org.gradle.internal.logging.services.LoggingServiceRegistry; import org.gradle.internal.nativeintegration.console.TestOverrideConsoleDetector; import org.gradle.internal.nativeintegration.services.NativeServices; import org.gradle.internal.service.ServiceRegistry; import org.gradle.internal.service.ServiceRegistryBuilder; import org.gradle.internal.service.scopes.GlobalScopeServices; import org.gradle.launcher.cli.DefaultCommandLineActionFactory; import org.gradle.launcher.daemon.configuration.DaemonBuildOptions; import org.gradle.process.internal.streams.SafeStreams; import org.gradle.test.fixtures.file.TestDirectoryProvider; import org.gradle.test.fixtures.file.TestFile; import org.gradle.testfixtures.internal.NativeServicesTestFixture; import org.gradle.util.ClosureBackedAction; import org.gradle.util.CollectionUtils; import org.gradle.util.GradleVersion; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static org.gradle.api.internal.artifacts.BaseRepositoryFactory.PLUGIN_PORTAL_OVERRIDE_URL_PROPERTY; import static org.gradle.integtests.fixtures.RepoScriptBlockUtil.gradlePluginRepositoryMirrorUrl; import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.DAEMON; import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.FOREGROUND; import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.NOT_DEFINED; import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.NO_DAEMON; import static org.gradle.integtests.fixtures.executer.OutputScrapingExecutionResult.STACK_TRACE_ELEMENT; import static org.gradle.internal.service.scopes.DefaultGradleUserHomeScopeServiceRegistry.REUSE_USER_HOME_SERVICES; import static org.gradle.util.CollectionUtils.collect; import static org.gradle.util.CollectionUtils.join; public abstract class AbstractGradleExecuter implements GradleExecuter { protected static final ServiceRegistry GLOBAL_SERVICES = ServiceRegistryBuilder.builder() .displayName("Global services") .parent(newCommandLineProcessLogging()) .parent(NativeServicesTestFixture.getInstance()) .provider(new GlobalScopeServices(true)) .build(); private static final JvmVersionDetector JVM_VERSION_DETECTOR = GLOBAL_SERVICES.get(JvmVersionDetector.class); protected final static Set<String> PROPAGATED_SYSTEM_PROPERTIES = Sets.newHashSet(); public static void propagateSystemProperty(String name) { PROPAGATED_SYSTEM_PROPERTIES.add(name); } private static final String DEBUG_SYSPROP = "org.gradle.integtest.debug"; private static final String LAUNCHER_DEBUG_SYSPROP = "org.gradle.integtest.launcher.debug"; private static final String PROFILE_SYSPROP = "org.gradle.integtest.profile"; protected static final List<String> DEBUG_ARGS = ImmutableList.of( "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005" ); private final Logger logger; protected final IntegrationTestBuildContext buildContext; private final Set<File> isolatedDaemonBaseDirs = new HashSet<File>(); private final Set<GradleHandle> running = new HashSet<GradleHandle>(); private final List<String> args = new ArrayList<String>(); private final List<String> tasks = new ArrayList<String>(); private boolean allowExtraLogging = true; protected ConsoleAttachment consoleAttachment = ConsoleAttachment.NOT_ATTACHED; private File workingDir; private boolean quiet; private boolean taskList; private boolean dependencyList; private Map<String, String> environmentVars = new HashMap<String, String>(); private List<File> initScripts = new ArrayList<File>(); private String executable; private TestFile gradleUserHomeDir; private File userHomeDir; private File javaHome; private File buildScript; private File projectDir; private File settingsFile; private boolean ignoreMissingSettingsFile; private PipedOutputStream stdinPipe; private String defaultCharacterEncoding; private Locale defaultLocale; private int daemonIdleTimeoutSecs = 120; private boolean requireDaemon; private File daemonBaseDir; private final List<String> buildJvmOpts = new ArrayList<String>(); private final List<String> commandLineJvmOpts = new ArrayList<String>(); private boolean useOnlyRequestedJvmOpts; private boolean requiresGradleDistribution; private boolean useOwnUserHomeServices; private ConsoleOutput consoleType; protected WarningMode warningMode = WarningMode.All; private boolean showStacktrace = true; private boolean renderWelcomeMessage; private int expectedGenericDeprecationWarnings; private final List<String> expectedDeprecationWarnings = new ArrayList<>(); private boolean eagerClassLoaderCreationChecksOn = true; private boolean stackTraceChecksOn = true; private final MutableActionSet<GradleExecuter> beforeExecute = new MutableActionSet<GradleExecuter>(); private ImmutableActionSet<GradleExecuter> afterExecute = ImmutableActionSet.empty(); private final TestDirectoryProvider testDirectoryProvider; protected final GradleVersion gradleVersion; private final GradleDistribution distribution; private boolean debug = Boolean.getBoolean(DEBUG_SYSPROP); private boolean debugLauncher = Boolean.getBoolean(LAUNCHER_DEBUG_SYSPROP); private String profiler = System.getProperty(PROFILE_SYSPROP, ""); protected boolean interactive; private boolean noExplicitTmpDir; protected boolean noExplicitNativeServicesDir; private boolean fullDeprecationStackTrace = true; private boolean checkDeprecations = true; private TestFile tmpDir; private DurationMeasurement durationMeasurement; protected AbstractGradleExecuter(GradleDistribution distribution, TestDirectoryProvider testDirectoryProvider) { this(distribution, testDirectoryProvider, GradleVersion.current()); } protected AbstractGradleExecuter(GradleDistribution distribution, TestDirectoryProvider testDirectoryProvider, GradleVersion gradleVersion) { this(distribution, testDirectoryProvider, gradleVersion, IntegrationTestBuildContext.INSTANCE); } protected AbstractGradleExecuter(GradleDistribution distribution, TestDirectoryProvider testDirectoryProvider, GradleVersion gradleVersion, IntegrationTestBuildContext buildContext) { this.distribution = distribution; this.testDirectoryProvider = testDirectoryProvider; this.gradleVersion = gradleVersion; logger = Logging.getLogger(getClass()); this.buildContext = buildContext; gradleUserHomeDir = buildContext.getGradleUserHomeDir(); daemonBaseDir = buildContext.getDaemonBaseDir(); } protected Logger getLogger() { return logger; } @Override public GradleExecuter reset() { args.clear(); tasks.clear(); initScripts.clear(); workingDir = null; projectDir = null; buildScript = null; settingsFile = null; ignoreMissingSettingsFile = false; quiet = false; taskList = false; dependencyList = false; executable = null; javaHome = null; environmentVars.clear(); stdinPipe = null; defaultCharacterEncoding = null; defaultLocale = null; commandLineJvmOpts.clear(); buildJvmOpts.clear(); useOnlyRequestedJvmOpts = false; expectedGenericDeprecationWarnings = 0; expectedDeprecationWarnings.clear(); stackTraceChecksOn = true; renderWelcomeMessage = false; debug = Boolean.getBoolean(DEBUG_SYSPROP); debugLauncher = Boolean.getBoolean(LAUNCHER_DEBUG_SYSPROP); profiler = System.getProperty(PROFILE_SYSPROP, ""); interactive = false; checkDeprecations = true; durationMeasurement = null; consoleType = null; warningMode = WarningMode.All; return this; } @Override public GradleDistribution getDistribution() { return distribution; } @Override public TestDirectoryProvider getTestDirectoryProvider() { return testDirectoryProvider; } @Override public void beforeExecute(Action<? super GradleExecuter> action) { beforeExecute.add(action); } @Override public void beforeExecute(@DelegatesTo(GradleExecuter.class) Closure action) { beforeExecute.add(new ClosureBackedAction<GradleExecuter>(action)); } @Override public void afterExecute(Action<? super GradleExecuter> action) { afterExecute = afterExecute.add(action); } @Override public void afterExecute(@DelegatesTo(GradleExecuter.class) Closure action) { afterExecute(new ClosureBackedAction<GradleExecuter>(action)); } @Override public GradleExecuter inDirectory(File directory) { workingDir = directory; return this; } public File getWorkingDir() { return workingDir == null ? getTestDirectoryProvider().getTestDirectory() : workingDir; } @Override public GradleExecuter copyTo(GradleExecuter executer) { executer.withGradleUserHomeDir(gradleUserHomeDir); executer.withDaemonIdleTimeoutSecs(daemonIdleTimeoutSecs); executer.withDaemonBaseDir(daemonBaseDir); if (workingDir != null) { executer.inDirectory(workingDir); } if (projectDir != null) { executer.usingProjectDirectory(projectDir); } if (buildScript != null) { executer.usingBuildScript(buildScript); } if (settingsFile != null) { executer.usingSettingsFile(settingsFile); } if (ignoreMissingSettingsFile) { executer.ignoreMissingSettingsFile(); } if (javaHome != null) { executer.withJavaHome(javaHome); } for (File initScript : initScripts) { executer.usingInitScript(initScript); } executer.withTasks(tasks); executer.withArguments(args); executer.withEnvironmentVars(environmentVars); executer.usingExecutable(executable); if (quiet) { executer.withQuietLogging(); } if (taskList) { executer.withTaskList(); } if (dependencyList) { executer.withDependencyList(); } if (userHomeDir != null) { executer.withUserHomeDir(userHomeDir); } if (stdinPipe != null) { executer.withStdinPipe(stdinPipe); } if (defaultCharacterEncoding != null) { executer.withDefaultCharacterEncoding(defaultCharacterEncoding); } if (noExplicitTmpDir) { executer.withNoExplicitTmpDir(); } if (noExplicitNativeServicesDir) { executer.withNoExplicitNativeServicesDir(); } if (!fullDeprecationStackTrace) { executer.withFullDeprecationStackTraceDisabled(); } if (defaultLocale != null) { executer.withDefaultLocale(defaultLocale); } executer.withCommandLineGradleOpts(commandLineJvmOpts); executer.withBuildJvmOpts(buildJvmOpts); if (useOnlyRequestedJvmOpts) { executer.useOnlyRequestedJvmOpts(); } executer.noExtraLogging(); if (expectedGenericDeprecationWarnings > 0) { executer.expectDeprecationWarnings(expectedGenericDeprecationWarnings); } expectedDeprecationWarnings.forEach(executer::expectDeprecationWarning); if (!eagerClassLoaderCreationChecksOn) { executer.withEagerClassLoaderCreationCheckDisabled(); } if (!stackTraceChecksOn) { executer.withStackTraceChecksDisabled(); } if (requiresGradleDistribution) { executer.requireGradleDistribution(); } if (useOwnUserHomeServices) { executer.withOwnUserHomeServices(); } if (requireDaemon) { executer.requireDaemon(); } executer.startBuildProcessInDebugger(debug); executer.startLauncherInDebugger(debugLauncher); executer.withProfiler(profiler); executer.withForceInteractive(interactive); if (!checkDeprecations) { executer.noDeprecationChecks(); } if (durationMeasurement != null) { executer.withDurationMeasurement(durationMeasurement); } if (consoleType != null) { executer.withConsole(consoleType); } executer.withWarningMode(warningMode); if (!showStacktrace) { executer.withStacktraceDisabled(); } if (renderWelcomeMessage) { executer.withWelcomeMessageEnabled(); } executer.withTestConsoleAttached(consoleAttachment); return executer; } @Override public GradleExecuter usingBuildScript(File buildScript) { this.buildScript = buildScript; return this; } @Override public GradleExecuter usingProjectDirectory(File projectDir) { this.projectDir = projectDir; return this; } @Override public GradleExecuter usingSettingsFile(File settingsFile) { this.settingsFile = settingsFile; return this; } @Override public GradleExecuter usingInitScript(File initScript) { initScripts.add(initScript); return this; } @Override public TestFile getGradleUserHomeDir() { return gradleUserHomeDir; } @Override public GradleExecuter withGradleUserHomeDir(File userHomeDir) { this.gradleUserHomeDir = userHomeDir == null ? null : new TestFile(userHomeDir); return this; } @Override public GradleExecuter requireOwnGradleUserHomeDir() { return withGradleUserHomeDir(testDirectoryProvider.getTestDirectory().file("user-home")); } public File getUserHomeDir() { return userHomeDir; } protected GradleInvocation buildInvocation() { validateDaemonVisibility(); GradleInvocation gradleInvocation = new GradleInvocation(); gradleInvocation.environmentVars.putAll(environmentVars); if (!useOnlyRequestedJvmOpts) { gradleInvocation.buildJvmArgs.addAll(getImplicitBuildJvmArgs()); } gradleInvocation.buildJvmArgs.addAll(buildJvmOpts); calculateLauncherJvmArgs(gradleInvocation); gradleInvocation.args.addAll(getAllArgs()); transformInvocation(gradleInvocation); if (!gradleInvocation.implicitLauncherJvmArgs.isEmpty()) { throw new IllegalStateException("Implicit JVM args have not been handled."); } return gradleInvocation; } protected void validateDaemonVisibility() { if (isUseDaemon() && isSharedDaemons()) { throw new IllegalStateException("Daemon that will be visible to other tests has been requested."); } } /** * Adjusts the calculated invocation prior to execution. This method is responsible for handling the implicit launcher JVM args in some way, by mutating the invocation appropriately. */ protected void transformInvocation(GradleInvocation gradleInvocation) { gradleInvocation.launcherJvmArgs.addAll(0, gradleInvocation.implicitLauncherJvmArgs); gradleInvocation.implicitLauncherJvmArgs.clear(); } /** * Returns the JVM opts that should be used to start a forked JVM. */ private void calculateLauncherJvmArgs(GradleInvocation gradleInvocation) { // Add JVM args that were explicitly requested gradleInvocation.launcherJvmArgs.addAll(commandLineJvmOpts); if (isUseDaemon() && !gradleInvocation.buildJvmArgs.isEmpty()) { // Pass build JVM args through to daemon via system property on the launcher JVM String quotedArgs = join(" ", collect(gradleInvocation.buildJvmArgs, new Transformer<String, String>() { @Override public String transform(String input) { return String.format("'%s'", input); } })); gradleInvocation.implicitLauncherJvmArgs.add("-Dorg.gradle.jvmargs=" + quotedArgs); } else { // Have to pass build JVM args directly to launcher JVM gradleInvocation.launcherJvmArgs.addAll(gradleInvocation.buildJvmArgs); } // Set the implicit system properties regardless of whether default JVM args are required or not, this should not interfere with tests' intentions // These will also be copied across to any daemon used for (Map.Entry<String, String> entry : getImplicitJvmSystemProperties().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); gradleInvocation.implicitLauncherJvmArgs.add(String.format("-D%s=%s", key, value)); } if (isDebugLauncher()) { gradleInvocation.implicitLauncherJvmArgs.addAll(DEBUG_ARGS); } gradleInvocation.implicitLauncherJvmArgs.add("-ea"); } /** * Returns additional JVM args that should be used to start the build JVM. */ protected List<String> getImplicitBuildJvmArgs() { List<String> buildJvmOpts = new ArrayList<String>(); buildJvmOpts.add("-ea"); if (isDebug()) { buildJvmOpts.addAll(DEBUG_ARGS); } if (isProfile()) { buildJvmOpts.add(profiler); } if (isSharedDaemons()) { buildJvmOpts.add("-Xms256m"); buildJvmOpts.add("-Xmx1024m"); } else { buildJvmOpts.add("-Xms256m"); buildJvmOpts.add("-Xmx512m"); } if (JVM_VERSION_DETECTOR.getJavaVersion(Jvm.forHome(getJavaHome())).compareTo(JavaVersion.VERSION_1_8) < 0) { buildJvmOpts.add("-XX:MaxPermSize=320m"); } else { buildJvmOpts.add("-XX:MaxMetaspaceSize=512m"); } buildJvmOpts.add("-XX:+HeapDumpOnOutOfMemoryError"); buildJvmOpts.add("-XX:HeapDumpPath=" + buildContext.getGradleUserHomeDir()); return buildJvmOpts; } private boolean xmxSpecified() { for (String arg : buildJvmOpts) { if (arg.startsWith("-Xmx")) { return true; } } return false; } @Override public GradleExecuter withUserHomeDir(File userHomeDir) { this.userHomeDir = userHomeDir; return this; } public File getJavaHome() { return javaHome == null ? Jvm.current().getJavaHome() : javaHome; } @Override public GradleExecuter withJavaHome(File javaHome) { this.javaHome = javaHome; return this; } @Override public GradleExecuter usingExecutable(String script) { this.executable = script; return this; } public String getExecutable() { return executable; } @Override public GradleExecuter withStdinPipe() { return withStdinPipe(new PipedOutputStream()); } @Override public GradleExecuter withStdinPipe(PipedOutputStream stdInPipe) { this.stdinPipe = stdInPipe; return this; } public InputStream connectStdIn() { try { return stdinPipe == null ? SafeStreams.emptyInput() : new PipedInputStream(stdinPipe); } catch (IOException e) { throw UncheckedException.throwAsUncheckedException(e); } } public PipedOutputStream getStdinPipe() { return stdinPipe; } @Override public GradleExecuter withDefaultCharacterEncoding(String defaultCharacterEncoding) { this.defaultCharacterEncoding = defaultCharacterEncoding; return this; } public String getDefaultCharacterEncoding() { return defaultCharacterEncoding == null ? Charset.defaultCharset().name() : defaultCharacterEncoding; } @Override public GradleExecuter withDefaultLocale(Locale defaultLocale) { this.defaultLocale = defaultLocale; return this; } public Locale getDefaultLocale() { return defaultLocale; } public boolean isQuiet() { return quiet; } @Override public GradleExecuter withQuietLogging() { quiet = true; return this; } @Override public GradleExecuter withTaskList() { taskList = true; return this; } @Override public GradleExecuter withDependencyList() { dependencyList = true; return this; } @Override public GradleExecuter withArguments(String... args) { return withArguments(Arrays.asList(args)); } @Override public GradleExecuter withArguments(List<String> args) { this.args.clear(); this.args.addAll(args); return this; } @Override public GradleExecuter withArgument(String arg) { this.args.add(arg); return this; } @Override public GradleExecuter withEnvironmentVars(Map<String, ?> environment) { environmentVars.clear(); for (Map.Entry<String, ?> entry : environment.entrySet()) { environmentVars.put(entry.getKey(), entry.getValue().toString()); } return this; } protected String toJvmArgsString(Iterable<String> jvmArgs) { StringBuilder result = new StringBuilder(); for (String jvmArg : jvmArgs) { if (result.length() > 0) { result.append(" "); } if (jvmArg.contains(" ")) { assert !jvmArg.contains("\"") : "jvmArg '" + jvmArg + "' contains '\"'"; result.append('"'); result.append(jvmArg); result.append('"'); } else { result.append(jvmArg); } } return result.toString(); } @Override public GradleExecuter withTasks(String... names) { return withTasks(Arrays.asList(names)); } @Override public GradleExecuter withTasks(List<String> names) { tasks.clear(); tasks.addAll(names); return this; } @Override public GradleExecuter withDaemonIdleTimeoutSecs(int secs) { daemonIdleTimeoutSecs = secs; return this; } @Override public GradleExecuter useOnlyRequestedJvmOpts() { useOnlyRequestedJvmOpts = true; return this; } @Override public GradleExecuter withDaemonBaseDir(File daemonBaseDir) { this.daemonBaseDir = daemonBaseDir; return this; } @Override public GradleExecuter requireIsolatedDaemons() { return withDaemonBaseDir(testDirectoryProvider.getTestDirectory().file("daemon")); } @Override public GradleExecuter withWorkerDaemonsExpirationDisabled() { return withCommandLineGradleOpts("-Dorg.gradle.workers.internal.disable-daemons-expiration=true"); } @Override public boolean usesSharedDaemons() { return isSharedDaemons(); } @Override public File getDaemonBaseDir() { return daemonBaseDir; } @Override public GradleExecuter requireDaemon() { this.requireDaemon = true; return this; } protected boolean isSharedDaemons() { return daemonBaseDir.equals(buildContext.getDaemonBaseDir()); } @Override public boolean isUseDaemon() { CliDaemonArgument cliDaemonArgument = resolveCliDaemonArgument(); if (cliDaemonArgument == NO_DAEMON || cliDaemonArgument == FOREGROUND) { return false; } return requireDaemon || cliDaemonArgument == DAEMON; } @Override public GradleExecuter withOwnUserHomeServices() { useOwnUserHomeServices = true; return this; } @Override public GradleExecuter withWarningMode(WarningMode warningMode) { this.warningMode = warningMode; return this; } @Override public GradleExecuter withConsole(ConsoleOutput consoleType) { this.consoleType = consoleType; return this; } @Override public GradleExecuter withStacktraceDisabled() { showStacktrace = false; return this; } @Override public GradleExecuter withWelcomeMessageEnabled() { renderWelcomeMessage = true; return this; } @Override public GradleExecuter withRepositoryMirrors() { beforeExecute(new Action<GradleExecuter>() { @Override public void execute(GradleExecuter gradleExecuter) { usingInitScript(RepoScriptBlockUtil.createMirrorInitScript()); } }); return this; } @Override public GradleExecuter withGlobalRepositoryMirrors() { beforeExecute(new Action<GradleExecuter>() { @Override public void execute(GradleExecuter gradleExecuter) { TestFile userHome = testDirectoryProvider.getTestDirectory().file("user-home"); withGradleUserHomeDir(userHome); userHome.file("init.d/mirrors.gradle").write(RepoScriptBlockUtil.mirrorInitScript()); } }); return this; } @Override public GradleExecuter withPluginRepositoryMirror() { beforeExecute(new Action<GradleExecuter>() { @Override public void execute(GradleExecuter gradleExecuter) { withArgument("-D" + PLUGIN_PORTAL_OVERRIDE_URL_PROPERTY + "=" + gradlePluginRepositoryMirrorUrl()); } }); return this; } /** * Performs cleanup at completion of the test. */ public void cleanup() { stopRunningBuilds(); cleanupIsolatedDaemons(); } private void stopRunningBuilds() { for (GradleHandle handle : running) { try { handle.abort().waitForExit(); } catch (Exception e) { getLogger().warn("Problem stopping running build", e); } } } private void cleanupIsolatedDaemons() { for (File baseDir : isolatedDaemonBaseDirs) { try { new DaemonLogsAnalyzer(baseDir, gradleVersion.getVersion()).killAll(); } catch (Exception e) { getLogger().warn("Problem killing isolated daemons of Gradle version " + gradleVersion + " in " + baseDir, e); } } } enum CliDaemonArgument { NOT_DEFINED, DAEMON, NO_DAEMON, FOREGROUND } protected CliDaemonArgument resolveCliDaemonArgument() { for (int i = args.size() - 1; i >= 0; i--) { final String arg = args.get(i); if (arg.equals("--daemon")) { return DAEMON; } if (arg.equals("--no-daemon")) { return NO_DAEMON; } if (arg.equals("--foreground")) { return FOREGROUND; } } return NOT_DEFINED; } private boolean noDaemonArgumentGiven() { return resolveCliDaemonArgument() == NOT_DEFINED; } protected List<String> getAllArgs() { List<String> allArgs = new ArrayList<String>(); if (buildScript != null) { allArgs.add("--build-file"); allArgs.add(buildScript.getAbsolutePath()); } if (projectDir != null) { allArgs.add("--project-dir"); allArgs.add(projectDir.getAbsolutePath()); } for (File initScript : initScripts) { allArgs.add("--init-script"); allArgs.add(initScript.getAbsolutePath()); } if (settingsFile != null) { allArgs.add("--settings-file"); allArgs.add(settingsFile.getAbsolutePath()); } if (quiet) { allArgs.add("--quiet"); } if (noDaemonArgumentGiven()) { if (isUseDaemon()) { allArgs.add("--daemon"); } else { allArgs.add("--no-daemon"); } } if (showStacktrace) { allArgs.add("--stacktrace"); } if (taskList) { allArgs.add("tasks"); } if (dependencyList) { allArgs.add("dependencies"); } if (settingsFile == null && !ignoreMissingSettingsFile) { ensureSettingsFileAvailable(); } // This will cause problems on Windows if the path to the Gradle executable that is used has a space in it (e.g. the user's dir is c:/Users/Luke Daley/) // This is fundamentally a windows issue: You can't have arguments with spaces in them if the path to the batch script has a space // We could work around this by setting -Dgradle.user.home but GRADLE-1730 (which affects 1.0-milestone-3) means that that // is problematic as well. For now, we just don't support running the int tests from a path with a space in it on Windows. // When we stop testing against M3 we should change to use the system property. if (getGradleUserHomeDir() != null) { allArgs.add("--gradle-user-home"); allArgs.add(getGradleUserHomeDir().getAbsolutePath()); } if (consoleType != null) { allArgs.add("--console=" + consoleType.toString().toLowerCase()); } if (warningMode != null) { allArgs.add("--warning-mode=" + warningMode.toString().toLowerCase(Locale.ENGLISH)); } allArgs.addAll(args); allArgs.addAll(tasks); return allArgs; } @Override public GradleExecuter ignoreMissingSettingsFile() { ignoreMissingSettingsFile = true; return this; } private void ensureSettingsFileAvailable() { TestFile workingDir = new TestFile(getWorkingDir()); TestFile dir = workingDir; while (dir != null && getTestDirectoryProvider().getTestDirectory().isSelfOrDescendent(dir)) { if (hasSettingsFile(dir) || hasSettingsFile(dir.file("master"))) { return; } dir = dir.getParentFile(); } workingDir.createFile("settings.gradle"); } private boolean hasSettingsFile(TestFile dir) { if (dir.isDirectory()) { return dir.file("settings.gradle").isFile() || dir.file("settings.gradle.kts").isFile(); } return false; } /** * Returns the set of system properties that should be set on every JVM used by this executer. */ protected Map<String, String> getImplicitJvmSystemProperties() { Map<String, String> properties = new LinkedHashMap<String, String>(); if (getUserHomeDir() != null) { properties.put("user.home", getUserHomeDir().getAbsolutePath()); } properties.put(DaemonBuildOptions.IdleTimeoutOption.GRADLE_PROPERTY, "" + (daemonIdleTimeoutSecs * 1000)); properties.put(DaemonBuildOptions.BaseDirOption.GRADLE_PROPERTY, daemonBaseDir.getAbsolutePath()); if (!noExplicitNativeServicesDir) { properties.put(NativeServices.NATIVE_DIR_OVERRIDE, buildContext.getNativeServicesDir().getAbsolutePath()); } properties.put(LoggingDeprecatedFeatureHandler.ORG_GRADLE_DEPRECATION_TRACE_PROPERTY_NAME, Boolean.toString(fullDeprecationStackTrace)); boolean useCustomGradleUserHomeDir = gradleUserHomeDir != null && !gradleUserHomeDir.equals(buildContext.getGradleUserHomeDir()); if (useOwnUserHomeServices || useCustomGradleUserHomeDir) { properties.put(REUSE_USER_HOME_SERVICES, "false"); } if (!useCustomGradleUserHomeDir) { TestFile generatedApiJarCacheDir = buildContext.getGradleGeneratedApiJarCacheDir(); if (generatedApiJarCacheDir != null) { properties.put(DefaultGeneratedGradleJarCache.BASE_DIR_OVERRIDE_PROPERTY, generatedApiJarCacheDir.getAbsolutePath()); } } if (!noExplicitTmpDir) { if (tmpDir == null) { tmpDir = getDefaultTmpDir(); } String tmpDirPath = tmpDir.createDir().getAbsolutePath(); if (!tmpDirPath.contains(" ") || (getDistribution().isSupportsSpacesInGradleAndJavaOpts() && supportsWhiteSpaceInEnvVars())) { properties.put("java.io.tmpdir", tmpDirPath); } } properties.put("file.encoding", getDefaultCharacterEncoding()); Locale locale = getDefaultLocale(); if (locale != null) { properties.put("user.language", locale.getLanguage()); properties.put("user.country", locale.getCountry()); properties.put("user.variant", locale.getVariant()); } if (eagerClassLoaderCreationChecksOn) { properties.put(DefaultClassLoaderScope.STRICT_MODE_PROPERTY, "true"); } if (interactive) { properties.put(TestOverrideConsoleDetector.INTERACTIVE_TOGGLE, "true"); } properties.put(DefaultCommandLineActionFactory.WELCOME_MESSAGE_ENABLED_SYSTEM_PROPERTY, Boolean.toString(renderWelcomeMessage)); return properties; } protected boolean supportsWhiteSpaceInEnvVars() { return true; } @Override public final GradleHandle start() { assert afterExecute.isEmpty() : "afterExecute actions are not implemented for async execution"; return startHandle(); } protected GradleHandle startHandle() { fireBeforeExecute(); assertCanExecute(); collectStateBeforeExecution(); try { GradleHandle handle = createGradleHandle(); running.add(handle); return handle; } finally { reset(); } } @Override public final ExecutionResult run() { fireBeforeExecute(); assertCanExecute(); collectStateBeforeExecution(); try { ExecutionResult result = doRun(); if (errorsShouldAppearOnStdout()) { result = new ErrorsOnStdoutScrapingExecutionResult(result); } afterExecute.execute(this); return result; } finally { finished(); } } protected void finished() { reset(); } @Override public final ExecutionFailure runWithFailure() { fireBeforeExecute(); assertCanExecute(); collectStateBeforeExecution(); try { ExecutionFailure executionFailure = doRunWithFailure(); if (errorsShouldAppearOnStdout()) { executionFailure = new ErrorsOnStdoutScrapingExecutionFailure(executionFailure); } afterExecute.execute(this); return executionFailure; } finally { finished(); } } private void collectStateBeforeExecution() { if (!isSharedDaemons()) { isolatedDaemonBaseDirs.add(daemonBaseDir); } } private void fireBeforeExecute() { beforeExecute.execute(this); } protected GradleHandle createGradleHandle() { throw new UnsupportedOperationException(String.format("%s does not support running asynchronously.", getClass().getSimpleName())); } protected abstract ExecutionResult doRun(); protected abstract ExecutionFailure doRunWithFailure(); @Override public GradleExecuter withCommandLineGradleOpts(Iterable<String> jvmOpts) { CollectionUtils.addAll(commandLineJvmOpts, jvmOpts); return this; } @Override public GradleExecuter withCommandLineGradleOpts(String... jvmOpts) { CollectionUtils.addAll(commandLineJvmOpts, jvmOpts); return this; } @Override public AbstractGradleExecuter withBuildJvmOpts(String... jvmOpts) { CollectionUtils.addAll(buildJvmOpts, jvmOpts); return this; } @Override public GradleExecuter withBuildJvmOpts(Iterable<String> jvmOpts) { CollectionUtils.addAll(buildJvmOpts, jvmOpts); return this; } @Override public GradleExecuter withBuildCacheEnabled() { return withArgument("--build-cache"); } protected Action<ExecutionResult> getResultAssertion() { return new Action<ExecutionResult>() { private int expectedGenericDeprecationWarnings = AbstractGradleExecuter.this.expectedGenericDeprecationWarnings; private final List<String> expectedDeprecationWarnings = new ArrayList<>(AbstractGradleExecuter.this.expectedDeprecationWarnings); private final boolean expectStackTraces = !AbstractGradleExecuter.this.stackTraceChecksOn; private final boolean checkDeprecations = AbstractGradleExecuter.this.checkDeprecations; @Override public void execute(ExecutionResult executionResult) { String normalizedOutput = executionResult.getNormalizedOutput(); String error = executionResult.getError(); boolean executionFailure = isExecutionFailure(executionResult); // for tests using rich console standard out and error are combined in output of execution result if (executionFailure) { normalizedOutput = removeExceptionStackTraceForFailedExecution(normalizedOutput); } validate(normalizedOutput, "Standard output"); if (executionFailure) { error = removeExceptionStackTraceForFailedExecution(error); } validate(error, "Standard error"); if (!expectedDeprecationWarnings.isEmpty()) { throw new AssertionError(String.format("Expected the following deprecation warnings:%n%s", expectedDeprecationWarnings.stream() .map(warning -> " - " + warning) .collect(Collectors.joining("\n")))); } if (expectedGenericDeprecationWarnings > 0) { throw new AssertionError(String.format("Expected %d more deprecation warnings", expectedGenericDeprecationWarnings)); } } private boolean isErrorOutEmpty(String error) { //remove SLF4J error out like 'Class path contains multiple SLF4J bindings.' //See: https://github.com/gradle/performance/issues/375#issuecomment-315103861 return Strings.isNullOrEmpty(error.replaceAll("(?m)^SLF4J: .*", "").trim()); } private boolean isExecutionFailure(ExecutionResult executionResult) { return executionResult instanceof ExecutionFailure; } // Axe everything after the expected exception private String removeExceptionStackTraceForFailedExecution(String text) { int pos = text.indexOf("* Exception is:"); if (pos >= 0) { text = text.substring(0, pos); } return text; } private void validate(String output, String displayName) { List<String> lines; try { lines = CharSource.wrap(output).readLines(); } catch (IOException e) { throw new UncheckedIOException(e); } int i = 0; boolean insideVariantDescriptionBlock = false; while (i < lines.size()) { String line = lines.get(i); if (insideVariantDescriptionBlock && line.contains("]")) { insideVariantDescriptionBlock = false; } else if (!insideVariantDescriptionBlock && line.contains("variant \"")) { insideVariantDescriptionBlock = true; } if (line.matches(".*use(s)? or override(s)? a deprecated API\\.")) { // A javac warning, ignore i++; } else if (line.matches(".*w: .* is deprecated\\..*")) { // A kotlinc warning, ignore i++; } else if (isDeprecationMessageInHelpDescription(line)) { i++; } else if (expectedDeprecationWarnings.remove(line)) { // Deprecation warning is expected i++; i = skipStackTrace(lines, i); } else if (line.matches(".*\\s+deprecated.*")) { if (checkDeprecations && expectedGenericDeprecationWarnings <= 0) { throw new AssertionError(String.format("%s line %d contains a deprecation warning: %s%n=====%n%s%n=====%n", displayName, i + 1, line, output)); } expectedGenericDeprecationWarnings--; // skip over stack trace i++; i = skipStackTrace(lines, i); } else if (!expectStackTraces && !insideVariantDescriptionBlock && STACK_TRACE_ELEMENT.matcher(line).matches() && i < lines.size() - 1 && STACK_TRACE_ELEMENT.matcher(lines.get(i + 1)).matches()) { // 2 or more lines that look like stack trace elements throw new AssertionError(String.format("%s line %d contains an unexpected stack trace: %s%n=====%n%s%n=====%n", displayName, i + 1, line, output)); } else { i++; } } } private int skipStackTrace(List<String> lines, int i) { while (i < lines.size() && STACK_TRACE_ELEMENT.matcher(lines.get(i)).matches()) { i++; } return i; } private boolean isDeprecationMessageInHelpDescription(String s) { return s.matches(".*\\[deprecated.*]"); } }; } @Override public GradleExecuter expectDeprecationWarning() { return expectDeprecationWarnings(1); } @Override public GradleExecuter expectDeprecationWarnings(int count) { Preconditions.checkState(expectedGenericDeprecationWarnings == 0, "expected deprecation count is already set for this execution"); Preconditions.checkArgument(count > 0, "expected deprecation count must be positive"); expectedGenericDeprecationWarnings = count; return this; } @Override public GradleExecuter expectDeprecationWarning(String warning) { expectedDeprecationWarnings.add(warning); return this; } @Override public GradleExecuter noDeprecationChecks() { checkDeprecations = false; return this; } @Override public GradleExecuter withEagerClassLoaderCreationCheckDisabled() { eagerClassLoaderCreationChecksOn = false; return this; } @Override public GradleExecuter withStackTraceChecksDisabled() { stackTraceChecksOn = false; return this; } protected TestFile getDefaultTmpDir() { return buildContext.getTmpDir().createDir(); } @Override public GradleExecuter noExtraLogging() { this.allowExtraLogging = false; return this; } public boolean isAllowExtraLogging() { return allowExtraLogging; } public boolean isRequiresGradleDistribution() { return requiresGradleDistribution; } @Override public GradleExecuter requireGradleDistribution() { this.requiresGradleDistribution = true; return this; } @Override public GradleExecuter startBuildProcessInDebugger(boolean flag) { debug = flag; return this; } @Override public GradleExecuter startLauncherInDebugger(boolean flag) { debugLauncher = flag; return this; } @Override public boolean isDebugLauncher() { return debugLauncher; } @Override public GradleExecuter withProfiler(String args) { profiler = args; return this; } @Override public GradleExecuter withForceInteractive(boolean flag) { interactive = flag; return this; } @Override public GradleExecuter withNoExplicitTmpDir() { noExplicitTmpDir = true; return this; } @Override public GradleExecuter withNoExplicitNativeServicesDir() { noExplicitNativeServicesDir = true; return this; } @Override public GradleExecuter withFullDeprecationStackTraceDisabled() { fullDeprecationStackTrace = false; return this; } @Override public boolean isDebug() { return debug; } @Override public boolean isProfile() { return !profiler.isEmpty(); } protected static class GradleInvocation { final Map<String, String> environmentVars = new HashMap<String, String>(); final List<String> args = new ArrayList<String>(); // JVM args that must be used for the build JVM final List<String> buildJvmArgs = new ArrayList<String>(); // JVM args that must be used to fork a JVM final List<String> launcherJvmArgs = new ArrayList<String>(); // Implicit JVM args that should be used to fork a JVM final List<String> implicitLauncherJvmArgs = new ArrayList<String>(); } @Override public void stop() { cleanup(); } @Override public GradleExecuter withDurationMeasurement(DurationMeasurement durationMeasurement) { this.durationMeasurement = durationMeasurement; return this; } protected void startMeasurement() { if (durationMeasurement != null) { durationMeasurement.start(); } } protected void stopMeasurement() { if (durationMeasurement != null) { durationMeasurement.stop(); } } protected DurationMeasurement getDurationMeasurement() { return durationMeasurement; } private static LoggingServiceRegistry newCommandLineProcessLogging() { LoggingServiceRegistry loggingServices = LoggingServiceRegistry.newEmbeddableLogging(); LoggingManagerInternal rootLoggingManager = loggingServices.get(DefaultLoggingManagerFactory.class).getRoot(); rootLoggingManager.attachSystemOutAndErr(); return loggingServices; } @Override public GradleExecuter withTestConsoleAttached() { return withTestConsoleAttached(ConsoleAttachment.ATTACHED); } @Override public GradleExecuter withTestConsoleAttached(ConsoleAttachment consoleAttachment) { this.consoleAttachment = consoleAttachment; return configureConsoleCommandLineArgs(); } protected GradleExecuter configureConsoleCommandLineArgs() { if (consoleAttachment == ConsoleAttachment.NOT_ATTACHED) { return this; } else { return withCommandLineGradleOpts(consoleAttachment.getConsoleMetaData().getCommandLineArgument()); } } private boolean errorsShouldAppearOnStdout() { // If stdout and stderr are attached to the console return consoleAttachment.isStderrAttached() && consoleAttachment.isStdoutAttached(); } }
subprojects/internal-integ-testing/src/main/groovy/org/gradle/integtests/fixtures/executer/AbstractGradleExecuter.java
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.integtests.fixtures.executer; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.google.common.io.CharSource; import groovy.lang.Closure; import groovy.lang.DelegatesTo; import org.gradle.api.Action; import org.gradle.api.JavaVersion; import org.gradle.api.Transformer; import org.gradle.api.UncheckedIOException; import org.gradle.api.internal.initialization.DefaultClassLoaderScope; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import org.gradle.api.logging.configuration.ConsoleOutput; import org.gradle.api.logging.configuration.WarningMode; import org.gradle.cache.internal.DefaultGeneratedGradleJarCache; import org.gradle.integtests.fixtures.RepoScriptBlockUtil; import org.gradle.integtests.fixtures.daemon.DaemonLogsAnalyzer; import org.gradle.internal.ImmutableActionSet; import org.gradle.internal.MutableActionSet; import org.gradle.internal.UncheckedException; import org.gradle.internal.featurelifecycle.LoggingDeprecatedFeatureHandler; import org.gradle.internal.jvm.Jvm; import org.gradle.internal.jvm.inspection.JvmVersionDetector; import org.gradle.internal.logging.LoggingManagerInternal; import org.gradle.internal.logging.services.DefaultLoggingManagerFactory; import org.gradle.internal.logging.services.LoggingServiceRegistry; import org.gradle.internal.nativeintegration.console.TestOverrideConsoleDetector; import org.gradle.internal.nativeintegration.services.NativeServices; import org.gradle.internal.service.ServiceRegistry; import org.gradle.internal.service.ServiceRegistryBuilder; import org.gradle.internal.service.scopes.GlobalScopeServices; import org.gradle.internal.service.scopes.GradleUserHomeScopeServices; import org.gradle.launcher.cli.DefaultCommandLineActionFactory; import org.gradle.launcher.daemon.configuration.DaemonBuildOptions; import org.gradle.process.internal.streams.SafeStreams; import org.gradle.test.fixtures.file.TestDirectoryProvider; import org.gradle.test.fixtures.file.TestFile; import org.gradle.testfixtures.internal.NativeServicesTestFixture; import org.gradle.util.ClosureBackedAction; import org.gradle.util.CollectionUtils; import org.gradle.util.GradleVersion; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static org.gradle.api.internal.artifacts.BaseRepositoryFactory.PLUGIN_PORTAL_OVERRIDE_URL_PROPERTY; import static org.gradle.integtests.fixtures.RepoScriptBlockUtil.gradlePluginRepositoryMirrorUrl; import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.DAEMON; import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.FOREGROUND; import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.NOT_DEFINED; import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.NO_DAEMON; import static org.gradle.integtests.fixtures.executer.OutputScrapingExecutionResult.STACK_TRACE_ELEMENT; import static org.gradle.internal.service.scopes.DefaultGradleUserHomeScopeServiceRegistry.REUSE_USER_HOME_SERVICES; import static org.gradle.util.CollectionUtils.collect; import static org.gradle.util.CollectionUtils.join; public abstract class AbstractGradleExecuter implements GradleExecuter { protected static final ServiceRegistry GLOBAL_SERVICES = ServiceRegistryBuilder.builder() .displayName("Global services") .parent(newCommandLineProcessLogging()) .parent(NativeServicesTestFixture.getInstance()) .provider(new GlobalScopeServices(true)) .build(); private static final JvmVersionDetector JVM_VERSION_DETECTOR = GLOBAL_SERVICES.get(JvmVersionDetector.class); protected final static Set<String> PROPAGATED_SYSTEM_PROPERTIES = Sets.newHashSet(); public static void propagateSystemProperty(String name) { PROPAGATED_SYSTEM_PROPERTIES.add(name); } private static final String DEBUG_SYSPROP = "org.gradle.integtest.debug"; private static final String LAUNCHER_DEBUG_SYSPROP = "org.gradle.integtest.launcher.debug"; private static final String PROFILE_SYSPROP = "org.gradle.integtest.profile"; protected static final List<String> DEBUG_ARGS = ImmutableList.of( "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005" ); private final Logger logger; protected final IntegrationTestBuildContext buildContext; private final Set<File> isolatedDaemonBaseDirs = new HashSet<File>(); private final Set<GradleHandle> running = new HashSet<GradleHandle>(); private final List<String> args = new ArrayList<String>(); private final List<String> tasks = new ArrayList<String>(); private boolean allowExtraLogging = true; protected ConsoleAttachment consoleAttachment = ConsoleAttachment.NOT_ATTACHED; private File workingDir; private boolean quiet; private boolean taskList; private boolean dependencyList; private Map<String, String> environmentVars = new HashMap<String, String>(); private List<File> initScripts = new ArrayList<File>(); private String executable; private TestFile gradleUserHomeDir; private File userHomeDir; private File javaHome; private File buildScript; private File projectDir; private File settingsFile; private boolean ignoreMissingSettingsFile; private PipedOutputStream stdinPipe; private String defaultCharacterEncoding; private Locale defaultLocale; private int daemonIdleTimeoutSecs = 120; private boolean requireDaemon; private File daemonBaseDir; private final List<String> buildJvmOpts = new ArrayList<String>(); private final List<String> commandLineJvmOpts = new ArrayList<String>(); private boolean useOnlyRequestedJvmOpts; private boolean requiresGradleDistribution; private boolean useOwnUserHomeServices; private ConsoleOutput consoleType; protected WarningMode warningMode = WarningMode.All; private boolean showStacktrace = true; private boolean renderWelcomeMessage; private int expectedGenericDeprecationWarnings; private final List<String> expectedDeprecationWarnings = new ArrayList<>(); private boolean eagerClassLoaderCreationChecksOn = true; private boolean stackTraceChecksOn = true; private final MutableActionSet<GradleExecuter> beforeExecute = new MutableActionSet<GradleExecuter>(); private ImmutableActionSet<GradleExecuter> afterExecute = ImmutableActionSet.empty(); private final TestDirectoryProvider testDirectoryProvider; protected final GradleVersion gradleVersion; private final GradleDistribution distribution; private boolean debug = Boolean.getBoolean(DEBUG_SYSPROP); private boolean debugLauncher = Boolean.getBoolean(LAUNCHER_DEBUG_SYSPROP); private String profiler = System.getProperty(PROFILE_SYSPROP, ""); protected boolean interactive; private boolean noExplicitTmpDir; protected boolean noExplicitNativeServicesDir; private boolean fullDeprecationStackTrace = true; private boolean checkDeprecations = true; private TestFile tmpDir; private DurationMeasurement durationMeasurement; protected AbstractGradleExecuter(GradleDistribution distribution, TestDirectoryProvider testDirectoryProvider) { this(distribution, testDirectoryProvider, GradleVersion.current()); } protected AbstractGradleExecuter(GradleDistribution distribution, TestDirectoryProvider testDirectoryProvider, GradleVersion gradleVersion) { this(distribution, testDirectoryProvider, gradleVersion, IntegrationTestBuildContext.INSTANCE); } protected AbstractGradleExecuter(GradleDistribution distribution, TestDirectoryProvider testDirectoryProvider, GradleVersion gradleVersion, IntegrationTestBuildContext buildContext) { this.distribution = distribution; this.testDirectoryProvider = testDirectoryProvider; this.gradleVersion = gradleVersion; logger = Logging.getLogger(getClass()); this.buildContext = buildContext; gradleUserHomeDir = buildContext.getGradleUserHomeDir(); daemonBaseDir = buildContext.getDaemonBaseDir(); } protected Logger getLogger() { return logger; } @Override public GradleExecuter reset() { args.clear(); tasks.clear(); initScripts.clear(); workingDir = null; projectDir = null; buildScript = null; settingsFile = null; ignoreMissingSettingsFile = false; quiet = false; taskList = false; dependencyList = false; executable = null; javaHome = null; environmentVars.clear(); stdinPipe = null; defaultCharacterEncoding = null; defaultLocale = null; commandLineJvmOpts.clear(); buildJvmOpts.clear(); useOnlyRequestedJvmOpts = false; expectedGenericDeprecationWarnings = 0; expectedDeprecationWarnings.clear(); stackTraceChecksOn = true; renderWelcomeMessage = false; debug = Boolean.getBoolean(DEBUG_SYSPROP); debugLauncher = Boolean.getBoolean(LAUNCHER_DEBUG_SYSPROP); profiler = System.getProperty(PROFILE_SYSPROP, ""); interactive = false; checkDeprecations = true; durationMeasurement = null; consoleType = null; warningMode = WarningMode.All; return this; } @Override public GradleDistribution getDistribution() { return distribution; } @Override public TestDirectoryProvider getTestDirectoryProvider() { return testDirectoryProvider; } @Override public void beforeExecute(Action<? super GradleExecuter> action) { beforeExecute.add(action); } @Override public void beforeExecute(@DelegatesTo(GradleExecuter.class) Closure action) { beforeExecute.add(new ClosureBackedAction<GradleExecuter>(action)); } @Override public void afterExecute(Action<? super GradleExecuter> action) { afterExecute = afterExecute.add(action); } @Override public void afterExecute(@DelegatesTo(GradleExecuter.class) Closure action) { afterExecute(new ClosureBackedAction<GradleExecuter>(action)); } @Override public GradleExecuter inDirectory(File directory) { workingDir = directory; return this; } public File getWorkingDir() { return workingDir == null ? getTestDirectoryProvider().getTestDirectory() : workingDir; } @Override public GradleExecuter copyTo(GradleExecuter executer) { executer.withGradleUserHomeDir(gradleUserHomeDir); executer.withDaemonIdleTimeoutSecs(daemonIdleTimeoutSecs); executer.withDaemonBaseDir(daemonBaseDir); if (workingDir != null) { executer.inDirectory(workingDir); } if (projectDir != null) { executer.usingProjectDirectory(projectDir); } if (buildScript != null) { executer.usingBuildScript(buildScript); } if (settingsFile != null) { executer.usingSettingsFile(settingsFile); } if (ignoreMissingSettingsFile) { executer.ignoreMissingSettingsFile(); } if (javaHome != null) { executer.withJavaHome(javaHome); } for (File initScript : initScripts) { executer.usingInitScript(initScript); } executer.withTasks(tasks); executer.withArguments(args); executer.withEnvironmentVars(environmentVars); executer.usingExecutable(executable); if (quiet) { executer.withQuietLogging(); } if (taskList) { executer.withTaskList(); } if (dependencyList) { executer.withDependencyList(); } if (userHomeDir != null) { executer.withUserHomeDir(userHomeDir); } if (stdinPipe != null) { executer.withStdinPipe(stdinPipe); } if (defaultCharacterEncoding != null) { executer.withDefaultCharacterEncoding(defaultCharacterEncoding); } if (noExplicitTmpDir) { executer.withNoExplicitTmpDir(); } if (noExplicitNativeServicesDir) { executer.withNoExplicitNativeServicesDir(); } if (!fullDeprecationStackTrace) { executer.withFullDeprecationStackTraceDisabled(); } if (defaultLocale != null) { executer.withDefaultLocale(defaultLocale); } executer.withCommandLineGradleOpts(commandLineJvmOpts); executer.withBuildJvmOpts(buildJvmOpts); if (useOnlyRequestedJvmOpts) { executer.useOnlyRequestedJvmOpts(); } executer.noExtraLogging(); if (expectedGenericDeprecationWarnings > 0) { executer.expectDeprecationWarnings(expectedGenericDeprecationWarnings); } expectedDeprecationWarnings.forEach(executer::expectDeprecationWarning); if (!eagerClassLoaderCreationChecksOn) { executer.withEagerClassLoaderCreationCheckDisabled(); } if (!stackTraceChecksOn) { executer.withStackTraceChecksDisabled(); } if (requiresGradleDistribution) { executer.requireGradleDistribution(); } if (useOwnUserHomeServices) { executer.withOwnUserHomeServices(); } if (requireDaemon) { executer.requireDaemon(); } executer.startBuildProcessInDebugger(debug); executer.startLauncherInDebugger(debugLauncher); executer.withProfiler(profiler); executer.withForceInteractive(interactive); if (!checkDeprecations) { executer.noDeprecationChecks(); } if (durationMeasurement != null) { executer.withDurationMeasurement(durationMeasurement); } if (consoleType != null) { executer.withConsole(consoleType); } executer.withWarningMode(warningMode); if (!showStacktrace) { executer.withStacktraceDisabled(); } if (renderWelcomeMessage) { executer.withWelcomeMessageEnabled(); } executer.withTestConsoleAttached(consoleAttachment); return executer; } @Override public GradleExecuter usingBuildScript(File buildScript) { this.buildScript = buildScript; return this; } @Override public GradleExecuter usingProjectDirectory(File projectDir) { this.projectDir = projectDir; return this; } @Override public GradleExecuter usingSettingsFile(File settingsFile) { this.settingsFile = settingsFile; return this; } @Override public GradleExecuter usingInitScript(File initScript) { initScripts.add(initScript); return this; } @Override public TestFile getGradleUserHomeDir() { return gradleUserHomeDir; } @Override public GradleExecuter withGradleUserHomeDir(File userHomeDir) { this.gradleUserHomeDir = userHomeDir == null ? null : new TestFile(userHomeDir); return this; } @Override public GradleExecuter requireOwnGradleUserHomeDir() { return withGradleUserHomeDir(testDirectoryProvider.getTestDirectory().file("user-home")); } public File getUserHomeDir() { return userHomeDir; } protected GradleInvocation buildInvocation() { validateDaemonVisibility(); GradleInvocation gradleInvocation = new GradleInvocation(); gradleInvocation.environmentVars.putAll(environmentVars); if (!useOnlyRequestedJvmOpts) { gradleInvocation.buildJvmArgs.addAll(getImplicitBuildJvmArgs()); } gradleInvocation.buildJvmArgs.addAll(buildJvmOpts); calculateLauncherJvmArgs(gradleInvocation); gradleInvocation.args.addAll(getAllArgs()); transformInvocation(gradleInvocation); if (!gradleInvocation.implicitLauncherJvmArgs.isEmpty()) { throw new IllegalStateException("Implicit JVM args have not been handled."); } return gradleInvocation; } protected void validateDaemonVisibility() { if (isUseDaemon() && isSharedDaemons()) { throw new IllegalStateException("Daemon that will be visible to other tests has been requested."); } } /** * Adjusts the calculated invocation prior to execution. This method is responsible for handling the implicit launcher JVM args in some way, by mutating the invocation appropriately. */ protected void transformInvocation(GradleInvocation gradleInvocation) { gradleInvocation.launcherJvmArgs.addAll(0, gradleInvocation.implicitLauncherJvmArgs); gradleInvocation.implicitLauncherJvmArgs.clear(); } /** * Returns the JVM opts that should be used to start a forked JVM. */ private void calculateLauncherJvmArgs(GradleInvocation gradleInvocation) { // Add JVM args that were explicitly requested gradleInvocation.launcherJvmArgs.addAll(commandLineJvmOpts); if (isUseDaemon() && !gradleInvocation.buildJvmArgs.isEmpty()) { // Pass build JVM args through to daemon via system property on the launcher JVM String quotedArgs = join(" ", collect(gradleInvocation.buildJvmArgs, new Transformer<String, String>() { @Override public String transform(String input) { return String.format("'%s'", input); } })); gradleInvocation.implicitLauncherJvmArgs.add("-Dorg.gradle.jvmargs=" + quotedArgs); } else { // Have to pass build JVM args directly to launcher JVM gradleInvocation.launcherJvmArgs.addAll(gradleInvocation.buildJvmArgs); } // Set the implicit system properties regardless of whether default JVM args are required or not, this should not interfere with tests' intentions // These will also be copied across to any daemon used for (Map.Entry<String, String> entry : getImplicitJvmSystemProperties().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); gradleInvocation.implicitLauncherJvmArgs.add(String.format("-D%s=%s", key, value)); } if (isDebugLauncher()) { gradleInvocation.implicitLauncherJvmArgs.addAll(DEBUG_ARGS); } gradleInvocation.implicitLauncherJvmArgs.add("-ea"); } /** * Returns additional JVM args that should be used to start the build JVM. */ protected List<String> getImplicitBuildJvmArgs() { List<String> buildJvmOpts = new ArrayList<String>(); buildJvmOpts.add("-ea"); if (isDebug()) { buildJvmOpts.addAll(DEBUG_ARGS); } if (isProfile()) { buildJvmOpts.add(profiler); } if (isSharedDaemons()) { buildJvmOpts.add("-Xms256m"); buildJvmOpts.add("-Xmx1024m"); } else { buildJvmOpts.add("-Xms256m"); buildJvmOpts.add("-Xmx512m"); } if (JVM_VERSION_DETECTOR.getJavaVersion(Jvm.forHome(getJavaHome())).compareTo(JavaVersion.VERSION_1_8) < 0) { buildJvmOpts.add("-XX:MaxPermSize=320m"); } else { buildJvmOpts.add("-XX:MaxMetaspaceSize=512m"); } buildJvmOpts.add("-XX:+HeapDumpOnOutOfMemoryError"); buildJvmOpts.add("-XX:HeapDumpPath=" + buildContext.getGradleUserHomeDir()); return buildJvmOpts; } private boolean xmxSpecified() { for (String arg : buildJvmOpts) { if (arg.startsWith("-Xmx")) { return true; } } return false; } @Override public GradleExecuter withUserHomeDir(File userHomeDir) { this.userHomeDir = userHomeDir; return this; } public File getJavaHome() { return javaHome == null ? Jvm.current().getJavaHome() : javaHome; } @Override public GradleExecuter withJavaHome(File javaHome) { this.javaHome = javaHome; return this; } @Override public GradleExecuter usingExecutable(String script) { this.executable = script; return this; } public String getExecutable() { return executable; } @Override public GradleExecuter withStdinPipe() { return withStdinPipe(new PipedOutputStream()); } @Override public GradleExecuter withStdinPipe(PipedOutputStream stdInPipe) { this.stdinPipe = stdInPipe; return this; } public InputStream connectStdIn() { try { return stdinPipe == null ? SafeStreams.emptyInput() : new PipedInputStream(stdinPipe); } catch (IOException e) { throw UncheckedException.throwAsUncheckedException(e); } } public PipedOutputStream getStdinPipe() { return stdinPipe; } @Override public GradleExecuter withDefaultCharacterEncoding(String defaultCharacterEncoding) { this.defaultCharacterEncoding = defaultCharacterEncoding; return this; } public String getDefaultCharacterEncoding() { return defaultCharacterEncoding == null ? Charset.defaultCharset().name() : defaultCharacterEncoding; } @Override public GradleExecuter withDefaultLocale(Locale defaultLocale) { this.defaultLocale = defaultLocale; return this; } public Locale getDefaultLocale() { return defaultLocale; } public boolean isQuiet() { return quiet; } @Override public GradleExecuter withQuietLogging() { quiet = true; return this; } @Override public GradleExecuter withTaskList() { taskList = true; return this; } @Override public GradleExecuter withDependencyList() { dependencyList = true; return this; } @Override public GradleExecuter withArguments(String... args) { return withArguments(Arrays.asList(args)); } @Override public GradleExecuter withArguments(List<String> args) { this.args.clear(); this.args.addAll(args); return this; } @Override public GradleExecuter withArgument(String arg) { this.args.add(arg); return this; } @Override public GradleExecuter withEnvironmentVars(Map<String, ?> environment) { environmentVars.clear(); for (Map.Entry<String, ?> entry : environment.entrySet()) { environmentVars.put(entry.getKey(), entry.getValue().toString()); } return this; } protected String toJvmArgsString(Iterable<String> jvmArgs) { StringBuilder result = new StringBuilder(); for (String jvmArg : jvmArgs) { if (result.length() > 0) { result.append(" "); } if (jvmArg.contains(" ")) { assert !jvmArg.contains("\"") : "jvmArg '" + jvmArg + "' contains '\"'"; result.append('"'); result.append(jvmArg); result.append('"'); } else { result.append(jvmArg); } } return result.toString(); } @Override public GradleExecuter withTasks(String... names) { return withTasks(Arrays.asList(names)); } @Override public GradleExecuter withTasks(List<String> names) { tasks.clear(); tasks.addAll(names); return this; } @Override public GradleExecuter withDaemonIdleTimeoutSecs(int secs) { daemonIdleTimeoutSecs = secs; return this; } @Override public GradleExecuter useOnlyRequestedJvmOpts() { useOnlyRequestedJvmOpts = true; return this; } @Override public GradleExecuter withDaemonBaseDir(File daemonBaseDir) { this.daemonBaseDir = daemonBaseDir; return this; } @Override public GradleExecuter requireIsolatedDaemons() { return withDaemonBaseDir(testDirectoryProvider.getTestDirectory().file("daemon")); } @Override public GradleExecuter withWorkerDaemonsExpirationDisabled() { return withCommandLineGradleOpts("-Dorg.gradle.workers.internal.disable-daemons-expiration=true"); } @Override public boolean usesSharedDaemons() { return isSharedDaemons(); } @Override public File getDaemonBaseDir() { return daemonBaseDir; } @Override public GradleExecuter requireDaemon() { this.requireDaemon = true; return this; } protected boolean isSharedDaemons() { return daemonBaseDir.equals(buildContext.getDaemonBaseDir()); } @Override public boolean isUseDaemon() { CliDaemonArgument cliDaemonArgument = resolveCliDaemonArgument(); if (cliDaemonArgument == NO_DAEMON || cliDaemonArgument == FOREGROUND) { return false; } return requireDaemon || cliDaemonArgument == DAEMON; } @Override public GradleExecuter withOwnUserHomeServices() { useOwnUserHomeServices = true; return this; } @Override public GradleExecuter withWarningMode(WarningMode warningMode) { this.warningMode = warningMode; return this; } @Override public GradleExecuter withConsole(ConsoleOutput consoleType) { this.consoleType = consoleType; return this; } @Override public GradleExecuter withStacktraceDisabled() { showStacktrace = false; return this; } @Override public GradleExecuter withWelcomeMessageEnabled() { renderWelcomeMessage = true; return this; } @Override public GradleExecuter withRepositoryMirrors() { beforeExecute(new Action<GradleExecuter>() { @Override public void execute(GradleExecuter gradleExecuter) { usingInitScript(RepoScriptBlockUtil.createMirrorInitScript()); } }); return this; } @Override public GradleExecuter withGlobalRepositoryMirrors() { beforeExecute(new Action<GradleExecuter>() { @Override public void execute(GradleExecuter gradleExecuter) { TestFile userHome = testDirectoryProvider.getTestDirectory().file("user-home"); withGradleUserHomeDir(userHome); userHome.file("init.d/mirrors.gradle").write(RepoScriptBlockUtil.mirrorInitScript()); } }); return this; } @Override public GradleExecuter withPluginRepositoryMirror() { beforeExecute(new Action<GradleExecuter>() { @Override public void execute(GradleExecuter gradleExecuter) { withArgument("-D" + PLUGIN_PORTAL_OVERRIDE_URL_PROPERTY + "=" + gradlePluginRepositoryMirrorUrl()); } }); return this; } /** * Performs cleanup at completion of the test. */ public void cleanup() { stopRunningBuilds(); cleanupIsolatedDaemons(); } private void stopRunningBuilds() { for (GradleHandle handle : running) { try { handle.abort().waitForExit(); } catch (Exception e) { getLogger().warn("Problem stopping running build", e); } } } private void cleanupIsolatedDaemons() { for (File baseDir : isolatedDaemonBaseDirs) { try { new DaemonLogsAnalyzer(baseDir, gradleVersion.getVersion()).killAll(); } catch (Exception e) { getLogger().warn("Problem killing isolated daemons of Gradle version " + gradleVersion + " in " + baseDir, e); } } } enum CliDaemonArgument { NOT_DEFINED, DAEMON, NO_DAEMON, FOREGROUND } protected CliDaemonArgument resolveCliDaemonArgument() { for (int i = args.size() - 1; i >= 0; i--) { final String arg = args.get(i); if (arg.equals("--daemon")) { return DAEMON; } if (arg.equals("--no-daemon")) { return NO_DAEMON; } if (arg.equals("--foreground")) { return FOREGROUND; } } return NOT_DEFINED; } private boolean noDaemonArgumentGiven() { return resolveCliDaemonArgument() == NOT_DEFINED; } protected List<String> getAllArgs() { List<String> allArgs = new ArrayList<String>(); if (buildScript != null) { allArgs.add("--build-file"); allArgs.add(buildScript.getAbsolutePath()); } if (projectDir != null) { allArgs.add("--project-dir"); allArgs.add(projectDir.getAbsolutePath()); } for (File initScript : initScripts) { allArgs.add("--init-script"); allArgs.add(initScript.getAbsolutePath()); } if (settingsFile != null) { allArgs.add("--settings-file"); allArgs.add(settingsFile.getAbsolutePath()); } if (quiet) { allArgs.add("--quiet"); } if (noDaemonArgumentGiven()) { if (isUseDaemon()) { allArgs.add("--daemon"); } else { allArgs.add("--no-daemon"); } } if (showStacktrace) { allArgs.add("--stacktrace"); } if (taskList) { allArgs.add("tasks"); } if (dependencyList) { allArgs.add("dependencies"); } if (settingsFile == null && !ignoreMissingSettingsFile) { ensureSettingsFileAvailable(); } // This will cause problems on Windows if the path to the Gradle executable that is used has a space in it (e.g. the user's dir is c:/Users/Luke Daley/) // This is fundamentally a windows issue: You can't have arguments with spaces in them if the path to the batch script has a space // We could work around this by setting -Dgradle.user.home but GRADLE-1730 (which affects 1.0-milestone-3) means that that // is problematic as well. For now, we just don't support running the int tests from a path with a space in it on Windows. // When we stop testing against M3 we should change to use the system property. if (getGradleUserHomeDir() != null) { allArgs.add("--gradle-user-home"); allArgs.add(getGradleUserHomeDir().getAbsolutePath()); } if (consoleType != null) { allArgs.add("--console=" + consoleType.toString().toLowerCase()); } if (warningMode != null) { allArgs.add("--warning-mode=" + warningMode.toString().toLowerCase(Locale.ENGLISH)); } allArgs.addAll(args); allArgs.addAll(tasks); return allArgs; } @Override public GradleExecuter ignoreMissingSettingsFile() { ignoreMissingSettingsFile = true; return this; } private void ensureSettingsFileAvailable() { TestFile workingDir = new TestFile(getWorkingDir()); TestFile dir = workingDir; while (dir != null && getTestDirectoryProvider().getTestDirectory().isSelfOrDescendent(dir)) { if (hasSettingsFile(dir) || hasSettingsFile(dir.file("master"))) { return; } dir = dir.getParentFile(); } workingDir.createFile("settings.gradle"); } private boolean hasSettingsFile(TestFile dir) { if (dir.isDirectory()) { return dir.file("settings.gradle").isFile() || dir.file("settings.gradle.kts").isFile(); } return false; } /** * Returns the set of system properties that should be set on every JVM used by this executer. */ protected Map<String, String> getImplicitJvmSystemProperties() { Map<String, String> properties = new LinkedHashMap<String, String>(); if (getUserHomeDir() != null) { properties.put("user.home", getUserHomeDir().getAbsolutePath()); } properties.put(DaemonBuildOptions.IdleTimeoutOption.GRADLE_PROPERTY, "" + (daemonIdleTimeoutSecs * 1000)); properties.put(DaemonBuildOptions.BaseDirOption.GRADLE_PROPERTY, daemonBaseDir.getAbsolutePath()); if (!noExplicitNativeServicesDir) { properties.put(NativeServices.NATIVE_DIR_OVERRIDE, buildContext.getNativeServicesDir().getAbsolutePath()); } properties.put(LoggingDeprecatedFeatureHandler.ORG_GRADLE_DEPRECATION_TRACE_PROPERTY_NAME, Boolean.toString(fullDeprecationStackTrace)); boolean useCustomGradleUserHomeDir = gradleUserHomeDir != null && !gradleUserHomeDir.equals(buildContext.getGradleUserHomeDir()); if (useOwnUserHomeServices || useCustomGradleUserHomeDir) { properties.put(REUSE_USER_HOME_SERVICES, "false"); } if (!useCustomGradleUserHomeDir) { TestFile generatedApiJarCacheDir = buildContext.getGradleGeneratedApiJarCacheDir(); if (generatedApiJarCacheDir != null) { properties.put(DefaultGeneratedGradleJarCache.BASE_DIR_OVERRIDE_PROPERTY, generatedApiJarCacheDir.getAbsolutePath()); } } if (!noExplicitTmpDir) { if (tmpDir == null) { tmpDir = getDefaultTmpDir(); } String tmpDirPath = tmpDir.createDir().getAbsolutePath(); if (!tmpDirPath.contains(" ") || (getDistribution().isSupportsSpacesInGradleAndJavaOpts() && supportsWhiteSpaceInEnvVars())) { properties.put("java.io.tmpdir", tmpDirPath); } } properties.put("file.encoding", getDefaultCharacterEncoding()); Locale locale = getDefaultLocale(); if (locale != null) { properties.put("user.language", locale.getLanguage()); properties.put("user.country", locale.getCountry()); properties.put("user.variant", locale.getVariant()); } if (eagerClassLoaderCreationChecksOn) { properties.put(DefaultClassLoaderScope.STRICT_MODE_PROPERTY, "true"); } if (interactive) { properties.put(TestOverrideConsoleDetector.INTERACTIVE_TOGGLE, "true"); } // Enable VFS properties.put(GradleUserHomeScopeServices.ENABLE_VFS_SYSTEM_PROPERTY_NAME, "true"); properties.put(DefaultCommandLineActionFactory.WELCOME_MESSAGE_ENABLED_SYSTEM_PROPERTY, Boolean.toString(renderWelcomeMessage)); return properties; } protected boolean supportsWhiteSpaceInEnvVars() { return true; } @Override public final GradleHandle start() { assert afterExecute.isEmpty() : "afterExecute actions are not implemented for async execution"; return startHandle(); } protected GradleHandle startHandle() { fireBeforeExecute(); assertCanExecute(); collectStateBeforeExecution(); try { GradleHandle handle = createGradleHandle(); running.add(handle); return handle; } finally { reset(); } } @Override public final ExecutionResult run() { fireBeforeExecute(); assertCanExecute(); collectStateBeforeExecution(); try { ExecutionResult result = doRun(); if (errorsShouldAppearOnStdout()) { result = new ErrorsOnStdoutScrapingExecutionResult(result); } afterExecute.execute(this); return result; } finally { finished(); } } protected void finished() { reset(); } @Override public final ExecutionFailure runWithFailure() { fireBeforeExecute(); assertCanExecute(); collectStateBeforeExecution(); try { ExecutionFailure executionFailure = doRunWithFailure(); if (errorsShouldAppearOnStdout()) { executionFailure = new ErrorsOnStdoutScrapingExecutionFailure(executionFailure); } afterExecute.execute(this); return executionFailure; } finally { finished(); } } private void collectStateBeforeExecution() { if (!isSharedDaemons()) { isolatedDaemonBaseDirs.add(daemonBaseDir); } } private void fireBeforeExecute() { beforeExecute.execute(this); } protected GradleHandle createGradleHandle() { throw new UnsupportedOperationException(String.format("%s does not support running asynchronously.", getClass().getSimpleName())); } protected abstract ExecutionResult doRun(); protected abstract ExecutionFailure doRunWithFailure(); @Override public GradleExecuter withCommandLineGradleOpts(Iterable<String> jvmOpts) { CollectionUtils.addAll(commandLineJvmOpts, jvmOpts); return this; } @Override public GradleExecuter withCommandLineGradleOpts(String... jvmOpts) { CollectionUtils.addAll(commandLineJvmOpts, jvmOpts); return this; } @Override public AbstractGradleExecuter withBuildJvmOpts(String... jvmOpts) { CollectionUtils.addAll(buildJvmOpts, jvmOpts); return this; } @Override public GradleExecuter withBuildJvmOpts(Iterable<String> jvmOpts) { CollectionUtils.addAll(buildJvmOpts, jvmOpts); return this; } @Override public GradleExecuter withBuildCacheEnabled() { return withArgument("--build-cache"); } protected Action<ExecutionResult> getResultAssertion() { return new Action<ExecutionResult>() { private int expectedGenericDeprecationWarnings = AbstractGradleExecuter.this.expectedGenericDeprecationWarnings; private final List<String> expectedDeprecationWarnings = new ArrayList<>(AbstractGradleExecuter.this.expectedDeprecationWarnings); private final boolean expectStackTraces = !AbstractGradleExecuter.this.stackTraceChecksOn; private final boolean checkDeprecations = AbstractGradleExecuter.this.checkDeprecations; @Override public void execute(ExecutionResult executionResult) { String normalizedOutput = executionResult.getNormalizedOutput(); String error = executionResult.getError(); boolean executionFailure = isExecutionFailure(executionResult); // for tests using rich console standard out and error are combined in output of execution result if (executionFailure) { normalizedOutput = removeExceptionStackTraceForFailedExecution(normalizedOutput); } validate(normalizedOutput, "Standard output"); if (executionFailure) { error = removeExceptionStackTraceForFailedExecution(error); } validate(error, "Standard error"); if (!expectedDeprecationWarnings.isEmpty()) { throw new AssertionError(String.format("Expected the following deprecation warnings:%n%s", expectedDeprecationWarnings.stream() .map(warning -> " - " + warning) .collect(Collectors.joining("\n")))); } if (expectedGenericDeprecationWarnings > 0) { throw new AssertionError(String.format("Expected %d more deprecation warnings", expectedGenericDeprecationWarnings)); } } private boolean isErrorOutEmpty(String error) { //remove SLF4J error out like 'Class path contains multiple SLF4J bindings.' //See: https://github.com/gradle/performance/issues/375#issuecomment-315103861 return Strings.isNullOrEmpty(error.replaceAll("(?m)^SLF4J: .*", "").trim()); } private boolean isExecutionFailure(ExecutionResult executionResult) { return executionResult instanceof ExecutionFailure; } // Axe everything after the expected exception private String removeExceptionStackTraceForFailedExecution(String text) { int pos = text.indexOf("* Exception is:"); if (pos >= 0) { text = text.substring(0, pos); } return text; } private void validate(String output, String displayName) { List<String> lines; try { lines = CharSource.wrap(output).readLines(); } catch (IOException e) { throw new UncheckedIOException(e); } int i = 0; boolean insideVariantDescriptionBlock = false; while (i < lines.size()) { String line = lines.get(i); if (insideVariantDescriptionBlock && line.contains("]")) { insideVariantDescriptionBlock = false; } else if (!insideVariantDescriptionBlock && line.contains("variant \"")) { insideVariantDescriptionBlock = true; } if (line.matches(".*use(s)? or override(s)? a deprecated API\\.")) { // A javac warning, ignore i++; } else if (line.matches(".*w: .* is deprecated\\..*")) { // A kotlinc warning, ignore i++; } else if (isDeprecationMessageInHelpDescription(line)) { i++; } else if (expectedDeprecationWarnings.remove(line)) { // Deprecation warning is expected i++; i = skipStackTrace(lines, i); } else if (line.matches(".*\\s+deprecated.*")) { if (checkDeprecations && expectedGenericDeprecationWarnings <= 0) { throw new AssertionError(String.format("%s line %d contains a deprecation warning: %s%n=====%n%s%n=====%n", displayName, i + 1, line, output)); } expectedGenericDeprecationWarnings--; // skip over stack trace i++; i = skipStackTrace(lines, i); } else if (!expectStackTraces && !insideVariantDescriptionBlock && STACK_TRACE_ELEMENT.matcher(line).matches() && i < lines.size() - 1 && STACK_TRACE_ELEMENT.matcher(lines.get(i + 1)).matches()) { // 2 or more lines that look like stack trace elements throw new AssertionError(String.format("%s line %d contains an unexpected stack trace: %s%n=====%n%s%n=====%n", displayName, i + 1, line, output)); } else { i++; } } } private int skipStackTrace(List<String> lines, int i) { while (i < lines.size() && STACK_TRACE_ELEMENT.matcher(lines.get(i)).matches()) { i++; } return i; } private boolean isDeprecationMessageInHelpDescription(String s) { return s.matches(".*\\[deprecated.*]"); } }; } @Override public GradleExecuter expectDeprecationWarning() { return expectDeprecationWarnings(1); } @Override public GradleExecuter expectDeprecationWarnings(int count) { Preconditions.checkState(expectedGenericDeprecationWarnings == 0, "expected deprecation count is already set for this execution"); Preconditions.checkArgument(count > 0, "expected deprecation count must be positive"); expectedGenericDeprecationWarnings = count; return this; } @Override public GradleExecuter expectDeprecationWarning(String warning) { expectedDeprecationWarnings.add(warning); return this; } @Override public GradleExecuter noDeprecationChecks() { checkDeprecations = false; return this; } @Override public GradleExecuter withEagerClassLoaderCreationCheckDisabled() { eagerClassLoaderCreationChecksOn = false; return this; } @Override public GradleExecuter withStackTraceChecksDisabled() { stackTraceChecksOn = false; return this; } protected TestFile getDefaultTmpDir() { return buildContext.getTmpDir().createDir(); } @Override public GradleExecuter noExtraLogging() { this.allowExtraLogging = false; return this; } public boolean isAllowExtraLogging() { return allowExtraLogging; } public boolean isRequiresGradleDistribution() { return requiresGradleDistribution; } @Override public GradleExecuter requireGradleDistribution() { this.requiresGradleDistribution = true; return this; } @Override public GradleExecuter startBuildProcessInDebugger(boolean flag) { debug = flag; return this; } @Override public GradleExecuter startLauncherInDebugger(boolean flag) { debugLauncher = flag; return this; } @Override public boolean isDebugLauncher() { return debugLauncher; } @Override public GradleExecuter withProfiler(String args) { profiler = args; return this; } @Override public GradleExecuter withForceInteractive(boolean flag) { interactive = flag; return this; } @Override public GradleExecuter withNoExplicitTmpDir() { noExplicitTmpDir = true; return this; } @Override public GradleExecuter withNoExplicitNativeServicesDir() { noExplicitNativeServicesDir = true; return this; } @Override public GradleExecuter withFullDeprecationStackTraceDisabled() { fullDeprecationStackTrace = false; return this; } @Override public boolean isDebug() { return debug; } @Override public boolean isProfile() { return !profiler.isEmpty(); } protected static class GradleInvocation { final Map<String, String> environmentVars = new HashMap<String, String>(); final List<String> args = new ArrayList<String>(); // JVM args that must be used for the build JVM final List<String> buildJvmArgs = new ArrayList<String>(); // JVM args that must be used to fork a JVM final List<String> launcherJvmArgs = new ArrayList<String>(); // Implicit JVM args that should be used to fork a JVM final List<String> implicitLauncherJvmArgs = new ArrayList<String>(); } @Override public void stop() { cleanup(); } @Override public GradleExecuter withDurationMeasurement(DurationMeasurement durationMeasurement) { this.durationMeasurement = durationMeasurement; return this; } protected void startMeasurement() { if (durationMeasurement != null) { durationMeasurement.start(); } } protected void stopMeasurement() { if (durationMeasurement != null) { durationMeasurement.stop(); } } protected DurationMeasurement getDurationMeasurement() { return durationMeasurement; } private static LoggingServiceRegistry newCommandLineProcessLogging() { LoggingServiceRegistry loggingServices = LoggingServiceRegistry.newEmbeddableLogging(); LoggingManagerInternal rootLoggingManager = loggingServices.get(DefaultLoggingManagerFactory.class).getRoot(); rootLoggingManager.attachSystemOutAndErr(); return loggingServices; } @Override public GradleExecuter withTestConsoleAttached() { return withTestConsoleAttached(ConsoleAttachment.ATTACHED); } @Override public GradleExecuter withTestConsoleAttached(ConsoleAttachment consoleAttachment) { this.consoleAttachment = consoleAttachment; return configureConsoleCommandLineArgs(); } protected GradleExecuter configureConsoleCommandLineArgs() { if (consoleAttachment == ConsoleAttachment.NOT_ATTACHED) { return this; } else { return withCommandLineGradleOpts(consoleAttachment.getConsoleMetaData().getCommandLineArgument()); } } private boolean errorsShouldAppearOnStdout() { // If stdout and stderr are attached to the console return consoleAttachment.isStderrAttached() && consoleAttachment.isStdoutAttached(); } }
Remove code to disable VFS via system property
subprojects/internal-integ-testing/src/main/groovy/org/gradle/integtests/fixtures/executer/AbstractGradleExecuter.java
Remove code to disable VFS via system property
Java
apache-2.0
a569803a232869d835335282745f412f2b1166fa
0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
/* * 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.shardingsphere.core.parsing.antlr.rule.registry; import com.google.common.base.Optional; import org.apache.shardingsphere.core.constant.DatabaseType; import org.apache.shardingsphere.core.parsing.antlr.filler.SQLSegmentFiller; import org.apache.shardingsphere.core.parsing.antlr.rule.jaxb.loader.RuleDefinitionFileConstant; import org.apache.shardingsphere.core.parsing.antlr.rule.jaxb.loader.extractor.ExtractorRuleDefinitionEntityLoader; import org.apache.shardingsphere.core.parsing.antlr.rule.jaxb.loader.filler.FillerRuleDefinitionEntityLoader; import org.apache.shardingsphere.core.parsing.antlr.rule.jaxb.loader.statement.SQLStatementRuleDefinitionEntityLoader; import org.apache.shardingsphere.core.parsing.antlr.rule.registry.statement.SQLStatementRule; import org.apache.shardingsphere.core.parsing.antlr.sql.segment.SQLSegment; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Parsing rule registry. * * @author zhangliang * @author duhongjun */ public abstract class ParsingRuleRegistry { private final SQLStatementRuleDefinitionEntityLoader statementRuleDefinitionLoader = new SQLStatementRuleDefinitionEntityLoader(); private final ExtractorRuleDefinitionEntityLoader extractorRuleDefinitionLoader = new ExtractorRuleDefinitionEntityLoader(); private final FillerRuleDefinitionEntityLoader fillerRuleDefinitionLoader = new FillerRuleDefinitionEntityLoader(); private final ParserRuleDefinition commonRuleDefinition = new ParserRuleDefinition(); private final Map<DatabaseType, ParserRuleDefinition> parserRuleDefinitions = new HashMap<>(4, 1); protected void init() { initCommonParserRuleDefinition(); initParserRuleDefinition(); } private void initCommonParserRuleDefinition() { List<String> fillerFilePaths = Arrays.asList(new String[]{RuleDefinitionFileConstant.getCommonFillerRuleDefinitionFileName()}); List<String> extractorFilePaths = Arrays.asList(new String[]{RuleDefinitionFileConstant.getCommonExtractorRuleDefinitionFileName()}); initParserRuleDefinition(commonRuleDefinition, fillerFilePaths, extractorFilePaths, new ArrayList<String>()); } private void initParserRuleDefinition() { for (DatabaseType each : DatabaseType.values()) { if (DatabaseType.H2 != each) { if (!needParser(each)) { continue; } List<String> fillerFilePaths = new LinkedList<>(); List<String> extractorFilePaths = new LinkedList<>(); List<String> sqlStateRuleFilePaths = new LinkedList<>(); fillRuleFilePaths(each, fillerFilePaths, extractorFilePaths, sqlStateRuleFilePaths); ParserRuleDefinition shardingRuleDefinition = new ParserRuleDefinition(); initParserRuleDefinitionFromCommon(shardingRuleDefinition, fillerFilePaths, extractorFilePaths, sqlStateRuleFilePaths); parserRuleDefinitions.put(each, shardingRuleDefinition); } } } protected boolean needParser(final DatabaseType databaseType) { return true; } protected abstract void fillRuleFilePaths(DatabaseType databaseType, List<String> fillerFilePaths, List<String> extractorFilePaths, List<String> sqlStateRuleFilePaths); private void initParserRuleDefinitionFromCommon(final ParserRuleDefinition parserRuleDefinition, final List<String> fillerFilePaths, final List<String> extractorFilePaths, final List<String> sqlStateRuleFilePaths) { parserRuleDefinition.getExtractorRuleDefinition().getRules().putAll(commonRuleDefinition.getExtractorRuleDefinition().getRules()); parserRuleDefinition.getFillerRuleDefinition().getRules().putAll(commonRuleDefinition.getFillerRuleDefinition().getRules()); initParserRuleDefinition(parserRuleDefinition, fillerFilePaths, extractorFilePaths, sqlStateRuleFilePaths); } private void initParserRuleDefinition(final ParserRuleDefinition parserRuleDefinition, final List<String> fillerFilePaths, final List<String> extractorFilePaths, final List<String> sqlStateRuleFilePaths) { for (String each : fillerFilePaths) { parserRuleDefinition.getFillerRuleDefinition().init(fillerRuleDefinitionLoader.load(each)); } for (String each : extractorFilePaths) { parserRuleDefinition.getExtractorRuleDefinition().init(extractorRuleDefinitionLoader.load(each)); } for (String each : sqlStateRuleFilePaths) { parserRuleDefinition.getSqlStatementRuleDefinition().init(statementRuleDefinitionLoader.load(each), parserRuleDefinition.getExtractorRuleDefinition()); } } /** * Find SQL statement rule. * * @param databaseType database type * @param contextClassName context class name * @return SQL statement rule */ public Optional<SQLStatementRule> findSQLStatementRule(final DatabaseType databaseType, final String contextClassName) { return Optional.fromNullable(parserRuleDefinitions.get(DatabaseType.H2 == databaseType ? DatabaseType.MySQL : databaseType).getSqlStatementRuleDefinition().getRules().get(contextClassName)); } /** * Find SQL segment rule. * * @param databaseType database type * @param sqlSegmentClass SQL segment class * @return SQL segment rule */ public Optional<SQLSegmentFiller> findSQLSegmentFiller(final DatabaseType databaseType, final Class<? extends SQLSegment> sqlSegmentClass) { return Optional.fromNullable(parserRuleDefinitions.get(DatabaseType.H2 == databaseType ? DatabaseType.MySQL : databaseType).getFillerRuleDefinition().getRules().get(sqlSegmentClass)); } }
sharding-core/sharding-core-parser/sharding-core-parser-common/src/main/java/org/apache/shardingsphere/core/parsing/antlr/rule/registry/ParsingRuleRegistry.java
/* * 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.shardingsphere.core.parsing.antlr.rule.registry; import com.google.common.base.Optional; import org.apache.shardingsphere.core.constant.DatabaseType; import org.apache.shardingsphere.core.parsing.antlr.filler.SQLSegmentFiller; import org.apache.shardingsphere.core.parsing.antlr.rule.jaxb.loader.RuleDefinitionFileConstant; import org.apache.shardingsphere.core.parsing.antlr.rule.jaxb.loader.extractor.ExtractorRuleDefinitionEntityLoader; import org.apache.shardingsphere.core.parsing.antlr.rule.jaxb.loader.filler.FillerRuleDefinitionEntityLoader; import org.apache.shardingsphere.core.parsing.antlr.rule.jaxb.loader.statement.SQLStatementRuleDefinitionEntityLoader; import org.apache.shardingsphere.core.parsing.antlr.rule.registry.statement.SQLStatementRule; import org.apache.shardingsphere.core.parsing.antlr.sql.segment.SQLSegment; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Parsing rule registry. * * @author zhangliang * @author duhongjun */ public abstract class ParsingRuleRegistry { private final SQLStatementRuleDefinitionEntityLoader statementRuleDefinitionLoader = new SQLStatementRuleDefinitionEntityLoader(); private final ExtractorRuleDefinitionEntityLoader extractorRuleDefinitionLoader = new ExtractorRuleDefinitionEntityLoader(); private final FillerRuleDefinitionEntityLoader fillerRuleDefinitionLoader = new FillerRuleDefinitionEntityLoader(); private final ParserRuleDefinition commonRuleDefinition = new ParserRuleDefinition(); private final Map<DatabaseType, ParserRuleDefinition> parserRuleDefinitions = new HashMap<>(4, 1); protected void init() { initCommonParserRuleDefinition(); initParserRuleDefinition(); } private void initCommonParserRuleDefinition() { List<String> fillerFilePaths = Arrays.asList(new String[]{RuleDefinitionFileConstant.getCommonFillerRuleDefinitionFileName()}); List<String> extractorFilePaths = Arrays.asList(new String[]{RuleDefinitionFileConstant.getCommonExtractorRuleDefinitionFileName()}); initParserRuleDefinition(commonRuleDefinition, fillerFilePaths, extractorFilePaths, new ArrayList<String>()); } private void initParserRuleDefinition() { for (DatabaseType each : DatabaseType.values()) { if (DatabaseType.H2 != each) { if(!needParser(each)){ continue; } List<String> fillerFilePaths = new LinkedList<>(); List<String> extractorFilePaths = new LinkedList<>(); List<String> sqlStateRuleFilePaths = new LinkedList<>(); fillRuleFilePaths(each, fillerFilePaths, extractorFilePaths, sqlStateRuleFilePaths); ParserRuleDefinition shardingRuleDefinition = new ParserRuleDefinition(); initParserRuleDefinitionFromCommon(shardingRuleDefinition, fillerFilePaths, extractorFilePaths, sqlStateRuleFilePaths); parserRuleDefinitions.put(each, shardingRuleDefinition); } } } protected boolean needParser(final DatabaseType databaseType) { return true; } protected abstract void fillRuleFilePaths(final DatabaseType databaseType, final List<String> fillerFilePaths, final List<String> extractorFilePaths, final List<String> sqlStateRuleFilePaths); private void initParserRuleDefinitionFromCommon(final ParserRuleDefinition parserRuleDefinition, final List<String> fillerFilePaths, final List<String> extractorFilePaths, final List<String> sqlStateRuleFilePaths) { parserRuleDefinition.getExtractorRuleDefinition().getRules().putAll(commonRuleDefinition.getExtractorRuleDefinition().getRules()); parserRuleDefinition.getFillerRuleDefinition().getRules().putAll(commonRuleDefinition.getFillerRuleDefinition().getRules()); initParserRuleDefinition(parserRuleDefinition, fillerFilePaths, extractorFilePaths, sqlStateRuleFilePaths); } private void initParserRuleDefinition(final ParserRuleDefinition parserRuleDefinition, final List<String> fillerFilePaths, final List<String> extractorFilePaths, final List<String> sqlStateRuleFilePaths) { for (String each : fillerFilePaths) { parserRuleDefinition.getFillerRuleDefinition().init(fillerRuleDefinitionLoader.load(each)); } for (String each : extractorFilePaths) { parserRuleDefinition.getExtractorRuleDefinition().init(extractorRuleDefinitionLoader.load(each)); } for (String each : sqlStateRuleFilePaths) { parserRuleDefinition.getSqlStatementRuleDefinition().init(statementRuleDefinitionLoader.load(each), parserRuleDefinition.getExtractorRuleDefinition()); } } /** * Find SQL statement rule. * * @param databaseType database type * @param contextClassName context class name * @return SQL statement rule */ public Optional<SQLStatementRule> findSQLStatementRule(final DatabaseType databaseType, final String contextClassName) { return Optional.fromNullable(parserRuleDefinitions.get(DatabaseType.H2 == databaseType ? DatabaseType.MySQL : databaseType).getSqlStatementRuleDefinition().getRules().get(contextClassName)); } /** * Find SQL segment rule. * * @param databaseType database type * @param sqlSegmentClass SQL segment class * @return SQL segment rule */ public Optional<SQLSegmentFiller> findSQLSegmentFiller(final DatabaseType databaseType, final Class<? extends SQLSegment> sqlSegmentClass) { return Optional.fromNullable(parserRuleDefinitions.get(DatabaseType.H2 == databaseType ? DatabaseType.MySQL : databaseType).getFillerRuleDefinition().getRules().get(sqlSegmentClass)); } }
check style
sharding-core/sharding-core-parser/sharding-core-parser-common/src/main/java/org/apache/shardingsphere/core/parsing/antlr/rule/registry/ParsingRuleRegistry.java
check style
Java
apache-2.0
41198df721bd78044786961919f0504ab18044c0
0
GoogleCloudPlatform/java-docs-samples,GoogleCloudPlatform/java-docs-samples,GoogleCloudPlatform/java-docs-samples,GoogleCloudPlatform/java-docs-samples,GoogleCloudPlatform/java-docs-samples,GoogleCloudPlatform/java-docs-samples
/* * Copyright 2021 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 * * 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 compute; // [START compute_start_instance] import com.google.cloud.compute.v1.InstancesClient; import com.google.cloud.compute.v1.Operation; import com.google.cloud.compute.v1.Operation.Status; import com.google.cloud.compute.v1.StartInstanceRequest; import com.google.cloud.compute.v1.ZoneOperationsClient; import java.io.IOException; import java.util.concurrent.ExecutionException; public class StartInstance { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { // TODO(developer): Replace these variables before running the sample. /* project: project ID or project number of the Cloud project your instance belongs to. zone: name of the zone your instance belongs to. instanceName: name of the instance your want to start. */ String project = "your-project-id"; String zone = "zone-name"; String instanceName = "instance-name"; startInstance(project, zone, instanceName); } // Starts a stopped Google Compute Engine instance (with unencrypted disks). public static void startInstance(String project, String zone, String instanceName) throws IOException, ExecutionException, InterruptedException { /* Initialize client that will be used to send requests. This client only needs to be created once, and can be reused for multiple requests. After completing all of your requests, call the `instancesClient.close()` method on the client to safely clean up any remaining background resources. */ try (InstancesClient instancesClient = InstancesClient.create(); ZoneOperationsClient zoneOperationsClient = ZoneOperationsClient.create()) { // Create the request. StartInstanceRequest startInstanceRequest = StartInstanceRequest.newBuilder() .setProject(project) .setZone(zone) .setInstance(instanceName) .build(); Operation operation = instancesClient.startCallable() .futureCall(startInstanceRequest) .get(); // Wait for the operation to complete. Operation response = zoneOperationsClient.wait(project, zone, operation.getName()); if (response.getStatus() == Status.DONE) { System.out.println("Instance started successfully ! "); } } } } // [END compute_start_instance]
compute/cloud-client/src/main/java/compute/StartInstance.java
/* * Copyright 2021 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 * * 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 compute; import com.google.cloud.compute.v1.InstancesClient; import com.google.cloud.compute.v1.Operation; import com.google.cloud.compute.v1.Operation.Status; import com.google.cloud.compute.v1.StartInstanceRequest; import com.google.cloud.compute.v1.ZoneOperationsClient; import java.io.IOException; import java.util.concurrent.ExecutionException; // [START compute_start_instance] public class StartInstance { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { // TODO(developer): Replace these variables before running the sample. /* project: project ID or project number of the Cloud project your instance belongs to. zone: name of the zone your instance belongs to. instanceName: name of the instance your want to start. */ String project = "your-project-id"; String zone = "zone-name"; String instanceName = "instance-name"; startInstance(project, zone, instanceName); } // Starts a stopped Google Compute Engine instance (with unencrypted disks). public static void startInstance(String project, String zone, String instanceName) throws IOException, ExecutionException, InterruptedException { /* Initialize client that will be used to send requests. This client only needs to be created once, and can be reused for multiple requests. After completing all of your requests, call the `instancesClient.close()` method on the client to safely clean up any remaining background resources. */ try (InstancesClient instancesClient = InstancesClient.create(); ZoneOperationsClient zoneOperationsClient = ZoneOperationsClient.create()) { // Create the request. StartInstanceRequest startInstanceRequest = StartInstanceRequest.newBuilder() .setProject(project) .setZone(zone) .setInstance(instanceName) .build(); Operation operation = instancesClient.startCallable() .futureCall(startInstanceRequest) .get(); // Wait for the operation to complete. Operation response = zoneOperationsClient.wait(project, zone, operation.getName()); if (response.getStatus() == Status.DONE) { System.out.println("Instance started successfully ! "); } } } } // [END compute_start_instance]
docs(compute-samples): fixed region tag location (#6302)
compute/cloud-client/src/main/java/compute/StartInstance.java
docs(compute-samples): fixed region tag location (#6302)
Java
apache-2.0
5deb0a0c97e3fc6c3d159dc904485321ee168133
0
kaustavha/sigar,kaustavha/sigar,formicary/sigar,racker/sigar,cit-lab/sigar,boundary/sigar,monicasarbu/sigar,OlegYch/sigar,cit-lab/sigar,cit-lab/sigar,boundary/sigar,lsjeng/sigar,cit-lab/sigar,lsjeng/sigar,OlegYch/sigar,racker/sigar,boundary/sigar,ruleless/sigar,scouter-project/sigar,formicary/sigar,boundary/sigar,ChunPIG/sigar,formicary/sigar,kaustavha/sigar,abhinavmishra14/sigar,kaustavha/sigar,kaustavha/sigar,hyperic/sigar,monicasarbu/sigar,kaustavha/sigar,monicasarbu/sigar,kaustavha/sigar,ChunPIG/sigar,ChunPIG/sigar,OlegYch/sigar,monicasarbu/sigar,scouter-project/sigar,OlegYch/sigar,hyperic/sigar,kaustavha/sigar,kaustavha/sigar,formicary/sigar,ruleless/sigar,scouter-project/sigar,hyperic/sigar,abhinavmishra14/sigar,hyperic/sigar,lsjeng/sigar,monicasarbu/sigar,ChunPIG/sigar,abhinavmishra14/sigar,boundary/sigar,scouter-project/sigar,abhinavmishra14/sigar,cit-lab/sigar,lsjeng/sigar,cit-lab/sigar,cit-lab/sigar,OlegYch/sigar,couchbase/sigar,ruleless/sigar,OlegYch/sigar,ChunPIG/sigar,OlegYch/sigar,racker/sigar,cit-lab/sigar,scouter-project/sigar,lsjeng/sigar,hyperic/sigar,hyperic/sigar,monicasarbu/sigar,formicary/sigar,lsjeng/sigar,hyperic/sigar,lsjeng/sigar,ChunPIG/sigar,cit-lab/sigar,abhinavmishra14/sigar,formicary/sigar,boundary/sigar,racker/sigar,formicary/sigar,OlegYch/sigar,hyperic/sigar,ruleless/sigar,racker/sigar,ruleless/sigar,scouter-project/sigar,monicasarbu/sigar,scouter-project/sigar,kaustavha/sigar,lsjeng/sigar,abhinavmishra14/sigar,ruleless/sigar,scouter-project/sigar,abhinavmishra14/sigar,abhinavmishra14/sigar,OlegYch/sigar,couchbase/sigar,ruleless/sigar,monicasarbu/sigar,ChunPIG/sigar,kaustavha/sigar,hyperic/sigar,cit-lab/sigar,formicary/sigar,boundary/sigar,ruleless/sigar,abhinavmishra14/sigar,monicasarbu/sigar,hyperic/sigar,racker/sigar,formicary/sigar,hyperic/sigar,abhinavmishra14/sigar,monicasarbu/sigar,ChunPIG/sigar,lsjeng/sigar,boundary/sigar,boundary/sigar,cit-lab/sigar,ruleless/sigar,OlegYch/sigar,abhinavmishra14/sigar,racker/sigar,racker/sigar,scouter-project/sigar,ChunPIG/sigar,ChunPIG/sigar,scouter-project/sigar,boundary/sigar,racker/sigar,formicary/sigar,ruleless/sigar,scouter-project/sigar,racker/sigar,lsjeng/sigar,monicasarbu/sigar
/* * Copyright (C) [2004, 2005, 2006, 2007], Hyperic, Inc. * This file is part of SIGAR. * * SIGAR is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. This program is distributed * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.sigar.jmx; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import javax.management.AttributeNotFoundException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanServer; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.hyperic.sigar.FileSystem; import org.hyperic.sigar.NetInterfaceConfig; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarLoader; /** * <p>Registry of all Sigar MBeans. Can be used as a convenient way to invoke * Sigar MBeans at a central point. This brings a bunch of advantages with * it:</p> * * <ul> * <li>This class can be instantiated and registered to the MBean server by * simply calling {@link MBeanServer#createMBean(String, ObjectName)}, * resulting in the automatic creation of all known default Sigar MBeans such * as CPU and memory monitoring beans.</li> * <li>Any Sigar MBean spawned by an instance of this class will use the same * {@link org.hyperic.sigar.Sigar} instance, saving resources in the * process.</li> * <li>When this instance is deregistered from the MBean server, it will * automatically deregister all instances it created, cleaning up behind * itself.</li> * </ul> * * <p>So using this class to manage the Sigar MBeans requires one line of code * for creation, registration and MBean spawning, and one line of code to shut * it all down again.</p> * * @author Bjoern Martin * @since 1.5 */ public class SigarRegistry extends AbstractMBean { private static final String MBEAN_TYPE = "SigarRegistry"; private static final Map VERSION_ATTRS = new LinkedHashMap(); private static final MBeanInfo MBEAN_INFO; private static final MBeanConstructorInfo MBEAN_CONSTR_DEFAULT; // private static final MBeanOperationInfo MBEAN_OPER_LISTPROCESSES; static { MBEAN_CONSTR_DEFAULT = new MBeanConstructorInfo( SigarRegistry.class.getName(), "Creates a new instance of this class. Will create the Sigar " + "instance this class uses when constructing other MBeans", new MBeanParameterInfo[0]); // MBEAN_OPER_LISTPROCESSES = new MBeanOperationInfo("listProcesses", // "Executes a query returning the process IDs of all processes " + // "found on the system.", // null /* new MBeanParameterInfo[0] */, // String.class.getName(), MBeanOperationInfo.INFO); MBEAN_INFO = new MBeanInfo( SigarRegistry.class.getName(), "Sigar MBean registry. Provides a central point for creation " + "and destruction of Sigar MBeans. Any Sigar MBean created via " + "this instance will automatically be cleaned up when this " + "instance is deregistered from the MBean server.", getAttributeInfo(), new MBeanConstructorInfo[] { MBEAN_CONSTR_DEFAULT }, null /*new MBeanOperationInfo[0] */, null /*new MBeanNotificationInfo[0]*/); } private final String objectName; private final ArrayList managedBeans; private static MBeanAttributeInfo[] getAttributeInfo() { VERSION_ATTRS.put("JarVersion", Sigar.VERSION_STRING); VERSION_ATTRS.put("NativeVersion", Sigar.NATIVE_VERSION_STRING); VERSION_ATTRS.put("JarBuildDate", Sigar.BUILD_DATE); VERSION_ATTRS.put("NativeBuildDate", Sigar.NATIVE_BUILD_DATE); VERSION_ATTRS.put("JarSourceRevision", Sigar.SCM_REVISION); VERSION_ATTRS.put("NativeSourceRevision", Sigar.NATIVE_SCM_REVISION); VERSION_ATTRS.put("NativeLibraryName", SigarLoader.getNativeLibraryName()); MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[VERSION_ATTRS.size()]; int i=0; for (Iterator it=VERSION_ATTRS.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry)it.next(); String name = (String)entry.getKey(); attrs[i++] = new MBeanAttributeInfo(name, entry.getValue().getClass().getName(), name, true, // isReadable false, // isWritable false); // isIs } return attrs; } /** * Creates a new instance of this class. Will create the Sigar instance this * class uses when constructing other MBeans. */ public SigarRegistry() { super(new Sigar(), CACHELESS); this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE + "=" + MBEAN_TYPE; this.managedBeans = new ArrayList(); } /* (non-Javadoc) * @see AbstractMBean#getObjectName() */ public String getObjectName() { return this.objectName; } /* public String listProcesses() { try { final long start = System.currentTimeMillis(); long[] ids = sigar.getProcList(); StringBuffer procNames = new StringBuffer(); for (int i = 0; i < ids.length; i++) { try { procNames.append(ids[i] + ":" + sigar.getProcExe(ids[i]).getName()).append('\n'); } catch (SigarException e) { procNames.append(ids[i] + ":" + e.getMessage()).append('\n'); } } final long end = System.currentTimeMillis(); procNames.append("-- Took " + (end-start) + "ms"); return procNames.toString(); } catch (SigarException e) { throw unexpectedError("ProcList", e); } } */ /* (non-Javadoc) * @see javax.management.DynamicMBean#getAttribute(java.lang.String) */ public Object getAttribute(String attr) throws AttributeNotFoundException { Object obj = VERSION_ATTRS.get(attr); if (obj == null) { throw new AttributeNotFoundException(attr); } return obj; } /* (non-Javadoc) * @see javax.management.DynamicMBean#getMBeanInfo() */ public MBeanInfo getMBeanInfo() { return MBEAN_INFO; } private void registerMBean(AbstractMBean mbean) { try { ObjectName name = new ObjectName(mbean.getObjectName()); if (mbeanServer.isRegistered(name)) { return; } ObjectInstance instance = this.mbeanServer.registerMBean(mbean, name); this.managedBeans.add(instance.getObjectName()); } catch (Exception e) { e.printStackTrace(); } } // ------- // Implementation of the MBeanRegistration interface // ------- /** * Registers the default set of Sigar MBeans. Before doing so, a super call * is made to satisfy {@link AbstractMBean}. * * @see AbstractMBean#postRegister(Boolean) */ public void postRegister(Boolean success) { super.postRegister(success); if (!success.booleanValue()) return; //CPU beans try { final int cpuCount = sigar.getCpuInfoList().length; for (int i = 0; i < cpuCount; i++) { registerMBean(new SigarCpu(sigarImpl, i)); registerMBean(new SigarCpuPerc(sigarImpl, i)); registerMBean(new SigarCpuInfo(sigarImpl, i)); } } catch (SigarException e) { throw unexpectedError("CpuInfoList", e); } //FileSystem beans try { FileSystem[] fslist = sigarImpl.getFileSystemList(); for (int i=0; i<fslist.length; i++) { FileSystem fs = fslist[i]; if (fs.getType() != FileSystem.TYPE_LOCAL_DISK) { continue; } String name = fs.getDirName(); ReflectedMBean mbean = new ReflectedMBean(sigarImpl, "FileSystem", name); mbean.setType(mbean.getType() + "Usage"); mbean.putAttributes(fs); registerMBean(mbean); } } catch (SigarException e) { throw unexpectedError("FileSystemList", e); } //NetInterface beans try { String[] ifnames = sigarImpl.getNetInterfaceList(); for (int i=0; i<ifnames.length; i++) { String name = ifnames[i]; NetInterfaceConfig ifconfig = this.sigar.getNetInterfaceConfig(name); try { sigarImpl.getNetInterfaceStat(name); } catch (SigarException e) { continue; } ReflectedMBean mbean = new ReflectedMBean(sigarImpl, "NetInterface", name); mbean.setType(mbean.getType() + "Stat"); mbean.putAttributes(ifconfig); registerMBean(mbean); } } catch (SigarException e) { throw unexpectedError("NetInterfaceList", e); } //network info bean ReflectedMBean mbean = new ReflectedMBean(sigarImpl, "NetInfo"); try { mbean.putAttribute("FQDN", sigarImpl.getFQDN()); } catch (SigarException e) { } registerMBean(mbean); //physical memory bean registerMBean(new ReflectedMBean(sigarImpl, "Mem")); //swap memory bean registerMBean(new ReflectedMBean(sigarImpl, "Swap")); //load average bean registerMBean(new SigarLoadAverage(sigarImpl)); } /** * Deregisters all Sigar MBeans that were created and registered using this * instance. After doing so, a super call is made to satisfy {@link AbstractMBean}. * @throws Exception * * @see AbstractMBean#preDeregister() */ public void preDeregister() throws Exception { // count backwards to remove ONs immediately for (int i = managedBeans.size() - 1; i >= 0; i--) { ObjectName next = (ObjectName) managedBeans.remove(i); if (mbeanServer.isRegistered(next)) { try { mbeanServer.unregisterMBean(next); } catch (Exception e) { // ignore } } } // do the super call super.preDeregister(); } }
bindings/java/src/org/hyperic/sigar/jmx/SigarRegistry.java
/* * Copyright (C) [2004, 2005, 2006, 2007], Hyperic, Inc. * This file is part of SIGAR. * * SIGAR is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. This program is distributed * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.sigar.jmx; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import javax.management.AttributeNotFoundException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanServer; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.hyperic.sigar.FileSystem; import org.hyperic.sigar.NetInterfaceConfig; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarLoader; /** * <p>Registry of all Sigar MBeans. Can be used as a convenient way to invoke * Sigar MBeans at a central point. This brings a bunch of advantages with * it:</p> * * <ul> * <li>This class can be instantiated and registered to the MBean server by * simply calling {@link MBeanServer#createMBean(String, ObjectName)}, * resulting in the automatic creation of all known default Sigar MBeans such * as CPU and memory monitoring beans.</li> * <li>Any Sigar MBean spawned by an instance of this class will use the same * {@link org.hyperic.sigar.Sigar} instance, saving resources in the * process.</li> * <li>When this instance is deregistered from the MBean server, it will * automatically deregister all instances it created, cleaning up behind * itself.</li> * </ul> * * <p>So using this class to manage the Sigar MBeans requires one line of code * for creation, registration and MBean spawning, and one line of code to shut * it all down again.</p> * * @author Bjoern Martin * @since 1.5 */ public class SigarRegistry extends AbstractMBean { private static final String MBEAN_TYPE = "SigarRegistry"; private static final Map VERSION_ATTRS = new LinkedHashMap(); private static final MBeanInfo MBEAN_INFO; private static final MBeanConstructorInfo MBEAN_CONSTR_DEFAULT; // private static final MBeanOperationInfo MBEAN_OPER_LISTPROCESSES; static { MBEAN_CONSTR_DEFAULT = new MBeanConstructorInfo( SigarRegistry.class.getName(), "Creates a new instance of this class. Will create the Sigar " + "instance this class uses when constructing other MBeans", new MBeanParameterInfo[0]); // MBEAN_OPER_LISTPROCESSES = new MBeanOperationInfo("listProcesses", // "Executes a query returning the process IDs of all processes " + // "found on the system.", // null /* new MBeanParameterInfo[0] */, // String.class.getName(), MBeanOperationInfo.INFO); MBEAN_INFO = new MBeanInfo( SigarRegistry.class.getName(), "Sigar MBean registry. Provides a central point for creation " + "and destruction of Sigar MBeans. Any Sigar MBean created via " + "this instance will automatically be cleaned up when this " + "instance is deregistered from the MBean server.", getAttributeInfo(), new MBeanConstructorInfo[] { MBEAN_CONSTR_DEFAULT }, null /*new MBeanOperationInfo[0] */, null /*new MBeanNotificationInfo[0]*/); } private final String objectName; private final ArrayList managedBeans; private static MBeanAttributeInfo[] getAttributeInfo() { VERSION_ATTRS.put("JarVersion", Sigar.VERSION_STRING); VERSION_ATTRS.put("NativeVersion", Sigar.NATIVE_VERSION_STRING); VERSION_ATTRS.put("JarBuildDate", Sigar.BUILD_DATE); VERSION_ATTRS.put("NativeBuildDate", Sigar.NATIVE_BUILD_DATE); VERSION_ATTRS.put("JarSourceRevision", Sigar.SCM_REVISION); VERSION_ATTRS.put("NativeSourceRevision", Sigar.NATIVE_SCM_REVISION); VERSION_ATTRS.put("NativeLibraryName", SigarLoader.getNativeLibraryName()); MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[VERSION_ATTRS.size()]; int i=0; for (Iterator it=VERSION_ATTRS.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry)it.next(); String name = (String)entry.getKey(); attrs[i++] = new MBeanAttributeInfo(name, entry.getValue().getClass().getName(), name, true, // isReadable false, // isWritable false); // isIs } return attrs; } /** * Creates a new instance of this class. Will create the Sigar instance this * class uses when constructing other MBeans. */ public SigarRegistry() { super(new Sigar(), CACHELESS); this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE + "=" + MBEAN_TYPE; this.managedBeans = new ArrayList(); } /* (non-Javadoc) * @see AbstractMBean#getObjectName() */ public String getObjectName() { return this.objectName; } /* public String listProcesses() { try { final long start = System.currentTimeMillis(); long[] ids = sigar.getProcList(); StringBuffer procNames = new StringBuffer(); for (int i = 0; i < ids.length; i++) { try { procNames.append(ids[i] + ":" + sigar.getProcExe(ids[i]).getName()).append('\n'); } catch (SigarException e) { procNames.append(ids[i] + ":" + e.getMessage()).append('\n'); } } final long end = System.currentTimeMillis(); procNames.append("-- Took " + (end-start) + "ms"); return procNames.toString(); } catch (SigarException e) { throw unexpectedError("ProcList", e); } } */ /* (non-Javadoc) * @see javax.management.DynamicMBean#getAttribute(java.lang.String) */ public Object getAttribute(String attr) throws AttributeNotFoundException { Object obj = VERSION_ATTRS.get(attr); if (obj == null) { throw new AttributeNotFoundException(attr); } return obj; } /* (non-Javadoc) * @see javax.management.DynamicMBean#getMBeanInfo() */ public MBeanInfo getMBeanInfo() { return MBEAN_INFO; } private void registerMBean(AbstractMBean mbean) { try { ObjectName name = new ObjectName(mbean.getObjectName()); if (mbeanServer.isRegistered(name)) { return; } ObjectInstance instance = this.mbeanServer.registerMBean(mbean, name); this.managedBeans.add(instance.getObjectName()); } catch (Exception e) { e.printStackTrace(); } } // ------- // Implementation of the MBeanRegistration interface // ------- /** * Registers the default set of Sigar MBeans. Before doing so, a super call * is made to satisfy {@link AbstractMBean}. * * @see AbstractMBean#postRegister(Boolean) */ public void postRegister(Boolean success) { super.postRegister(success); if (!success.booleanValue()) return; //CPU beans try { final int cpuCount = sigar.getCpuInfoList().length; for (int i = 0; i < cpuCount; i++) { registerMBean(new SigarCpu(sigarImpl, i)); registerMBean(new SigarCpuPerc(sigarImpl, i)); registerMBean(new SigarCpuInfo(sigarImpl, i)); } } catch (SigarException e) { throw unexpectedError("CpuInfoList", e); } //FileSystem beans try { FileSystem[] fslist = sigarImpl.getFileSystemList(); for (int i=0; i<fslist.length; i++) { FileSystem fs = fslist[i]; if (fs.getType() != FileSystem.TYPE_LOCAL_DISK) { continue; } String name = fs.getDirName(); ReflectedMBean mbean = new ReflectedMBean(sigarImpl, "FileSystem", name); mbean.setType(mbean.getType() + "Usage"); mbean.putAttributes(fs); registerMBean(mbean); } } catch (SigarException e) { throw unexpectedError("FileSystemList", e); } //NetInterface beans try { String[] ifnames = sigarImpl.getNetInterfaceList(); for (int i=0; i<ifnames.length; i++) { String name = ifnames[i]; NetInterfaceConfig ifconfig = this.sigar.getNetInterfaceConfig(name); try { sigarImpl.getNetInterfaceStat(name); } catch (SigarException e) { continue; } ReflectedMBean mbean = new ReflectedMBean(sigarImpl, "NetInterface", name); mbean.setType(mbean.getType() + "Stat"); mbean.putAttributes(ifconfig); registerMBean(mbean); } } catch (SigarException e) { throw unexpectedError("NetInterfaceList", e); } //physical memory bean registerMBean(new ReflectedMBean(sigarImpl, "Mem")); //swap memory bean registerMBean(new ReflectedMBean(sigarImpl, "Swap")); //load average bean registerMBean(new SigarLoadAverage(sigarImpl)); } /** * Deregisters all Sigar MBeans that were created and registered using this * instance. After doing so, a super call is made to satisfy {@link AbstractMBean}. * @throws Exception * * @see AbstractMBean#preDeregister() */ public void preDeregister() throws Exception { // count backwards to remove ONs immediately for (int i = managedBeans.size() - 1; i >= 0; i--) { ObjectName next = (ObjectName) managedBeans.remove(i); if (mbeanServer.isRegistered(next)) { try { mbeanServer.unregisterMBean(next); } catch (Exception e) { // ignore } } } // do the super call super.preDeregister(); } }
add NetInfo MBean
bindings/java/src/org/hyperic/sigar/jmx/SigarRegistry.java
add NetInfo MBean
Java
bsd-2-clause
c40616048388553d71a435bd5b498c3c2ea8e9d0
0
TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej
// // SaltAndPepper.java // /* ImageJ software for multidimensional image processing and analysis. Copyright (c) 2010, ImageJDev.org. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the ImageJDev.org developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package imagej.core.plugins.imglib; import imagej.data.Dataset; import imagej.data.Extents; import imagej.data.Position; import imagej.ext.plugin.ImageJPlugin; import imagej.ext.plugin.Menu; import imagej.ext.plugin.Parameter; import imagej.ext.plugin.Plugin; import imagej.util.IntRect; import java.util.Random; import net.imglib2.RandomAccess; import net.imglib2.img.Img; import net.imglib2.type.numeric.RealType; /** * Implements the same functionality as IJ1's Salt and Pepper plugin. Assigns * random pixels to 255 or 0. 0 and 255 assignments are each evenly balanced at * 2.5% of the image. Currently only works on 2d images. * * @author Barry DeZonia */ @Plugin(menu = { @Menu(label = "Process", mnemonic = 'p'), @Menu(label = "Noise", mnemonic = 'n'), @Menu(label = "Salt and Pepper", weight = 3) }) public class SaltAndPepper implements ImageJPlugin { // -- instance variables that are Parameters -- @Parameter private Dataset input; // -- other instance variables -- private IntRect selection; private Img<? extends RealType<?>> inputImage; private RandomAccess<? extends RealType<?>> accessor; private long[] position; // -- public interface -- @Override public void run() { checkInput(); setupWorkingData(); assignPixels(); cleanup(); input.update(); } // -- private interface -- private void checkInput() { if (input == null) throw new IllegalArgumentException("input Dataset is null"); if (input.getImgPlus() == null) throw new IllegalArgumentException("input Image is null"); } private void setupWorkingData() { inputImage = input.getImgPlus(); selection = input.getSelection(); position = new long[inputImage.numDimensions()]; accessor = inputImage.randomAccess(); } private void assignPixels() { Random rng = new Random(); rng.setSeed(System.currentTimeMillis()); long[] planeDims = new long[inputImage.numDimensions() - 2]; for (int i = 0; i < planeDims.length; i++) planeDims[i] = inputImage.dimension(i+2); if (planeDims.length == 0) { // 2d only Position planePos = new Extents(new long[]{}).createPosition(); assignPixelsInXYPlane(planePos, rng); } else { // 3 or more dimsensions Extents extents = new Extents(planeDims); Position planePos = extents.createPosition(); long totalPlanes = extents.numElements(); for (long plane = 0; plane < totalPlanes; plane++) { planePos.setIndex(plane); assignPixelsInXYPlane(planePos, rng); } } } private void assignPixelsInXYPlane(Position planePos, Random rng) { for (int i = 2; i < position.length; i++) position[i] = planePos.getLongPosition(i-2); double percentToChange = 0.05; long[] dimensions = new long[inputImage.numDimensions()]; inputImage.dimensions(dimensions); int ox = selection.x; int oy = selection.y; int w = selection.width; int h = selection.height; if (w <= 0) w = (int) dimensions[0]; if (h <= 0) h = (int) dimensions[1]; long numPixels = (long) (percentToChange * w * h); for (long p = 0; p < numPixels / 2; p++) { int randomX, randomY; randomX = ox + rng.nextInt(w); randomY = oy + rng.nextInt(h); setPixel(randomX, randomY, 255); randomX = ox + rng.nextInt(w); randomY = oy + rng.nextInt(h); setPixel(randomX, randomY, 0); } } /** * Sets a value at a specific (x,y) location in the image to a given value */ private void setPixel(int x, int y, double value) { position[0] = x; position[1] = y; accessor.setPosition(position); accessor.get().setReal(value); } private void cleanup() { // nothing to do } }
core/core-plugins/src/main/java/imagej/core/plugins/imglib/SaltAndPepper.java
// // SaltAndPepper.java // /* ImageJ software for multidimensional image processing and analysis. Copyright (c) 2010, ImageJDev.org. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the ImageJDev.org developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package imagej.core.plugins.imglib; import imagej.data.Dataset; import imagej.data.Extents; import imagej.data.Position; import imagej.ext.plugin.ImageJPlugin; import imagej.ext.plugin.Menu; import imagej.ext.plugin.Parameter; import imagej.ext.plugin.Plugin; import imagej.util.IntRect; import java.util.Random; import net.imglib2.RandomAccess; import net.imglib2.img.Img; import net.imglib2.type.numeric.RealType; /** * Implements the same functionality as IJ1's Salt and Pepper plugin. Assigns * random pixels to 255 or 0. 0 and 255 assignments are each evenly balanced at * 2.5% of the image. Currently only works on 2d images. * * @author Barry DeZonia */ @Plugin(menu = { @Menu(label = "Process", mnemonic = 'p'), @Menu(label = "Noise", mnemonic = 'n'), @Menu(label = "Salt and Pepper", weight = 3) }) public class SaltAndPepper implements ImageJPlugin { // -- instance variables that are Parameters -- @Parameter private Dataset input; // -- other instance variables -- private IntRect selection; private Img<? extends RealType<?>> inputImage; private RandomAccess<? extends RealType<?>> accessor; private long[] position; // -- public interface -- @Override public void run() { checkInput(); setupWorkingData(); assignPixels(); cleanup(); input.update(); } // -- private interface -- private void checkInput() { if (input == null) throw new IllegalArgumentException("input Dataset is null"); if (input.getImgPlus() == null) throw new IllegalArgumentException("input Image is null"); } private void setupWorkingData() { inputImage = input.getImgPlus(); selection = input.getSelection(); position = new long[inputImage.numDimensions()]; accessor = inputImage.randomAccess(); } private void assignPixels() { Random rng = new Random(); rng.setSeed(System.currentTimeMillis()); long[] planeDims = new long[inputImage.numDimensions() - 2]; for (int i = 0; i < planeDims.length; i++) planeDims[i] = inputImage.dimension(i+2); if (planeDims.length == 0) { // 2d only assignPixelsInXYPlane(new long[]{}, rng); } else { // 3 or more dimsensions Extents extents = new Extents(planeDims); long[] planeIndex = new long[planeDims.length]; Position pos = extents.createPosition(); long totalPlanes = extents.numElements(); for (long plane = 0; plane < totalPlanes; plane++) { pos.setIndex(plane); pos.localize(planeIndex); assignPixelsInXYPlane(planeIndex, rng); } } } private void assignPixelsInXYPlane(long[] planeIndex, Random rng) { for (int i = 2; i < position.length; i++) position[i] = planeIndex[i-2]; double percentToChange = 0.05; long[] dimensions = new long[inputImage.numDimensions()]; inputImage.dimensions(dimensions); int ox = selection.x; int oy = selection.y; int w = selection.width; int h = selection.height; if (w <= 0) w = (int) dimensions[0]; if (h <= 0) h = (int) dimensions[1]; long numPixels = (long) (percentToChange * w * h); for (long p = 0; p < numPixels / 2; p++) { int randomX, randomY; randomX = ox + rng.nextInt(w); randomY = oy + rng.nextInt(h); setPixel(randomX, randomY, 255); randomX = ox + rng.nextInt(w); randomY = oy + rng.nextInt(h); setPixel(randomX, randomY, 0); } } /** * Sets a value at a specific (x,y) location in the image to a given value */ private void setPixel(int x, int y, double value) { position[0] = x; position[1] = y; accessor.setPosition(position); accessor.get().setReal(value); } private void cleanup() { // nothing to do } }
improve use of Position class This used to be revision r3410.
core/core-plugins/src/main/java/imagej/core/plugins/imglib/SaltAndPepper.java
improve use of Position class
Java
bsd-2-clause
20d2ac8ecf56e4cdeb23819f284d6cbf88f7f87a
0
wono/LoS,wono/LoS
src/objects/Pocketable.java
package objects; /** Objects that can be picked up and "pocketed". */ public abstract class Pocketable extends Interactable { /** Inventory item key this item is assigned to. */ public char shortcutKey; // public ItemType type; public Pocketable(String n, String desc, char shrtct) { super(n, desc); shortcutKey = shrtct; // type = typ; } /** Any special action that happens when an item is picked up. */ public abstract void get(); /** Any special action that happens when item is dropped. */ public abstract void drop(); /** What happens when an item is selected from inventory. */ public abstract void use(); /** When item is used on another object. */ public abstract void use(Interactable useon); }
Delete Pocketable.java
src/objects/Pocketable.java
Delete Pocketable.java
Java
bsd-2-clause
91ecefe1a548e1c1ab40af484ff4de2f0a2360a7
0
saalfeldlab/template-building,saalfeldlab/template-building,saalfeldlab/template-building,saalfeldlab/template-building,saalfeldlab/template-building
package net.imglib2.realtransform; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.janelia.saalfeldlab.transform.io.TransformReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.DfieldIoHelper; import io.IOHelper; import net.imglib2.FinalInterval; import net.imglib2.RandomAccess; import net.imglib2.RandomAccessibleInterval; import net.imglib2.RealPoint; import net.imglib2.img.imageplus.ImagePlusImg; import net.imglib2.img.imageplus.ImagePlusImgFactory; import net.imglib2.iterator.IntervalIterator; import net.imglib2.type.NativeType; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.real.FloatType; import net.imglib2.util.Util; import net.imglib2.util.ValuePair; import net.imglib2.view.Views; import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import process.RenderTransformed; @Command( version = "0.1.1-SNAPSHOT" ) public class TransformToDeformationField implements Callable<Void> { @Option( names = { "-t", "--transform" }, required = false, description = "Transformation file." ) private List< String > transformFiles = new ArrayList<>(); @Option( names = { "-s", "--outputImageSize" }, required = false, description = "Size / field of view of image output in pixels. Comma separated, e.g. \"200,250,300\". " + "Overrides reference image." ) private String outputSize; @Option( names = { "-r", "--output-resolution" }, required = false, split = ",", description = "The resolution at which to write the output. Overrides reference image." ) private double[] outputResolution; @Option( names = { "-f", "--reference" }, required = false, description = "A reference image specifying the output size and resolution." ) private String referenceImagePath; @Option( names = { "-o", "--output" }, required = true, description = "Output file for transformed image" ) private String outputFile; @Option( names = { "-q", "--nThreads" }, required = false, description = "Number of threads." ) private int nThreads = 1; // @Option( names = { "--double" }, required = false, description = "Use double precision for output, otherwise the output is 32 bit floats." ) // private boolean useDouble; private FinalInterval renderInterval; private RealTransformSequence totalTransform; private Scale pixelToPhysical; final Logger logger = LoggerFactory.getLogger( TransformToDeformationField.class ); public static void main( String[] args ) { CommandLine.call( new TransformToDeformationField(), args ); } public void setup() { // use size / resolution if the only input transform is a dfield // ( and size / resolution is not given ) if ( referenceImagePath != null && !referenceImagePath.isEmpty() && new File( referenceImagePath ).exists() ) { IOHelper io = new IOHelper(); ValuePair< long[], double[] > sizeAndRes = io.readSizeAndResolution( new File( referenceImagePath ) ); renderInterval = new FinalInterval( sizeAndRes.getA() ); if ( outputResolution == null ) outputResolution = sizeAndRes.getB(); } else if( transformFiles.size() == 1 ) { String transformFile = transformFiles.get( 0 ); if( transformFile.contains( ".nrrd" ) || transformFile.contains( ".nii" ) || transformFile.contains( ".h5" )) { try { ValuePair< long[], double[] > sizeAndRes = TransformReader.transformSizeAndRes( transformFile ); renderInterval = new FinalInterval( sizeAndRes.a ); pixelToPhysical = new Scale( sizeAndRes.b ); if( outputResolution == null ) { // this can happen if the pixelToPhysical outputResolution = sizeAndRes.b; } } catch ( Exception e ) { e.printStackTrace(); } } } if ( outputSize != null && !outputSize.isEmpty() ) renderInterval = RenderTransformed.parseInterval( outputSize ); // contains the physical transformation RealTransformSequence physicalTransform = TransformReader.readTransforms( transformFiles ); // we need to tack on the conversion from pixel to physical space first pixelToPhysical = null; if ( outputResolution != null ) pixelToPhysical = new Scale( outputResolution ); else { double[] ones = new double[ physicalTransform.numSourceDimensions() ]; Arrays.fill( ones, 1.0 ); pixelToPhysical = new Scale( ones ); } logger.info( "render interval: " + Util.printInterval( renderInterval ) ); logger.info( "pixelToPhysical: " + pixelToPhysical ); totalTransform = physicalTransform; } public Void call() throws Exception { setup(); process( totalTransform, new FloatType() ); return null; } public < T extends RealType< T > & NativeType< T > > void process( RealTransform transform, T t ) throws Exception { assert renderInterval.numDimensions() == transform.numTargetDimensions() || renderInterval.numDimensions() == transform.numTargetDimensions() + 1; // make sure the output interval has an extra dimension // and if its a nrrd, the vector dimension has to be first, // otherwise it goes last if ( renderInterval.numDimensions() == transform.numTargetDimensions() ) { long[] dims = new long[ transform.numTargetDimensions() + 1 ]; if ( outputFile.endsWith( "nrrd" ) ) { dims[ 0 ] = transform.numTargetDimensions(); for ( int d = 0; d < transform.numTargetDimensions(); d++ ) { dims[ d + 1 ] = renderInterval.dimension( d ); } } else { for ( int d = 0; d < transform.numTargetDimensions(); d++ ) { dims[ d ] = renderInterval.dimension( d ); } dims[ transform.numTargetDimensions() ] = transform.numTargetDimensions(); } FinalInterval renderIntervalNew = new FinalInterval( dims ); renderInterval = renderIntervalNew; } logger.info( "allocating" ); ImagePlusImgFactory< T > factory = new ImagePlusImgFactory<>( t ); ImagePlusImg< T, ? > dfieldraw = factory.create( renderInterval ); RandomAccessibleInterval< T > dfield = DfieldIoHelper.vectorAxisPermute( dfieldraw, 3, 3 ); logger.info( "processing with " + nThreads + " threads." ); transformToDeformationField( transform, dfield, pixelToPhysical, nThreads ); logger.info( "writing" ); DfieldIoHelper dfieldIo = new DfieldIoHelper(); dfieldIo.spacing = outputResolution; // naughty try { dfieldIo.write( dfield, outputFile ); } catch ( Exception e ) { e.printStackTrace(); } logger.info( "done" ); } public <T extends RealType<T> & NativeType<T>> void compare( final RealTransform transform, final RandomAccessibleInterval<T> dfield ) { DeformationFieldTransform<T> dfieldTransform = new DeformationFieldTransform<>( dfield ); RealTransformSequence dfieldWithPix2Phys = new RealTransformSequence(); dfieldWithPix2Phys.add( new Scale( outputResolution )); dfieldWithPix2Phys.add( dfieldTransform ); RealPoint p = new RealPoint( transform.numSourceDimensions() ); RealPoint qOrig = new RealPoint( transform.numTargetDimensions() ); RealPoint qNew = new RealPoint( transform.numTargetDimensions() ); final int vecdim = dfield.numDimensions() - 1; IntervalIterator it = new IntervalIterator( Views.hyperSlice( dfield, vecdim, 0 )); while( it.hasNext() ) { p.setPosition( it ); transform.apply( p, qOrig ); dfieldWithPix2Phys.apply( p, qNew ); } } public static <T extends RealType<T> & NativeType<T>> void transformToDeformationField( final RealTransform transform, final RandomAccessibleInterval<T> dfield, AffineGet pixelToPhysical, int nThreads ) { if( nThreads == 1 ) { transformToDeformationField( transform, dfield, pixelToPhysical ); return; } assert ( dfield.numDimensions() == transform.numSourceDimensions() + 1 ); final int vecdim = dfield.numDimensions() - 1; final int step = nThreads; ExecutorService exec = Executors.newFixedThreadPool( nThreads ); ArrayList<Callable<Void>> jobs = new ArrayList<Callable<Void>>(); for( int i = 0; i < nThreads; i++ ) { final int start = i; jobs.add( new Callable<Void>() { @Override public Void call() throws Exception { final RealPoint p = new RealPoint( transform.numSourceDimensions() ); final RealPoint q = new RealPoint( transform.numTargetDimensions() ); final RealTransform transformCopy = transform.copy(); final AffineGet pixelToPhysicalCopy = pixelToPhysical.copy(); final RandomAccess< T > dfieldRa = dfield.randomAccess(); final IntervalIterator it = new IntervalIterator( Views.hyperSlice( dfield, vecdim, 0 )); it.jumpFwd( start ); while( it.hasNext() ) { it.jumpFwd( step ); pixelToPhysicalCopy.apply( it, p ); // set position for( int d = 0; d < it.numDimensions(); d++ ) { dfieldRa.setPosition( it.getIntPosition( d ), d ); } // apply the transform transformCopy.apply( p, q ); // set the result for( int d = 0; d < it.numDimensions(); d++ ) { dfieldRa.setPosition( d, vecdim ); dfieldRa.get().setReal( q.getDoublePosition( d ) - p.getDoublePosition( d ) ); } } return null; } }); } try { List< Future< Void > > futures = exec.invokeAll( jobs ); exec.shutdown(); // wait for jobs to finish } catch ( InterruptedException e ) { e.printStackTrace(); } } public static <T extends RealType<T> & NativeType<T>> void transformToDeformationField( final RealTransform transform, final RandomAccessibleInterval<T> dfield, final AffineGet pixelToPhysical ) { assert ( dfield.numDimensions() == transform.numSourceDimensions() + 1 ); final RealPoint p = new RealPoint( transform.numSourceDimensions() ); final RealPoint q = new RealPoint( transform.numTargetDimensions() ); int vecdim = dfield.numDimensions() - 1; final IntervalIterator it = new IntervalIterator( Views.hyperSlice( dfield, vecdim, 0 )); final RandomAccess< T > dfieldRa = dfield.randomAccess(); while( it.hasNext() ) { it.fwd(); pixelToPhysical.apply( it, p ); // set position for( int d = 0; d < it.numDimensions(); d++ ) { dfieldRa.setPosition( it.getIntPosition( d ), d ); } // apply the transform transform.apply( p, q ); // set the result for( int d = 0; d < it.numDimensions(); d++ ) { dfieldRa.setPosition( d, vecdim ); dfieldRa.get().setReal( q.getDoublePosition( d ) - p.getDoublePosition( d ) ); } } } }
src/main/java/net/imglib2/realtransform/TransformToDeformationField.java
package net.imglib2.realtransform; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.janelia.saalfeldlab.transform.io.TransformReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.DfieldIoHelper; import io.IOHelper; import net.imglib2.FinalInterval; import net.imglib2.RandomAccess; import net.imglib2.RandomAccessibleInterval; import net.imglib2.RealPoint; import net.imglib2.img.imageplus.ImagePlusImg; import net.imglib2.img.imageplus.ImagePlusImgFactory; import net.imglib2.iterator.IntervalIterator; import net.imglib2.type.NativeType; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.real.FloatType; import net.imglib2.util.Util; import net.imglib2.util.ValuePair; import net.imglib2.view.Views; import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import process.RenderTransformed; @Command( version = "0.1.1-SNAPSHOT" ) public class TransformToDeformationField implements Callable<Void> { @Option( names = { "-t", "--transform" }, required = false, description = "Transformation file." ) private List< String > transformFiles = new ArrayList<>(); @Option( names = { "-s", "--outputImageSize" }, required = false, description = "Size / field of view of image output in pixels. Comma separated, e.g. \"200,250,300\". " + "Overrides reference image." ) private String outputSize; @Option( names = { "-r", "--output-resolution" }, required = false, split = ",", description = "The resolution at which to write the output. Overrides reference image." ) private double[] outputResolution; @Option( names = { "-f", "--reference" }, required = false, description = "A reference image specifying the output size and resolution." ) private String referenceImagePath; @Option( names = { "-o", "--output" }, required = true, description = "Output file for transformed image" ) private String outputFile; @Option( names = { "-q", "--nThreads" }, required = false, description = "Number of threads." ) private int nThreads = 1; // @Option( names = { "--double" }, required = false, description = "Use double precision for output, otherwise the output is 32 bit floats." ) // private boolean useDouble; private FinalInterval renderInterval; private RealTransformSequence totalTransform; private Scale pixelToPhysical; final Logger logger = LoggerFactory.getLogger( TransformToDeformationField.class ); public static void main( String[] args ) { CommandLine.call( new TransformToDeformationField(), args ); } public void setup() { // use size / resolution if the only input transform is a dfield // ( and size / resolution is not given ) if ( referenceImagePath != null && !referenceImagePath.isEmpty() && new File( referenceImagePath ).exists() ) { IOHelper io = new IOHelper(); ValuePair< long[], double[] > sizeAndRes = io.readSizeAndResolution( new File( referenceImagePath ) ); renderInterval = new FinalInterval( sizeAndRes.getA() ); if ( outputResolution == null ) outputResolution = sizeAndRes.getB(); } else if( transformFiles.size() == 1 ) { String transformFile = transformFiles.get( 0 ); if( transformFile.contains( ".nrrd" ) || transformFile.contains( ".nii" ) || transformFile.contains( ".h5" )) { try { ValuePair< long[], double[] > sizeAndRes = TransformReader.transformSizeAndRes( transformFile ); renderInterval = new FinalInterval( sizeAndRes.a ); pixelToPhysical = new Scale( sizeAndRes.b ); if( outputResolution == null ) { // this can happen if the pixelToPhysical outputResolution = sizeAndRes.b; } } catch ( Exception e ) { e.printStackTrace(); } } } if ( outputSize != null && !outputSize.isEmpty() ) renderInterval = RenderTransformed.parseInterval( outputSize ); // contains the physical transformation RealTransformSequence physicalTransform = TransformReader.readTransforms( transformFiles ); // we need to tack on the conversion from pixel to physical space first pixelToPhysical = null; if ( outputResolution != null ) pixelToPhysical = new Scale( outputResolution ); else { double[] ones = new double[ physicalTransform.numSourceDimensions() ]; Arrays.fill( ones, 1.0 ); pixelToPhysical = new Scale( ones ); } logger.info( "render interval: " + Util.printInterval( renderInterval ) ); logger.info( "pixelToPhysical: " + pixelToPhysical ); totalTransform = physicalTransform; } public Void call() throws Exception { setup(); process( totalTransform, new FloatType() ); return null; } public < T extends RealType< T > & NativeType< T > > void process( RealTransform transform, T t ) throws Exception { assert renderInterval.numDimensions() == transform.numTargetDimensions() || renderInterval.numDimensions() == transform.numTargetDimensions() + 1; // make sure the output interval has an extra dimension // and if its a nrrd, the vector dimension has to be first, // otherwise it goes last if ( renderInterval.numDimensions() == transform.numTargetDimensions() ) { long[] dims = new long[ transform.numTargetDimensions() + 1 ]; if ( outputFile.endsWith( "nrrd" ) ) { dims[ 0 ] = transform.numTargetDimensions(); for ( int d = 0; d < transform.numTargetDimensions(); d++ ) { dims[ d + 1 ] = renderInterval.dimension( d ); } } else { for ( int d = 0; d < transform.numTargetDimensions(); d++ ) { dims[ d ] = renderInterval.dimension( d ); } dims[ transform.numTargetDimensions() ] = transform.numTargetDimensions(); } FinalInterval renderIntervalNew = new FinalInterval( dims ); renderInterval = renderIntervalNew; } logger.info( "allocating" ); ImagePlusImgFactory< T > factory = new ImagePlusImgFactory<>( t ); ImagePlusImg< T, ? > dfieldraw = factory.create( renderInterval ); RandomAccessibleInterval< T > dfield = DfieldIoHelper.vectorAxisPermute( dfieldraw, 3, 3 ); logger.info( "processing" ); transformToDeformationField( transform, dfield, pixelToPhysical ); logger.info( "writing" ); DfieldIoHelper dfieldIo = new DfieldIoHelper(); dfieldIo.spacing = outputResolution; // naughty try { dfieldIo.write( dfield, outputFile ); } catch ( Exception e ) { e.printStackTrace(); } logger.info( "done" ); } public <T extends RealType<T> & NativeType<T>> void compare( final RealTransform transform, final RandomAccessibleInterval<T> dfield ) { DeformationFieldTransform<T> dfieldTransform = new DeformationFieldTransform<>( dfield ); RealTransformSequence dfieldWithPix2Phys = new RealTransformSequence(); dfieldWithPix2Phys.add( new Scale( outputResolution )); dfieldWithPix2Phys.add( dfieldTransform ); RealPoint p = new RealPoint( transform.numSourceDimensions() ); RealPoint qOrig = new RealPoint( transform.numTargetDimensions() ); RealPoint qNew = new RealPoint( transform.numTargetDimensions() ); final int vecdim = dfield.numDimensions() - 1; IntervalIterator it = new IntervalIterator( Views.hyperSlice( dfield, vecdim, 0 )); while( it.hasNext() ) { p.setPosition( it ); transform.apply( p, qOrig ); dfieldWithPix2Phys.apply( p, qNew ); } } public static <T extends RealType<T> & NativeType<T>> void transformToDeformationField( final RealTransform transform, final RandomAccessibleInterval<T> dfield, AffineGet pixelToPhysical, int nThreads ) { if( nThreads == 1 ) { transformToDeformationField( transform, dfield, pixelToPhysical ); return; } assert ( dfield.numDimensions() == transform.numSourceDimensions() + 1 ); final int vecdim = dfield.numDimensions() - 1; final int step = nThreads; ExecutorService exec = Executors.newFixedThreadPool( nThreads ); ArrayList<Callable<Void>> jobs = new ArrayList<Callable<Void>>(); for( int i = 0; i < nThreads; i++ ) { jobs.add( new Callable<Void>() { @Override public Void call() throws Exception { final RealPoint p = new RealPoint( transform.numSourceDimensions() ); final RealPoint q = new RealPoint( transform.numTargetDimensions() ); final RealTransform transformCopy = transform.copy(); final AffineGet pixelToPhysicalCopy = pixelToPhysical.copy(); final RandomAccess< T > dfieldRa = dfield.randomAccess(); final IntervalIterator it = new IntervalIterator( Views.hyperSlice( dfield, vecdim, 0 )); it.jumpFwd( step ); while( it.hasNext() ) { it.jumpFwd( step ); pixelToPhysicalCopy.apply( it, p ); // set position for( int d = 0; d < it.numDimensions(); d++ ) { dfieldRa.setPosition( it.getIntPosition( d ), d ); } // apply the transform transformCopy.apply( p, q ); // set the result for( int d = 0; d < it.numDimensions(); d++ ) { dfieldRa.setPosition( d, vecdim ); dfieldRa.get().setReal( q.getDoublePosition( d ) - p.getDoublePosition( d ) ); } } return null; } }); } try { List< Future< Void > > futures = exec.invokeAll( jobs ); exec.shutdown(); // wait for jobs to finish } catch ( InterruptedException e ) { e.printStackTrace(); } } public static <T extends RealType<T> & NativeType<T>> void transformToDeformationField( final RealTransform transform, final RandomAccessibleInterval<T> dfield, final AffineGet pixelToPhysical ) { assert ( dfield.numDimensions() == transform.numSourceDimensions() + 1 ); final RealPoint p = new RealPoint( transform.numSourceDimensions() ); final RealPoint q = new RealPoint( transform.numTargetDimensions() ); int vecdim = dfield.numDimensions() - 1; final IntervalIterator it = new IntervalIterator( Views.hyperSlice( dfield, vecdim, 0 )); final RandomAccess< T > dfieldRa = dfield.randomAccess(); while( it.hasNext() ) { it.fwd(); pixelToPhysical.apply( it, p ); // set position for( int d = 0; d < it.numDimensions(); d++ ) { dfieldRa.setPosition( it.getIntPosition( d ), d ); } // apply the transform transform.apply( p, q ); // set the result for( int d = 0; d < it.numDimensions(); d++ ) { dfieldRa.setPosition( d, vecdim ); dfieldRa.get().setReal( q.getDoublePosition( d ) - p.getDoublePosition( d ) ); } } } }
fix parallel transform2dfield computation
src/main/java/net/imglib2/realtransform/TransformToDeformationField.java
fix parallel transform2dfield computation
Java
bsd-3-clause
e83dcdad1ef2d86ed2e0aa399420e582ba1540dc
0
erwin1/MyDevoxxGluon,abhinayagarwal/MyDevoxxGluon,tiainen/MyDevoxxGluon,devoxx/MyDevoxxGluon
/* * Copyright (c) 2016, 2018 Gluon Software * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.devoxx.util; import com.devoxx.DevoxxView; import com.devoxx.model.Session; import com.devoxx.service.Service; import com.devoxx.views.SessionPresenter; import com.gluonhq.charm.down.Services; import com.gluonhq.charm.down.plugins.LocalNotificationsService; import com.gluonhq.charm.down.plugins.Notification; import javafx.collections.ListChangeListener; import javax.inject.Inject; import javax.inject.Singleton; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import static com.devoxx.util.DevoxxLogging.LOGGING_ENABLED; import static java.time.temporal.ChronoUnit.SECONDS; @Singleton public class DevoxxNotifications { private static final Logger LOG = Logger.getLogger(DevoxxNotifications.class.getName()); public static final String GCM_SENDER_ID = "945674729015"; private static final String ID_START = "START_"; private static final String ID_VOTE = "VOTE_"; private final static String TITLE_VOTE_SESSION = DevoxxBundle.getString("OTN.VISUALS.VOTE_NOW"); private final static String TITLE_SESSION_STARTS = DevoxxBundle.getString("OTN.VISUALS.SESSION_STARTING_SOON"); private final static int SHOW_VOTE_NOTIFICATION = -2; // show vote notification two minutes before session ends private final static int SHOW_SESSION_START_NOTIFICATION = -15; // show session start warning 15 minutes before posted start time private final Map<String, Notification> startSessionNotificationMap = new HashMap<>(); private final Map<String, Notification> voteSessionNotificationMap = new HashMap<>(); private final Map<String, Notification> dummyNotificationMap = new HashMap<>(); private ListChangeListener<Session> favoriteSessionsListener; @Inject private Service service; private final Optional<LocalNotificationsService> notificationsService; private boolean startup; public DevoxxNotifications() { notificationsService = Services.get(LocalNotificationsService.class); } /** * For a new Favorite Session, we create two local notifications: * - One notification will be triggered by the device before the session starts * - One notification will be triggered by the device right before the session ends * * We create the notifications and schedule them on the device, but only for future events. * * @param session The new favored session */ public final void addFavoriteSessionNotifications(Session session) { final String sessionId = session.getTalk().getId(); if (!startSessionNotificationMap.containsKey(sessionId)) { createStartNotification(session).ifPresent(notification -> { startSessionNotificationMap.put(sessionId, notification); notificationsService.ifPresent(n -> n.getNotifications().add(notification)); }); } if (!voteSessionNotificationMap.containsKey(sessionId)) { createVoteNotification(session).ifPresent(notification -> { voteSessionNotificationMap.put(sessionId, notification); notificationsService.ifPresent(n -> n.getNotifications().add(notification)); }); } } /** * If a favorite session is removed as favorite, both start and vote notifications * should be cancelled on the device * @param session session removed as favorite */ public final void removeFavoriteSessionNotifications(Session session) { final Notification startNotification = startSessionNotificationMap.remove(session.getTalk().getId()); if (startNotification != null) { notificationsService.ifPresent(n -> n.getNotifications().remove(startNotification)); } final Notification voteNotification = voteSessionNotificationMap.remove(session.getTalk().getId()); if (voteNotification != null) { notificationsService.ifPresent(n -> n.getNotifications().remove(voteNotification)); } } /** * Called when the application starts, allows retrieving the favorite * notifications, and restoring the notifications map */ public void preloadFavoriteSessions() { if (LOGGING_ENABLED) { LOG.log(Level.INFO, "Preload of favored sessions started"); } if (service.isAuthenticated()) { startup = true; favoriteSessionsListener = (ListChangeListener.Change<? extends Session> c) -> { while (c.next()) { if (c.wasAdded()) { for (Session session : c.getAddedSubList()) { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Adding notification #", session.getTalk().getId())); } addAlreadyFavoredSessionNotifications(session); } } } }; service.retrieveFavoredSessions().addListener(favoriteSessionsListener); } } /** * Called after the application has started and pre-loading the favored sessions * ends. At this point, we have all the notifications available, and we can remove * the listener (so new notifications are not treated as already scheduled) and * send them to the Local Notifications service at once */ public void preloadingFavoriteSessionsDone() { if (favoriteSessionsListener != null) { service.retrieveFavoredSessions().removeListener(favoriteSessionsListener); favoriteSessionsListener = null; if (! dummyNotificationMap.isEmpty()) { // 1. Add all dummy notifications to the notification map at once. // These need to be present all the time (as notifications will // be opened always some time after they were delivered). // Adding these dummy notifications doesn't schedule them on the // device and it doesn't cause duplicate exceptions notificationsService.ifPresent(ns -> ns.getNotifications().addAll(dummyNotificationMap.values())); } // process notifications at once List<Notification> notificationList = new ArrayList<>(); notificationList.addAll(startSessionNotificationMap.values()); notificationList.addAll(voteSessionNotificationMap.values()); if (! notificationList.isEmpty()) { // 2. Schedule only real future notifications final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); notificationsService.ifPresent(ns -> { for (Notification n : notificationList) { if (n.getDateTime() != null && n.getDateTime().isAfter(now)) { // Remove notification before scheduling it again, // to avoid duplicate exception final Notification dummyN = dummyNotificationMap.get(n.getId()); if (dummyN != null) { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Removing notification %s", n.getId())); } ns.getNotifications().remove(dummyN); } LOG.log(Level.INFO, String.format("Adding favored notification %s", n.getId())); ns.getNotifications().add(n); } } }); } dummyNotificationMap.clear(); } startup = false; if (LOGGING_ENABLED) { LOG.log(Level.INFO, "Preload of favored sessions ended"); } } /** * Creates a notification that will be triggered by the device before the session starts * @param session the favored session * @return a notification if the event is in the future */ private Optional<Notification> createStartNotification(Session session) { final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); // Add notification 15 min before session starts or during startup ZonedDateTime dateTimeStart = session.getStartDate().plusMinutes(SHOW_SESSION_START_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeStart = dateTimeStart.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Start notification scheduled at: %s", dateTimeStart)); } } // add the notification for new ones if they haven't started yet if (dateTimeStart.isAfter(now) || startup) { return Optional.of(getStartNotification(session, dateTimeStart)); } return Optional.empty(); } /** * Creates a notification that will be triggered by the device right before the session ends * @param session the favored session * @return a notification if the session wasn't added yet and it was already scheduled or * the event is in the future */ private Optional<Notification> createVoteNotification(Session session) { final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); // Add notification 2 min before session ends ZonedDateTime dateTimeVote = session.getEndDate().plusMinutes(SHOW_VOTE_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeVote = dateTimeVote.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Vote notification scheduled at: %s", dateTimeVote)); } } // add the notification if the session hasn't finished yet or during startup if (dateTimeVote.isAfter(now) || startup) { return Optional.of(getVoteNotification(session, dateTimeVote)); } return Optional.empty(); } /** * For an already favored session, we create two local notifications. * * These notifications are not sent to the Local Notification service yet: * this will be done when calling {@link #preloadingFavoriteSessionsDone()}. * * We don't schedule them again on the device, but we add these notifications to the * notifications map, so in case they are delivered, their runnable is available. * * @param session The already favored session */ private void addAlreadyFavoredSessionNotifications(Session session) { final String sessionId = session.getTalk().getId(); final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); // Add notification 15 min before session starts ZonedDateTime dateTimeStart = session.getStartDate().plusMinutes(SHOW_SESSION_START_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeStart = dateTimeStart.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); } if (dateTimeStart.isAfter(now) || startup) { if (!startSessionNotificationMap.containsKey(sessionId)) { dummyNotificationMap.put(ID_START + sessionId, getStartNotification(session, null)); // Add notification createStartNotification(session).ifPresent(n -> { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Adding start notification %s", n.getId())); } startSessionNotificationMap.put(sessionId, n); }); } } // Add notification 2 min before session ends ZonedDateTime dateTimeVote = session.getEndDate().plusMinutes(SHOW_VOTE_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeVote = dateTimeVote.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); } if (dateTimeVote.isAfter(now) || startup) { if (!voteSessionNotificationMap.containsKey(sessionId)) { dummyNotificationMap.put(ID_VOTE + sessionId, getVoteNotification(session, null)); createVoteNotification(session).ifPresent(n -> { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Adding vote notification %s", n.getId())); } voteSessionNotificationMap.put(sessionId, n); }); } } } /** * Creates a notification that will be triggered by the device before the session starts * * @param session the favored session * @param dateTimeStart the session's start zoned date time. If null, this notification won't be * scheduled on the device * @return a local notification */ private Notification getStartNotification(Session session, ZonedDateTime dateTimeStart) { return new Notification( ID_START + session.getTalk().getId(), TITLE_SESSION_STARTS, DevoxxBundle.getString("OTN.VISUALS.IS_ABOUT_TO_START", session.getTitle()), DevoxxNotifications.class.getResourceAsStream("/icon.png"), dateTimeStart, () -> { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Running start notification %s", session.getTalk().getId())); } DevoxxView.SESSION.switchView().ifPresent(presenter -> { SessionPresenter sessionPresenter = (SessionPresenter) presenter; sessionPresenter.showSession(session); }); }); } /** * Creates a notification that will be triggered by the device right before the session ends * @param session the favored session * @param dateTimeVote the session's end zoned date time. If null, this notification won't be * scheduled on the device * @return a local notification */ private Notification getVoteNotification(Session session, ZonedDateTime dateTimeVote) { return new Notification( ID_VOTE + session.getTalk().getId(), TITLE_VOTE_SESSION, DevoxxBundle.getString("OTN.VISUALS.CAST_YOUR_VOTE_ON", session.getTitle()), DevoxxNotifications.class.getResourceAsStream("/icon.png"), dateTimeVote, () -> { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Running vote notification %s", session.getTalk().getId())); } // first go to the session DevoxxView.SESSION.switchView().ifPresent(presenter -> { SessionPresenter sessionPresenter = (SessionPresenter) presenter; sessionPresenter.showSession(session, SessionPresenter.Pane.VOTE); }); }); } }
DevoxxClientMobile/src/main/java/com/devoxx/util/DevoxxNotifications.java
/* * Copyright (c) 2016, 2018 Gluon Software * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.devoxx.util; import com.devoxx.DevoxxView; import com.devoxx.model.Session; import com.devoxx.service.Service; import com.devoxx.views.SessionPresenter; import com.gluonhq.charm.down.Services; import com.gluonhq.charm.down.plugins.LocalNotificationsService; import com.gluonhq.charm.down.plugins.Notification; import javafx.collections.ListChangeListener; import javax.inject.Inject; import javax.inject.Singleton; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import static com.devoxx.util.DevoxxLogging.LOGGING_ENABLED; import static java.time.temporal.ChronoUnit.SECONDS; @Singleton public class DevoxxNotifications { private static final Logger LOG = Logger.getLogger(DevoxxNotifications.class.getName()); public static final String GCM_SENDER_ID = "945674729015"; private static final String ID_START = "START_"; private static final String ID_VOTE = "VOTE_"; private final static String TITLE_VOTE_SESSION = DevoxxBundle.getString("OTN.VISUALS.VOTE_NOW"); private final static String TITLE_SESSION_STARTS = DevoxxBundle.getString("OTN.VISUALS.SESSION_STARTING_SOON"); private final static int SHOW_VOTE_NOTIFICATION = -2; // show vote notification two minutes before session ends private final static int SHOW_SESSION_START_NOTIFICATION = -15; // show session start warning 15 minutes before posted start time private final Map<String, Notification> startSessionNotificationMap = new HashMap<>(); private final Map<String, Notification> voteSessionNotificationMap = new HashMap<>(); private ListChangeListener<Session> favoriteSessionsListener; @Inject private Service service; private final Optional<LocalNotificationsService> notificationsService; public DevoxxNotifications() { notificationsService = Services.get(LocalNotificationsService.class); } /** * For a new Favorite Session, we create two local notifications: * - One notification will be triggered by the device before the session starts * - One notification will be triggered by the device right before the session ends * * We create the notifications and schedule them on the device, but only for future events. * * @param session The new favored session */ public final void addFavoriteSessionNotifications(Session session) { final String sessionId = session.getTalk().getId(); if (!startSessionNotificationMap.containsKey(sessionId)) { createStartNotification(session).ifPresent(notification -> { startSessionNotificationMap.put(sessionId, notification); notificationsService.ifPresent(n -> n.getNotifications().add(notification)); }); } if (!voteSessionNotificationMap.containsKey(sessionId)) { createVoteNotification(session).ifPresent(notification -> { voteSessionNotificationMap.put(sessionId, notification); notificationsService.ifPresent(n -> n.getNotifications().add(notification)); }); } } /** * If a favorite session is removed as favorite, both start and vote notifications * should be cancelled on the device * @param session session removed as favorite */ public final void removeFavoriteSessionNotifications(Session session) { final Notification startNotification = startSessionNotificationMap.remove(session.getTalk().getId()); if (startNotification != null) { notificationsService.ifPresent(n -> n.getNotifications().remove(startNotification)); } final Notification voteNotification = voteSessionNotificationMap.remove(session.getTalk().getId()); if (voteNotification != null) { notificationsService.ifPresent(n -> n.getNotifications().remove(voteNotification)); } } /** * Called when the application starts, allows retrieving the favorite * notifications, and restoring the notifications map */ public void preloadFavoriteSessions() { if (service.isAuthenticated()) { favoriteSessionsListener = (ListChangeListener.Change<? extends Session> c) -> { while (c.next()) { if (c.wasAdded()) { for (Session session : c.getAddedSubList()) { if (LOGGING_ENABLED) { LOG.log(Level.INFO, "Adding notification #" + session.getTalk().getId()); } addAlreadyFavoredSessionNotifications(session); } } } }; service.retrieveFavoredSessions().addListener(favoriteSessionsListener); } } /** * Called after the application has started and pre-loading the favored sessions * ends. At this point, we have all the notifications available, and we can remove * the listener (so new notifications are not treated as already scheduled) and * send them to the Local Notifications service at once */ public void preloadingFavoriteSessionsDone() { if (favoriteSessionsListener != null) { service.retrieveFavoredSessions().removeListener(favoriteSessionsListener); favoriteSessionsListener = null; // process notifications at once List<Notification> notificationList = new ArrayList<>(); notificationList.addAll(startSessionNotificationMap.values()); notificationList.addAll(voteSessionNotificationMap.values()); if (notificationList.size() > 0) { LOG.log(Level.INFO, String.format("Adding %d notifications already favored", notificationList.size())); notificationsService.ifPresent(n -> n.getNotifications().addAll(notificationList)); } } } /** * Creates a notification that will be triggered by the device before the session starts * @param session the favored session * @return a notification if the event is in the future */ private Optional<Notification> createStartNotification(Session session) { final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); // Add notification 15 min before session starts ZonedDateTime dateTimeStart = session.getStartDate().plusMinutes(SHOW_SESSION_START_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeStart = dateTimeStart.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); } // add the notification for new ones if they haven't started yet if (dateTimeStart.isAfter(now)) { return Optional.of(getStartNotification(session, dateTimeStart)); } return Optional.empty(); } /** * Creates a notification that will be triggered by the device right before the session ends * @param session the favored session * @return a notification if the session wasn't added yet and it was already scheduled or * the event is in the future */ private Optional<Notification> createVoteNotification(Session session) { final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); // Add notification 2 min before session ends ZonedDateTime dateTimeVote = session.getEndDate().plusMinutes(SHOW_VOTE_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeVote = dateTimeVote.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); } // add the notification if the session hasn't finished yet if (dateTimeVote.isAfter(now)) { return Optional.of(getVoteNotification(session, dateTimeVote)); } return Optional.empty(); } /** * For an already favored session, we create two local notifications. * * These notifications are not sent to the Local Notification service yet: * this will be done when calling {@link #preloadingFavoriteSessionsDone()}. * * We don't schedule them again on the device, but we add these notifications to the * notifications map, so in case they are delivered, their runnable is available. * * @param session The already favored session */ private void addAlreadyFavoredSessionNotifications(Session session) { final String sessionId = session.getTalk().getId(); final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); // Add notification 15 min before session starts ZonedDateTime dateTimeStart = session.getStartDate().plusMinutes(SHOW_SESSION_START_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeStart = dateTimeStart.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); } if (dateTimeStart.isAfter(now)) { if (!startSessionNotificationMap.containsKey(sessionId)) { final Notification dummyStartNotification = getStartNotification(session, null); // Remove notification to avoid duplicate notification notificationsService.ifPresent(ns -> { // we need to add the notification first so because no direct method // exists on LocalNotificationsService to un-schedule a notification. // and un-scheduling is done via the listener attached to notifications observable list ns.getNotifications().add(dummyStartNotification); ns.getNotifications().remove(dummyStartNotification); }); // Add notification createStartNotification(session).ifPresent(n -> { LOG.log(Level.INFO, "Adding final start notification"); startSessionNotificationMap.put(sessionId, n); }); } } // Add notification 2 min before session ends ZonedDateTime dateTimeVote = session.getEndDate().plusMinutes(SHOW_VOTE_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeVote = dateTimeVote.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); } if (dateTimeVote.isAfter(now)) { if (!voteSessionNotificationMap.containsKey(sessionId)) { final Notification dummyVoteNotification = getVoteNotification(session, null); notificationsService.ifPresent(ns -> { ns.getNotifications().add(dummyVoteNotification); ns.getNotifications().remove(dummyVoteNotification); }); createVoteNotification(session).ifPresent(n -> { LOG.log(Level.INFO, "Adding final vote notification"); voteSessionNotificationMap.put(sessionId, n); }); } } } /** * Creates a notification that will be triggered by the device before the session starts * * @param session the favored session * @param dateTimeStart the session's start zoned date time. If null, this notification won't be * scheduled on the device * @return a local notification */ private Notification getStartNotification(Session session, ZonedDateTime dateTimeStart) { return new Notification( ID_START + session.getTalk().getId(), TITLE_SESSION_STARTS, DevoxxBundle.getString("OTN.VISUALS.IS_ABOUT_TO_START", session.getTitle()), DevoxxNotifications.class.getResourceAsStream("/icon.png"), dateTimeStart, () -> DevoxxView.SESSION.switchView().ifPresent(presenter -> { SessionPresenter sessionPresenter = (SessionPresenter) presenter; sessionPresenter.showSession(session); }) ); } /** * Creates a notification that will be triggered by the device right before the session ends * @param session the favored session * @param dateTimeVote the session's end zoned date time. If null, this notification won't be * scheduled on the device * @return a local notification */ private Notification getVoteNotification(Session session, ZonedDateTime dateTimeVote) { return new Notification( ID_VOTE + session.getTalk().getId(), TITLE_VOTE_SESSION, DevoxxBundle.getString("OTN.VISUALS.CAST_YOUR_VOTE_ON", session.getTitle()), DevoxxNotifications.class.getResourceAsStream("/icon.png"), dateTimeVote, () -> { // first go to the session DevoxxView.SESSION.switchView().ifPresent(presenter -> { SessionPresenter sessionPresenter = (SessionPresenter) presenter; sessionPresenter.showSession(session, SessionPresenter.Pane.VOTE); }); }); } }
#96 Fix to perform notification actions
DevoxxClientMobile/src/main/java/com/devoxx/util/DevoxxNotifications.java
#96 Fix to perform notification actions
Java
mit
dd21f85304adca0bf157e00d5e1304fa32cbe220
0
fclairamb/tc65lib,fclairamb/tc65lib
package org.javacint.settings; import com.siemens.icm.io.file.FileConnection; import java.io.*; import java.util.*; import javax.microedition.io.Connector; import org.javacint.common.Strings; import org.javacint.logging.Logger; /** * Settings management class * * @author Florent Clairambault / www.webingenia.com */ public class Settings { private static Hashtable settings; private static String fileName = "settings.txt"; private static final Vector consumers = new Vector(); /** * APN setting */ public static final String SETTING_APN = "apn"; public static final String SETTING_CODE = "code"; public static final String SETTING_MANAGERSPHONE = "phoneManager"; public static final String SETTING_IMSI = "imsi"; public static final String SETTING_PINCODE = "pincode"; /** * JADUrl setting */ public static final String SETTING_JADURL = "jadurl"; private static boolean madeSomeChanges = false; private static boolean loading; public static synchronized void setFilename(String filename) { fileName = filename; settings = null; } public static void loading(boolean l) { loading = l; } public static String getFilename() { return fileName; } /** * Load settings */ public static synchronized void load() { if (Logger.BUILD_DEBUG) { Logger.log("Settings.load();"); } StringBuffer buffer = new StringBuffer(); Hashtable settings = getDefaultSettings(); try { FileConnection fc = (FileConnection) Connector.open("file:///a:/" + fileName, Connector.READ); if (!fc.exists()) { if (Logger.BUILD_WARNING) { Logger.log("Settings.load: File \"" + fileName + "\" doesn\'t exist!"); } fc = (FileConnection) Connector.open("file:///a:/" + fileName + ".old", Connector.READ); if (fc.exists()) { if (Logger.BUILD_WARNING) { Logger.log("Settings.load: But \"" + fileName + ".old\" exists ! "); } } else { return; } } InputStream is = fc.openInputStream(); while (is.available() > 0) { int c = is.read(); if (c == '\n') { loadLine(settings, buffer.toString()); buffer.setLength(0); } else { buffer.append((char) c); } } is.close(); fc.close(); } catch (IOException ex) { // The exception we shoud have is at first launch : // There shouldn't be any file to read from if (Logger.BUILD_CRITICAL) { Logger.log("Settings.Load", ex); } } finally { settings = settings; } } /** * Treat each line of the file * * @param def Default settings * @param line Line to parse */ private static void loadLine(Hashtable settings, String line) { // if (Logger.BUILD_VERBOSE) { // Logger.log("loadTreatLine( [...], \"" + line + "\" );"); // } String[] spl = Strings.split('=', line); String key = spl[0]; String value = spl[1]; // If default settings hashTable contains this key // we can use this value if (settings.containsKey(key)) { settings.remove(key); settings.put(key, value); // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.loadLine: " + key + "=" + value); // } } } public void onSettingsChanged(String[] names) { onSettingsChanged(names, null); } /** * Launch an event when some settings * * @param names Names of the settings */ public void onSettingsChanged(String[] names, SettingsConsumer caller) { // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.onSettingsChanged( String[" + names.length + "] names );"); // } try { synchronized (consumers) { for (Enumeration en = consumers.elements(); en.hasMoreElements();) { SettingsConsumer cons = (SettingsConsumer) en.nextElement(); if (cons == caller) { continue; } cons.settingsChanged(names); } } } catch (Exception ex) { if (Logger.BUILD_CRITICAL) { Logger.log("Settings.OnSeettingChanged", ex); } } } /** * Get default settings * * @return Default settings Hashtable */ public static Hashtable getDefaultSettings() { // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.getDefaultSettings();"); // } Hashtable defaultSettings = new Hashtable(); // Code is mandatory defaultSettings.put(SETTING_CODE, "1234"); // APN is mandatory defaultSettings.put(SETTING_APN, "0"); // IMSI is mandatory defaultSettings.put(SETTING_IMSI, "0"); synchronized (consumers) { for (Enumeration en = consumers.elements(); en.hasMoreElements();) { SettingsConsumer cons = (SettingsConsumer) en.nextElement(); cons.getDefaultSettings(defaultSettings); } } return defaultSettings; } /** * Add a settings consumer class * * @param consumer Consumer of settings */ public synchronized void addSettingsConsumer(SettingsConsumer consumer) { // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.addSettingsConsumer( " + consumer + " );"); // } if (!loading) { throw new RuntimeException("Settings.addSettingsConsumer: We're not loading anymore !"); } synchronized (consumers) { consumers.addElement(consumer); settings = null; } } /** * Remove a settings consumer class * * @param consumer Consumer of settings */ public synchronized void removeSettingsConsumer(SettingsConsumer consumer) { synchronized (consumers) { if (consumers.contains(consumer)) { consumers.removeElement(consumer); } settings = null; } } /** * Reset all settings */ public synchronized void resetErything() { try { FileConnection fc = (FileConnection) Connector.open("file:///a:/" + fileName, Connector.READ_WRITE); if (fc.exists()) { fc.delete(); } load(); settings = null; } catch (Exception ex) { if (Logger.BUILD_CRITICAL) { Logger.log("Settings.resetErything", ex); } } } /** * Save setttings */ public synchronized void save() { // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.save();", true); // } // If there's no settings, we shouldn't have to save anything if (settings == null) { return; } // If no changes were made, we shouldn't have to save anything if (!madeSomeChanges) { return; } try { Hashtable defSettings = getDefaultSettings(); String fileNameTmp = fileName + ".tmp"; String fileNameOld = fileName + ".old"; String settingFileUrl = "file:///a:/" + fileName; String settingFileUrlTmp = "file:///a:/" + fileNameTmp; String settingFileUrlOld = "file:///a:/" + fileNameOld; // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save: Opening \"" + settingFileUrlTmp + "\"..."); // } FileConnection fc = (FileConnection) Connector.open(settingFileUrlTmp, Connector.READ_WRITE); //fc = (FileConnection) Connector.open("file:///" + _fileName, Connector.READ_WRITE); if (fc.exists()) { fc.delete(); } fc.create(); OutputStream os = fc.openOutputStream(); Enumeration e = defSettings.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); String value = (String) settings.get(key); String defValue = (String) defSettings.get(key); if ( // if there is a default value defValue != null && // and // the value isn't the same as the default value defValue.compareTo(value) != 0) { String line = key + "=" + value + '\n'; // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save.line: " + line); // } os.write(line.getBytes()); } } os.flush(); os.close(); { // We move the current setting file to the old one FileConnection currentFile = (FileConnection) Connector.open(settingFileUrl, Connector.READ_WRITE); // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save: Renaming \"" + settingFileUrl + "\" to \"" + fileNameOld + "\""); // } if (currentFile.exists()) { { // We delete the old setting file // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save: Deleting \"" + settingFileUrlOld + "\""); // } FileConnection oldFile = (FileConnection) Connector.open(settingFileUrlOld, Connector.READ_WRITE); if (oldFile.exists()) { oldFile.delete(); } } currentFile.rename(fileNameOld); } } { // We move the tmp file to the current setting file // if ( Logger.BUILD_DEBUG ) { // Logger.log("Setting.save: Renaming \"" + settingFileUrlTmp + "\" to \"" + _fileName + "\""); // } fc.rename(fileName); fc.close(); } // If we savec the file, we can reset the madeSomeChanges information madeSomeChanges = false; } catch (Exception ex) { if (Logger.BUILD_CRITICAL) { Logger.log("Settings.Save", ex, true); } } } /** * Init (and ReInit) method */ private static void checkLoad() { if (settings == null) { load(); } } /** * Get a setting's value as a String * * @param key Key Name of the setting * @return String value of the setting */ public static synchronized String get(String key) { return (String) getSettings().get(key); } /** * Get all the settings * * @return All the settings */ public static synchronized Hashtable getSettings() { checkLoad(); return settings; } /** * Set a setting * * @param key Setting to set * @param value Value of the setting */ public synchronized void set(String key, String value) { if (Logger.BUILD_DEBUG) { Logger.log("Settings.setSetting( \"" + key + "\", \"" + value + "\" );"); } if (setWithoutEvent(key, value)) { onSettingsChanged(new String[]{key}); } } public void set(String key, int value) { set(key, "" + value); } /** * Set a setting without launching the onSettingsChange method * * @param key Setting to set * @param value Value of the setting * @return If setting was actually changed */ public synchronized boolean setWithoutEvent(String key, String value) { Hashtable settings = getSettings(); if (settings.containsKey(key)) { String previousValue = (String) settings.get(key); if (previousValue.compareTo(value) == 0) { return false; } } else { return false; } if (loading) { throw new RuntimeException("Settings.setSettingWithoutChangeEvent: You can't change a setting while loading !"); } settings.put(key, value); madeSomeChanges = true; return true; } /** * Get a setting's value as an int * * @param key Key Name of the setting * @return Integer value of the setting * @throws java.lang.NumberFormatException When the int cannot be parsed */ public static int getInt(String key) throws NumberFormatException { String value = get(key); if (value == null) { return -1; } return Integer.parseInt(value); } /** * Get a setting's value as a boolean * * @param key Key name of the setting * @return The value of the setting (any value not understood will be * treated as false) */ public static boolean getBool(String key) { String value = get(key); if (value == null) { return false; } if (value.compareTo("1") == 0 || value.compareTo("true") == 0 || value.compareTo("on") == 0 || value.compareTo("yes") == 0) { return true; } return false; } }
tc65lib/src/org/javacint/settings/Settings.java
package org.javacint.settings; import com.siemens.icm.io.file.FileConnection; import java.io.*; import java.util.*; import javax.microedition.io.Connector; import org.javacint.common.Strings; import org.javacint.logging.Logger; /** * Settings management class * * @author Florent Clairambault / www.webingenia.com */ public class Settings { private static Hashtable settings; private static String fileName = "settings.txt"; private static final Vector consumers = new Vector(); /** * APN setting */ public static final String SETTING_APN = "apn"; public static final String SETTING_CODE = "code"; public static final String SETTING_MANAGERSPHONE = "phoneManager"; public static final String SETTING_IMSI = "imsi"; public static final String SETTING_PINCODE = "pincode"; /** * JADUrl setting */ public static final String SETTING_JADURL = "jadurl"; private boolean madeSomeChanges = false; private boolean loading; public static synchronized void setFilename(String filename) { fileName = filename; settings = null; } public void setLoading(boolean loading) { this.loading = loading; } public static String getFilename() { return fileName; } /** * Load settings */ public static synchronized void load() { if (Logger.BUILD_DEBUG) { Logger.log("Settings.load();"); } StringBuffer buffer = new StringBuffer(); Hashtable settings = getDefaultSettings(); try { FileConnection fc = (FileConnection) Connector.open("file:///a:/" + fileName, Connector.READ); if (!fc.exists()) { if (Logger.BUILD_WARNING) { Logger.log("Settings.load: File \"" + fileName + "\" doesn\'t exist!"); } fc = (FileConnection) Connector.open("file:///a:/" + fileName + ".old", Connector.READ); if (fc.exists()) { if (Logger.BUILD_WARNING) { Logger.log("Settings.load: But \"" + fileName + ".old\" exists ! "); } } else { return; } } InputStream is = fc.openInputStream(); while (is.available() > 0) { int c = is.read(); if (c == '\n') { loadLine(settings, buffer.toString()); buffer.setLength(0); } else { buffer.append((char) c); } } is.close(); fc.close(); } catch (IOException ex) { // The exception we shoud have is at first launch : // There shouldn't be any file to read from if (Logger.BUILD_CRITICAL) { Logger.log("Settings.Load", ex); } } finally { settings = settings; } } /** * Treat each line of the file * * @param def Default settings * @param line Line to parse */ private static void loadLine(Hashtable settings, String line) { // if (Logger.BUILD_VERBOSE) { // Logger.log("loadTreatLine( [...], \"" + line + "\" );"); // } String[] spl = Strings.split('=', line); String key = spl[0]; String value = spl[1]; // If default settings hashTable contains this key // we can use this value if (settings.containsKey(key)) { settings.remove(key); settings.put(key, value); // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.loadLine: " + key + "=" + value); // } } } public void onSettingsChanged(String[] names) { onSettingsChanged(names, null); } /** * Launch an event when some settings * * @param names Names of the settings */ public void onSettingsChanged(String[] names, SettingsConsumer caller) { // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.onSettingsChanged( String[" + names.length + "] names );"); // } try { synchronized (consumers) { for (Enumeration en = consumers.elements(); en.hasMoreElements();) { SettingsConsumer cons = (SettingsConsumer) en.nextElement(); if (cons == caller) { continue; } cons.settingsChanged(names); } } } catch (Exception ex) { if (Logger.BUILD_CRITICAL) { Logger.log("Settings.OnSeettingChanged", ex); } } } /** * Get default settings * * @return Default settings Hashtable */ public static Hashtable getDefaultSettings() { // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.getDefaultSettings();"); // } Hashtable defaultSettings = new Hashtable(); // Code is mandatory defaultSettings.put(SETTING_CODE, "1234"); // APN is mandatory defaultSettings.put(SETTING_APN, "0"); // IMSI is mandatory defaultSettings.put(SETTING_IMSI, "0"); synchronized (consumers) { for (Enumeration en = consumers.elements(); en.hasMoreElements();) { SettingsConsumer cons = (SettingsConsumer) en.nextElement(); cons.getDefaultSettings(defaultSettings); } } return defaultSettings; } /** * Add a settings consumer class * * @param consumer Consumer of settings */ public synchronized void addSettingsConsumer(SettingsConsumer consumer) { // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.addSettingsConsumer( " + consumer + " );"); // } if (!loading) { throw new RuntimeException("Settings.addSettingsConsumer: We're not loading anymore !"); } synchronized (consumers) { consumers.addElement(consumer); settings = null; } } /** * Remove a settings consumer class * * @param consumer Consumer of settings */ public synchronized void removeSettingsConsumer(SettingsConsumer consumer) { synchronized (consumers) { if (consumers.contains(consumer)) { consumers.removeElement(consumer); } settings = null; } } /** * Reset all settings */ public synchronized void resetErything() { try { FileConnection fc = (FileConnection) Connector.open("file:///a:/" + fileName, Connector.READ_WRITE); if (fc.exists()) { fc.delete(); } load(); settings = null; } catch (Exception ex) { if (Logger.BUILD_CRITICAL) { Logger.log("Settings.resetErything", ex); } } } /** * Save setttings */ public synchronized void save() { // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.save();", true); // } // If there's no settings, we shouldn't have to save anything if (settings == null) { return; } // If no changes were made, we shouldn't have to save anything if (!madeSomeChanges) { return; } try { Hashtable defSettings = getDefaultSettings(); String fileNameTmp = fileName + ".tmp"; String fileNameOld = fileName + ".old"; String settingFileUrl = "file:///a:/" + fileName; String settingFileUrlTmp = "file:///a:/" + fileNameTmp; String settingFileUrlOld = "file:///a:/" + fileNameOld; // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save: Opening \"" + settingFileUrlTmp + "\"..."); // } FileConnection fc = (FileConnection) Connector.open(settingFileUrlTmp, Connector.READ_WRITE); //fc = (FileConnection) Connector.open("file:///" + _fileName, Connector.READ_WRITE); if (fc.exists()) { fc.delete(); } fc.create(); OutputStream os = fc.openOutputStream(); Enumeration e = defSettings.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); String value = (String) settings.get(key); String defValue = (String) defSettings.get(key); if ( // if there is a default value defValue != null && // and // the value isn't the same as the default value defValue.compareTo(value) != 0) { String line = key + "=" + value + '\n'; // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save.line: " + line); // } os.write(line.getBytes()); } } os.flush(); os.close(); { // We move the current setting file to the old one FileConnection currentFile = (FileConnection) Connector.open(settingFileUrl, Connector.READ_WRITE); // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save: Renaming \"" + settingFileUrl + "\" to \"" + fileNameOld + "\""); // } if (currentFile.exists()) { { // We delete the old setting file // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save: Deleting \"" + settingFileUrlOld + "\""); // } FileConnection oldFile = (FileConnection) Connector.open(settingFileUrlOld, Connector.READ_WRITE); if (oldFile.exists()) { oldFile.delete(); } } currentFile.rename(fileNameOld); } } { // We move the tmp file to the current setting file // if ( Logger.BUILD_DEBUG ) { // Logger.log("Setting.save: Renaming \"" + settingFileUrlTmp + "\" to \"" + _fileName + "\""); // } fc.rename(fileName); fc.close(); } // If we savec the file, we can reset the madeSomeChanges information madeSomeChanges = false; } catch (Exception ex) { if (Logger.BUILD_CRITICAL) { Logger.log("Settings.Save", ex, true); } } } /** * Init (and ReInit) method */ private static void checkLoad() { if (settings == null) { load(); } } /** * Get a setting's value as a String * * @param key Key Name of the setting * @return String value of the setting */ public static synchronized String get(String key) { return (String) getSettings().get(key); } /** * Get all the settings * * @return All the settings */ public static synchronized Hashtable getSettings() { checkLoad(); return settings; } /** * Set a setting * * @param key Setting to set * @param value Value of the setting */ public synchronized void set(String key, String value) { if (Logger.BUILD_DEBUG) { Logger.log("Settings.setSetting( \"" + key + "\", \"" + value + "\" );"); } if (setWithoutEvent(key, value)) { onSettingsChanged(new String[]{key}); } } public void set(String key, int value) { set(key, "" + value); } /** * Set a setting without launching the onSettingsChange method * * @param key Setting to set * @param value Value of the setting * @return If setting was actually changed */ public synchronized boolean setWithoutEvent(String key, String value) { Hashtable settings = getSettings(); if (settings.containsKey(key)) { String previousValue = (String) settings.get(key); if (previousValue.compareTo(value) == 0) { return false; } } else { return false; } if (loading) { throw new RuntimeException("Settings.setSettingWithoutChangeEvent: You can't change a setting while loading !"); } settings.put(key, value); madeSomeChanges = true; return true; } /** * Get a setting's value as an int * * @param key Key Name of the setting * @return Integer value of the setting * @throws java.lang.NumberFormatException When the int cannot be parsed */ public static int getInt(String key) throws NumberFormatException { String value = get(key); if (value == null) { return -1; } return Integer.parseInt(value); } /** * Get a setting's value as a boolean * * @param key Key name of the setting * @return The value of the setting (any value not understood will be * treated as false) */ public static boolean getBool(String key) { String value = get(key); if (value == null) { return false; } if (value.compareTo("1") == 0 || value.compareTo("true") == 0 || value.compareTo("on") == 0 || value.compareTo("yes") == 0) { return true; } return false; } }
Fixing settings management.
tc65lib/src/org/javacint/settings/Settings.java
Fixing settings management.
Java
mit
34011cabb15456afde5d39329a031f1b51c1de94
0
CS2103JAN2017-T11-B2/main,CS2103JAN2017-T11-B2/main
package seedu.todolist.testutil; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Objects; import seedu.todolist.logic.commands.AddCommand; import seedu.todolist.model.tag.UniqueTagList; import seedu.todolist.model.todo.Name; import seedu.todolist.model.todo.ReadOnlyTodo; /** * A mutable todo object. For testing only. */ public class TestTodo implements ReadOnlyTodo { private Name name; private Date starttime; private Date endtime; private Date completeTime; private UniqueTagList tags; //@@author A0163720M /** * Constructor for a empty floating task */ public TestTodo() { this(null, null, null, null, new UniqueTagList()); } //@@author //@@author A0163720M /** * Constructor for a floating task */ public TestTodo(Name name, UniqueTagList tags) { this(name, null, null, null, tags); } //@@author //@@author A0163786N, A0163720M /** * Constructor for a deadline */ public TestTodo(Name name, Date endtime, UniqueTagList tags) { this(name, null, endtime, null, tags); } //@@author /** * Constructor for an event */ public TestTodo(Name name, Date starttime, Date endtime, UniqueTagList tags) { this(name, starttime, endtime, null, tags); } //@@author A0163786N, A0163720M /** * General todo constructor */ public TestTodo(Name name, Date starttime, Date endtime, Date completeTime, UniqueTagList tags) { this.name = name; this.starttime = starttime; this.endtime = endtime; this.completeTime = completeTime; this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list } //@@author /** * Creates a copy of the given ReadOnlyTodo. */ public TestTodo(ReadOnlyTodo source) { this(source.getName(), source.getStartTime(), source.getEndTime(), source.getCompleteTime(), source.getTags()); } public void setName(Name name) { assert name != null; this.name = name; } @Override public Name getName() { return name; } public void setStartTime(Date starttime) { assert starttime != null; this.starttime = starttime; } @Override public Date getStartTime() { return starttime; } public void setEndTime(Date endtime) { assert endtime != null; this.endtime = endtime; } @Override public Date getEndTime() { return endtime; } //@@author A0163786N public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } //@@author //@@author A0163786N @Override public Date getCompleteTime() { return completeTime; } //@@author @Override public UniqueTagList getTags() { return new UniqueTagList(tags); } /** * Replaces this todo's tags with the tags in the argument tag list. */ public void setTags(UniqueTagList replacement) { tags.setTags(replacement); } /** * Updates this todo with the details of {@code replacement}. */ public void resetData(ReadOnlyTodo replacement) { assert replacement != null; this.setName(replacement.getName()); this.setStartTime(replacement.getStartTime()); this.setEndTime(replacement.getEndTime()); this.setTags(replacement.getTags()); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof ReadOnlyTodo // instanceof handles nulls && this.isSameStateAs((ReadOnlyTodo) other)); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(name, starttime, endtime, tags); } @Override public String toString() { return getAsText(); } //@@author A0163786N public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().fullName); if (this.getEndTime() != null) { DateFormat dateFormat = new SimpleDateFormat(AddCommand.DATE_FORMAT); sb.append(" e/" + dateFormat.format(this.getEndTime())); if (this.getStartTime() != null) { sb.append(" s/" + dateFormat.format(this.getStartTime())); } } this.getTags().asObservableList().stream().forEach(s -> sb.append(" t/" + s.tagName + " ")); return sb.toString(); } //@@author }
src/test/java/seedu/todolist/testutil/TestTodo.java
package seedu.todolist.testutil; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Objects; import seedu.todolist.commons.util.CollectionUtil; import seedu.todolist.logic.commands.AddCommand; import seedu.todolist.model.tag.UniqueTagList; import seedu.todolist.model.todo.Name; import seedu.todolist.model.todo.ReadOnlyTodo; /** * A mutable todo object. For testing only. */ public class TestTodo implements ReadOnlyTodo { private Name name; private Date starttime; private Date endtime; private Date completeTime; private UniqueTagList tags; //@@author A0163720M /** * Constructor for a empty floating task */ public TestTodo() { this(null, null, null, null, new UniqueTagList()); } //@@author //@@author A0163720M /** * Constructor for a floating task */ public TestTodo(Name name, UniqueTagList tags) { this(name, null, null, null, tags); } //@@author //@@author A0163786N, A0163720M /** * Constructor for a deadline */ public TestTodo(Name name, Date endtime, UniqueTagList tags) { this(name, null, endtime, null, tags); } //@@author /** * Constructor for an event */ public TestTodo(Name name, Date starttime, Date endtime, UniqueTagList tags) { this(name, starttime, endtime, null, tags); } //@@author A0163786N, A0163720M /** * General todo constructor */ public TestTodo(Name name, Date starttime, Date endtime, Date completeTime, UniqueTagList tags) { this.name = name; this.starttime = starttime; this.endtime = endtime; this.completeTime = completeTime; this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list } //@@author /** * Creates a copy of the given ReadOnlyTodo. */ public TestTodo(ReadOnlyTodo source) { this(source.getName(), source.getStartTime(), source.getEndTime(), source.getCompleteTime(), source.getTags()); } public void setName(Name name) { assert name != null; this.name = name; } @Override public Name getName() { return name; } public void setStartTime(Date starttime) { assert starttime != null; this.starttime = starttime; } @Override public Date getStartTime() { return starttime; } public void setEndTime(Date endtime) { assert endtime != null; this.endtime = endtime; } @Override public Date getEndTime() { return endtime; } //@@author A0163786N public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } //@@author //@@author A0163786N @Override public Date getCompleteTime() { return completeTime; } //@@author @Override public UniqueTagList getTags() { return new UniqueTagList(tags); } /** * Replaces this todo's tags with the tags in the argument tag list. */ public void setTags(UniqueTagList replacement) { tags.setTags(replacement); } /** * Updates this todo with the details of {@code replacement}. */ public void resetData(ReadOnlyTodo replacement) { assert replacement != null; this.setName(replacement.getName()); this.setStartTime(replacement.getStartTime()); this.setEndTime(replacement.getEndTime()); this.setTags(replacement.getTags()); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof ReadOnlyTodo // instanceof handles nulls && this.isSameStateAs((ReadOnlyTodo) other)); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(name, starttime, endtime, tags); } @Override public String toString() { return getAsText(); } //@@author A0163786N public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().fullName); if (this.getEndTime() != null) { DateFormat dateFormat = new SimpleDateFormat(AddCommand.DATE_FORMAT); sb.append(" e/" + dateFormat.format(this.getEndTime())); if (this.getStartTime() != null) { sb.append(" s/" + dateFormat.format(this.getStartTime())); } } this.getTags().asObservableList().stream().forEach(s -> sb.append(" t/" + s.tagName + " ")); return sb.toString(); } //@@author }
Remove unused import
src/test/java/seedu/todolist/testutil/TestTodo.java
Remove unused import
Java
mit
8759e14c61683cbb3f8dfcd197aa8256aff016c5
0
OrangeFlare/FredBoat-CreamyMemers,OrangeFlare/FredBoat-CreamyMemers,napstr/FredBoat,Frederikam/FredBoat,Frederikam/FredBoat,Frederikam/FredBoat,Frederikam/FredBoat,napstr/FredBoat
/* * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package fredboat.perms; import fredboat.Config; import fredboat.db.EntityReader; import fredboat.db.entity.GuildPermissions; import fredboat.util.DiscordUtil; import fredboat.util.TextUtils; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Role; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.User; import java.text.MessageFormat; import java.util.List; public class PermsUtil { public static PermissionLevel getPerms(Member member) { if (isUserBotOwner(member.getUser())) { return PermissionLevel.BOT_OWNER; // https://fred.moe/Q-EB.png } else if (isAdmin(member)) { return PermissionLevel.BOT_ADMIN; } else if (member.isOwner()) { return PermissionLevel.ADMIN; } GuildPermissions gp = EntityReader.getGuildPermissions(member.getGuild()); if (checkList(gp.getAdminList(), member)) return PermissionLevel.ADMIN; if (checkList(gp.getDjList(), member)) return PermissionLevel.DJ; if (checkList(gp.getUserList(), member)) return PermissionLevel.USER; return PermissionLevel.BASE; } public static boolean checkPerms(PermissionLevel minLevel, Member member) { return getPerms(member).getLevel() >= minLevel.getLevel(); } public static boolean checkPermsWithFeedback(PermissionLevel minLevel, Member member, TextChannel channel) { PermissionLevel actual = getPerms(member); if (actual.getLevel() >= minLevel.getLevel()) { return true; } else { TextUtils.replyWithName(channel, member, MessageFormat.format("You don''t have permission to run this command! This command requires `{0}` but you only have `{1}`", minLevel, actual)); return false; } } /** * returns true if the member is or holds a role defined as admin in the configuration file */ private static boolean isAdmin(Member member) { boolean admin = false; for (String id : Config.CONFIG.getAdminIds()) { Role r = member.getGuild().getRoleById(id); if (member.getUser().getId().equals(id) || (r != null && member.getRoles().contains(r))) { admin = true; break; } } return admin; } // TODO: Make private and use getPerms() instead public static boolean isUserBotOwner(User user) { return DiscordUtil.getOwnerId(user.getJDA()).equals(user.getId()); } public static boolean checkList(List<String> list, Member member) { for (String id : list) { if (id.isEmpty()) continue; if (id.equals(member.getUser().getId())) return true; Role role = member.getGuild().getRoleById(id); if (role != null && (role.isPublicRole() || member.getRoles().contains(role))) return true; } return false; } }
FredBoat/src/main/java/fredboat/perms/PermsUtil.java
/* * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package fredboat.perms; import fredboat.Config; import fredboat.db.EntityReader; import fredboat.db.entity.GuildPermissions; import fredboat.util.DiscordUtil; import fredboat.util.TextUtils; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Role; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.User; import java.text.MessageFormat; import java.util.List; public class PermsUtil { public static PermissionLevel getPerms(Member member) { if (isUserBotOwner(member.getUser())) { return PermissionLevel.BOT_OWNER; // https://fred.moe/Q-EB.png } else if (isAdmin(member)) { return PermissionLevel.BOT_ADMIN; } else if (member.isOwner()) { return PermissionLevel.ADMIN; } GuildPermissions gp = EntityReader.getGuildPermissions(member.getGuild()); if (checkList(gp.getAdminList(), member)) return PermissionLevel.ADMIN; if (checkList(gp.getDjList(), member)) return PermissionLevel.DJ; if (checkList(gp.getUserList(), member)) return PermissionLevel.USER; return PermissionLevel.BASE; } public static boolean checkPerms(PermissionLevel minLevel, Member member) { return getPerms(member).getLevel() >= minLevel.getLevel(); } public static boolean checkPermsWithFeedback(PermissionLevel minLevel, Member member, TextChannel channel) { PermissionLevel actual = getPerms(member); if (actual.getLevel() >= minLevel.getLevel()) { return true; } else { TextUtils.replyWithName(channel, member, MessageFormat.format("You don''t have permission to run this command! This command requires `{0}` but you only have `{1}`", minLevel, actual)); return false; } } /** * returns true if the member is or holds a role defined as admin in the configuration file */ private static boolean isAdmin(Member member) { boolean admin = false; for (String id : Config.CONFIG.getAdminIds()) { Role r = member.getGuild().getRoleById(id); if (member.getUser().getId().equals(id) || (r != null && member.getRoles().contains(r))) { admin = true; break; } } return admin; } // TODO: Make private and use getPerms() instead public static boolean isUserBotOwner(User user) { return DiscordUtil.getOwnerId(user.getJDA()).equals(user.getId()); } public static boolean checkList(List<String> list, Member member) { for (String id : list) { if (id.equals(member.getUser().getId())) return true; Role role = member.getGuild().getRoleById(id); if (role != null && (role.isPublicRole() || member.getRoles().contains(role))) return true; } return false; } }
Fixed IllegalArgumentException
FredBoat/src/main/java/fredboat/perms/PermsUtil.java
Fixed IllegalArgumentException
Java
mit
3ac2e177c3b29071d5fd3c61281990d758404f9c
0
DMDirc/DMDirc,greboid/DMDirc,ShaneMcC/DMDirc-Client,ShaneMcC/DMDirc-Client,ShaneMcC/DMDirc-Client,greboid/DMDirc,DMDirc/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,greboid/DMDirc,csmith/DMDirc,greboid/DMDirc,csmith/DMDirc,DMDirc/DMDirc,csmith/DMDirc,csmith/DMDirc
/* * Copyright (c) 2006-2011 DMDirc Developers * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.plugins; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.config.InvalidIdentityFileException; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.util.SimpleInjector; import com.dmdirc.util.resourcemanager.ResourceManager; import com.dmdirc.util.validators.ValidationResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import java.util.logging.Level; /** * Stores plugin metadata and handles loading of plugin resources. */ public class PluginInfo implements Comparable<PluginInfo>, ServiceProvider { /** A logger for this class. */ private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(PluginInfo.class.getName()); /** The metadata for this plugin. */ private final PluginMetaData metadata; /** Filename for this plugin (taken from URL). */ private final String filename; /** The actual Plugin from this jar. */ private Plugin plugin; /** The classloader used for this Plugin. */ private PluginClassLoader classloader; /** The resource manager used by this pluginInfo. */ private ResourceManager resourceManager; /** Is this plugin only loaded temporarily? */ private boolean tempLoaded; /** List of classes this plugin has. */ private final List<String> myClasses = new ArrayList<String>(); /** Last Error Message. */ private String lastError = "No Error"; /** Are we trying to load? */ private boolean isLoading; /** List of services we provide. */ private final List<Service> provides = new ArrayList<Service>(); /** List of children of this plugin. */ private final List<PluginInfo> children = new ArrayList<PluginInfo>(); /** Map of exports. */ private final Map<String, ExportInfo> exports = new HashMap<String, ExportInfo>(); /** List of identities. */ private final List<Identity> identities = new ArrayList<Identity>(); /** * Create a new PluginInfo. * * @param metadata The plugin's metadata information * @throws PluginException if there is an error loading the Plugin * @since 0.6.6 */ public PluginInfo(final PluginMetaData metadata) throws PluginException { this.filename = new File(metadata.getPluginUrl().getPath()).getName(); this.metadata = metadata; ResourceManager res; try { res = getResourceManager(); } catch (IOException ioe) { lastError = "Error with resourcemanager: " + ioe.getMessage(); throw new PluginException("Plugin " + filename + " failed to load. " + lastError, ioe); } updateClassList(res); if (!myClasses.contains(metadata.getMainClass())) { lastError = "main class file (" + metadata.getMainClass() + ") not found in jar."; throw new PluginException("Plugin " + filename + " failed to load. " + lastError); } updateProvides(); getDefaults(); } /** * Gets this plugin's meta data object. * * @return Plugin meta data object */ public PluginMetaData getMetaData() { return metadata; } /** * Updates the list of known classes within this plugin from the specified * resource manager. */ private void updateClassList(final ResourceManager res) { myClasses.clear(); for (final String classfilename : res.getResourcesStartingWith("")) { final String classname = classfilename.replace('/', '.'); if (classname.endsWith(".class")) { myClasses.add(classname.substring(0, classname.length() - 6)); } } } /** * Retrieves the injector used to inject parameters into this * plugin's methods. * * @return The injector used for this plugin */ public SimpleInjector getInjector() { final SimpleInjector injector; final SimpleInjector[] parents = new SimpleInjector[metadata.getParents().length]; final Plugin[] plugins = new Plugin[parents.length]; for (int i = 0; i < metadata.getParents().length; i++) { final PluginInfo parent = PluginManager.getPluginManager() .getPluginInfoByName(metadata.getParents()[i]); parents[i] = parent.getInjector(); plugins[i] = parent.getPlugin(); } injector = new SimpleInjector(parents); for (Plugin parentPlugin : plugins) { injector.addParameter(parentPlugin); } injector.addParameter(PluginManager.class, PluginManager.getPluginManager()); injector.addParameter(ActionManager.getActionManager()); injector.addParameter(PluginInfo.class, this); injector.addParameter(PluginMetaData.class, metadata); injector.addParameter(IdentityManager.class, IdentityManager.getIdentityManager()); return injector; } /** * Get the licence for this plugin if it exists. * * @return An InputStream for the licence of this plugin, or null if no * licence found. * @throws IOException if there is an error with the ResourceManager. */ public Map<String, InputStream> getLicenceStreams() throws IOException { final TreeMap<String, InputStream> licences = new TreeMap<String, InputStream>(String.CASE_INSENSITIVE_ORDER); licences.putAll(getResourceManager().getResourcesStartingWithAsInputStreams( "META-INF/licences/")); return licences; } /** * Get the defaults, formatters and icons for this plugin. */ private void getDefaults() { final Identity defaults = IdentityManager.getAddonIdentity(); final String domain = "plugin-" + metadata.getName(); LOGGER.log(Level.FINER, "{0}: Using domain ''{1}''", new Object[]{metadata.getName(), domain}); for (Map.Entry<String, String> entry : metadata.getDefaultSettings().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); defaults.setOption(domain, key, value); } for (Map.Entry<String, String> entry : metadata.getFormatters().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); defaults.setOption("formatter", key, value); } for (Map.Entry<String, String> entry : metadata.getIcons().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); defaults.setOption("icon", key, value); } } /** * Try get the identities for this plugin. * This will unload any identities previously loaded by this plugin. */ private void loadIdentities() { try { final Map<String, InputStream> identityStreams = getResourceManager().getResourcesStartingWithAsInputStreams("META-INF/identities/"); unloadIdentities(); for (Map.Entry<String, InputStream> entry : identityStreams.entrySet()) { final String name = entry.getKey(); final InputStream stream = entry.getValue(); if (name.endsWith("/") || stream == null) { // Don't try to load folders or null streams continue; } synchronized (identities) { try { final Identity thisIdentity = new Identity(stream, false); IdentityManager.addIdentity(thisIdentity); identities.add(thisIdentity); } catch (final InvalidIdentityFileException ex) { Logger.userError(ErrorLevel.MEDIUM, "Error with identity file '" + name + "' in plugin '" + metadata.getName() + "'", ex); } } } } catch (final IOException ioe) { Logger.userError(ErrorLevel.MEDIUM, "Error finding identities in plugin '" + metadata.getName() + "'", ioe); } } /** * Unload any identities loaded by this plugin. */ private void unloadIdentities() { synchronized (identities) { for (Identity identity : identities) { IdentityManager.removeIdentity(identity); } identities.clear(); } } /** * Update provides list. */ private void updateProvides() { // Remove us from any existing provides lists. synchronized (provides) { for (Service service : provides) { service.delProvider(this); } provides.clear(); } // Get services provided by this plugin final Collection<String> providesList = metadata.getServices(); if (providesList != null) { for (String item : providesList) { final String[] bits = item.split(" "); final String name = bits[0]; final String type = bits.length > 1 ? bits[1] : "misc"; if (!name.equalsIgnoreCase("any") && !type.equalsIgnoreCase("export")) { final Service service = PluginManager.getPluginManager().getService(type, name, true); synchronized (provides) { service.addProvider(this); provides.add(service); } } } } updateExports(); } /** * Called when the plugin is updated using the updater. * Reloads metaData and updates the list of files. */ public void pluginUpdated() { try { // Force a new resourcemanager just incase. updateClassList(getResourceManager(true)); updateMetaData(); updateProvides(); getDefaults(); } catch (IOException ioe) { Logger.userError(ErrorLevel.MEDIUM, "There was an error updating " + metadata.getName(), ioe); } } /** * Try to reload the metaData from the plugin.config file. * If this fails, the old data will be used still. * * @return true if metaData was reloaded ok, else false. */ private boolean updateMetaData() { metadata.load(); return !metadata.hasErrors(); } /** * Gets a resource manager for this plugin * * @return The resource manager for this plugin * @throws IOException if there is any problem getting a ResourceManager for this plugin */ public ResourceManager getResourceManager() throws IOException { return getResourceManager(false); } /** * Get the resource manager for this plugin * * @return The resource manager for this plugin * @param forceNew Force a new resource manager rather than using the old one. * @throws IOException if there is any problem getting a ResourceManager for this plugin * @since 0.6 */ public synchronized ResourceManager getResourceManager(final boolean forceNew) throws IOException { if (resourceManager == null || forceNew) { resourceManager = ResourceManager.getResourceManager("jar://" + metadata.getPluginUrl().getPath()); // Clear the resourcemanager in 10 seconds to stop us holding the file open new Timer(filename + "-resourcemanagerTimer").schedule(new TimerTask() { /** {@inheritDoc} */ @Override public void run() { resourceManager = null; } }, 10000); } return resourceManager; } /** {@inheritDoc} */ @Override public final boolean isActive() { return isLoaded(); } /** {@inheritDoc} */ @Override public void activateServices() { loadPlugin(); } /** {@inheritDoc} */ @Override public String getProviderName() { return "Plugin: " + metadata.getFriendlyName() + " (" + metadata.getName() + " / " + getFilename() + ")"; } /** {@inheritDoc} */ @Override public List<Service> getServices() { synchronized (provides) { return new ArrayList<Service>(provides); } } /** * Is this plugin loaded? * * @return True if the plugin is currently (non-temporarily) loaded, false * otherwise */ public boolean isLoaded() { return plugin != null && !tempLoaded; } /** * Is this plugin temporarily loaded? * * @return True if this plugin is currently temporarily loaded, false * otherwise */ public boolean isTempLoaded() { return plugin != null && tempLoaded; } /** * Try to Load the plugin files temporarily. */ public void loadPluginTemp() { if (isLoaded() || isTempLoaded()) { // Already loaded, don't do anything return; } tempLoaded = true; loadPlugin(); } /** * Load any required plugins or services. * * @return True if all requirements have been satisfied, false otherwise */ protected boolean loadRequirements() { return loadRequiredPlugins() && loadRequiredServices(); } /** * Attempts to load all services that are required by this plugin. * * @return True iff all required services were found and satisfied */ protected boolean loadRequiredServices() { final ServiceManager manager = PluginManager.getPluginManager(); for (String serviceInfo : metadata.getRequiredServices()) { final String[] parts = serviceInfo.split(" ", 2); if ("any".equals(parts[0])) { Service best = null; boolean found = false; for (Service service : manager.getServicesByType(parts[1])) { if (service.isActive()) { found = true; break; } best = service; } if (!found && best != null) { found = best.activate(); } if (!found) { return false; } } else { final Service service = manager.getService(parts[1], parts[0]); if (service == null || !service.activate()) { return false; } } } return true; } /** * Attempts to load all plugins that are required by this plugin. * * @return True if all required plugins were found and loaded */ protected boolean loadRequiredPlugins() { final String required = metadata.getRequirements().get("plugins"); if (required != null) { for (String pluginName : required.split(",")) { final String[] data = pluginName.split(":"); if (!data[0].trim().isEmpty() && !loadRequiredPlugin(data[0])) { return false; } } } for (String parent : metadata.getParents()) { return loadRequiredPlugin(parent); } return true; } /** * Attempts to load the specified required plugin. * * @param name The name of the plugin to be loaded * @return True if the plugin was found and loaded, false otherwise */ protected boolean loadRequiredPlugin(final String name) { LOGGER.log(Level.FINE, "Loading required plugin '{0}' for plugin {1}", new Object[] { name, metadata.getName() }); final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(name); if (pi == null) { return false; } if (tempLoaded) { pi.loadPluginTemp(); } else { pi.loadPlugin(); } return true; } /** * Load the plugin files. */ public void loadPlugin() { if (isLoaded() || isLoading) { lastError = "Not Loading: (" + isLoaded() + "||" + isLoading + ")"; return; } updateProvides(); if (isTempLoaded()) { tempLoaded = false; if (!loadRequirements()) { tempLoaded = true; lastError = "Unable to satisfy dependencies for " + metadata.getName(); return; } try { plugin.onLoad(); } catch (LinkageError e) { lastError = "Error in onLoad for " + metadata.getName() + ":" + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); unloadPlugin(); } catch (Exception e) { lastError = "Error in onLoad for " + metadata.getName() + ":" + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); unloadPlugin(); } } else { isLoading = true; if (!loadRequirements()) { isLoading = false; lastError = "Unable to satisfy dependencies for " + metadata.getName(); return; } loadIdentities(); loadClass(metadata.getMainClass()); if (isLoaded()) { ActionManager.getActionManager().triggerEvent( CoreActionType.PLUGIN_LOADED, null, this); } isLoading = false; } } /** * Add the given Plugin as a child of this plugin. * * @param child Child to add */ public void addChild(final PluginInfo child) { children.add(child); } /** * Remove the given Plugin as a child of this plugin. * * @param child Child to remove */ public void delChild(final PluginInfo child) { children.remove(child); } /** * Returns a list of this plugin's children. * * @return List of child plugins */ public List<PluginInfo> getChildren() { return Collections.unmodifiableList(children); } /** * Checks if this plugin has any children. * * @return true iff this plugin has children */ public boolean hasChildren() { return !children.isEmpty(); } /** * Initialises this plugin's classloader. */ private void initialiseClassLoader() { if (classloader == null) { final PluginClassLoader[] loaders = new PluginClassLoader[metadata.getParents().length]; for (int i = 0; i < metadata.getParents().length; i++) { final String parentName = metadata.getParents()[i]; final PluginInfo parent = PluginManager.getPluginManager() .getPluginInfoByName(parentName); parent.addChild(this); loaders[i] = parent.getPluginClassLoader(); if (loaders[i] == null) { // Not loaded? Try again... parent.loadPlugin(); loaders[i] = parent.getPluginClassLoader(); if (loaders[i] == null) { lastError = "Unable to get classloader from required parent '" + parentName + "' for " + metadata.getName(); return; } } } classloader = new PluginClassLoader(this, loaders); } } /** * Load the given classname. * * @param classname Class to load */ private void loadClass(final String classname) { try { initialiseClassLoader(); // Don't reload a class if its already loaded. if (classloader.isClassLoaded(classname, true)) { lastError = "Classloader says we are already loaded."; return; } final Class<?> clazz = classloader.loadClass(classname); if (clazz == null) { lastError = "Class '" + classname + "' was not able to load."; return; } // Only try and construct the main class, anything else should be constructed // by the plugin itself. if (classname.equals(metadata.getMainClass())) { final Object temp = getInjector().createInstance(clazz); if (temp instanceof Plugin) { final ValidationResponse prerequisites = ((Plugin) temp).checkPrerequisites(); if (prerequisites.isFailure()) { if (!tempLoaded) { lastError = "Prerequisites for plugin not met. ('" + filename + ":" + metadata.getMainClass() + "' -> '" + prerequisites.getFailureReason() + "') "; Logger.userError(ErrorLevel.LOW, lastError); } } else { plugin = (Plugin) temp; LOGGER.log(Level.FINER, "{0}: Setting domain ''plugin-{0}''", new Object[]{metadata.getName()}); plugin.setDomain("plugin-" + metadata.getName()); if (!tempLoaded) { try { plugin.onLoad(); } catch (LinkageError e) { lastError = "Error in onLoad for " + metadata.getName() + ":" + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); unloadPlugin(); } catch (Exception e) { lastError = "Error in onLoad for " + metadata.getName() + ":" + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); unloadPlugin(); } } } } } } catch (ClassNotFoundException cnfe) { lastError = "Class not found ('" + filename + ":" + classname + ":" + classname.equals(metadata.getMainClass()) + "') - " + cnfe.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, cnfe); } catch (NoClassDefFoundError ncdf) { lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(metadata.getMainClass()) + "') - Unable to find class: " + ncdf.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ncdf); } catch (VerifyError ve) { lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(metadata.getMainClass()) + "') - Incompatible: " + ve.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ve); } catch (IllegalArgumentException ex) { lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(metadata.getMainClass()) + "') - Unable to construct: " + ex.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ex); } } /** * Unload the plugin if possible. */ public void unloadPlugin() { unloadPlugin(false); } /** * Can this plugin be unloaded? * Will return false if: * - The plugin is persistent (all its classes are loaded into the global class loader) * - The plugin isn't currently loaded * - The metadata key "unloadable" is set to false, no or 0 * * @return true if plugin can be unloaded */ public boolean isUnloadable() { return !isPersistent() && (isTempLoaded() || isLoaded()) && metadata.isUnloadable(); } /** * Unload the plugin if possible. * * @param parentUnloading is our parent already unloading? (if so, don't call delChild) */ private void unloadPlugin(final boolean parentUnloading) { if (isUnloadable()) { if (!isTempLoaded()) { // Unload all children for (PluginInfo child : children) { child.unloadPlugin(true); } // Delete ourself as a child of our parent. if (!parentUnloading) { for (String parent : metadata.getParents()) { final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(parent); if (pi != null) { pi.delChild(this); } } } // Now unload ourself try { plugin.onUnload(); } catch (Exception e) { lastError = "Error in onUnload for " + metadata.getName() + ":" + e + " - " + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); } catch (LinkageError e) { lastError = "Error in onUnload for " + metadata.getName() + ":" + e + " - " + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); } ActionManager.getActionManager().triggerEvent( CoreActionType.PLUGIN_UNLOADED, null, this); synchronized (provides) { for (Service service : provides) { service.delProvider(this); } provides.clear(); } } unloadIdentities(); tempLoaded = false; plugin = null; classloader = null; } } /** * Get the last Error * * @return last Error * @since 0.6 */ public String getLastError() { return lastError; } /** * Get the list of Classes * * @return Classes this plugin has */ public List<String> getClassList() { return Collections.unmodifiableList(myClasses); } /** * Get the Plugin for this plugin. * * @return Plugin */ public Plugin getPlugin() { return plugin; } /** * Get the PluginClassLoader for this plugin. * * @return PluginClassLoader */ protected PluginClassLoader getPluginClassLoader() { return classloader; } /** * Is this a persistent plugin? * * @return true if persistent, else false */ public boolean isPersistent() { return metadata.getPersistentClasses().contains("*"); } /** * Does this plugin contain any persistent classes? * * @return true if this plugin contains any persistent classes, else false */ public boolean hasPersistent() { return !metadata.getPersistentClasses().isEmpty(); } /** * Get a list of all persistent classes in this plugin * * @return List of all persistent classes in this plugin */ public Collection<String> getPersistentClasses() { if (isPersistent()) { return getClassList(); } else { return metadata.getPersistentClasses(); } } /** * Is this a persistent class? * * @param classname class to check persistence of * @return true if file (or whole plugin) is persistent, else false */ public boolean isPersistent(final String classname) { return isPersistent() || metadata.getPersistentClasses().contains(classname); } /** * Get the plugin Filename. * * @return Filename of plugin */ public String getFilename() { return filename; } /** * String Representation of this plugin * * @return String Representation of this plugin */ @Override public String toString() { return metadata.getFriendlyName() + " - " + filename; } /** {@inheritDoc} */ @Override public int compareTo(final PluginInfo o) { return toString().compareTo(o.toString()); } /** * Update exports list. */ private void updateExports() { exports.clear(); // Get exports provided by this plugin final Collection<String> exportsList = metadata.getExports(); for (String item : exportsList) { final String[] bits = item.split(" "); if (bits.length > 2) { final String methodName = bits[0]; final String methodClass = bits[2]; final String serviceName = bits.length > 4 ? bits[4] : bits[0]; // Add a provides for this final Service service = PluginManager.getPluginManager().getService("export", serviceName, true); synchronized (provides) { service.addProvider(this); provides.add(service); } // Add is as an export exports.put(serviceName, new ExportInfo(methodName, methodClass, this)); } } } /** {@inheritDoc} */ @Override public ExportedService getExportedService(final String name) { if (exports.containsKey(name)) { return exports.get(name).getExportedService(); } else { return null; } } /** * Does this plugin export the specified service? * * @param name Name of the service to check * * @return true iff the plugin exports the service */ public boolean hasExportedService(final String name) { return exports.containsKey(name); } /** * Get the Plugin object for this plugin. * * @return Plugin object for the plugin */ protected Plugin getPluginObject() { return plugin; } }
src/com/dmdirc/plugins/PluginInfo.java
/* * Copyright (c) 2006-2011 DMDirc Developers * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.plugins; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.config.InvalidIdentityFileException; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.util.SimpleInjector; import com.dmdirc.util.resourcemanager.ResourceManager; import com.dmdirc.util.validators.ValidationResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import java.util.logging.Level; /** * Stores plugin metadata and handles loading of plugin resources. */ public class PluginInfo implements Comparable<PluginInfo>, ServiceProvider { /** A logger for this class. */ private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(PluginInfo.class.getName()); /** The metadata for this plugin. */ private final PluginMetaData metadata; /** Filename for this plugin (taken from URL). */ private final String filename; /** The actual Plugin from this jar. */ private Plugin plugin; /** The classloader used for this Plugin. */ private PluginClassLoader classloader; /** The resource manager used by this pluginInfo. */ private ResourceManager resourceManager; /** Is this plugin only loaded temporarily? */ private boolean tempLoaded; /** List of classes this plugin has. */ private final List<String> myClasses = new ArrayList<String>(); /** Last Error Message. */ private String lastError = "No Error"; /** Are we trying to load? */ private boolean isLoading; /** List of services we provide. */ private final List<Service> provides = new ArrayList<Service>(); /** List of children of this plugin. */ private final List<PluginInfo> children = new ArrayList<PluginInfo>(); /** Map of exports. */ private final Map<String, ExportInfo> exports = new HashMap<String, ExportInfo>(); /** List of identities. */ private final List<Identity> identities = new ArrayList<Identity>(); /** * Create a new PluginInfo. * * @param metadata The plugin's metadata information * @throws PluginException if there is an error loading the Plugin * @since 0.6.6 */ public PluginInfo(final PluginMetaData metadata) throws PluginException { this.filename = new File(metadata.getPluginUrl().getPath()).getName(); this.metadata = metadata; ResourceManager res; try { res = getResourceManager(); } catch (IOException ioe) { lastError = "Error with resourcemanager: " + ioe.getMessage(); throw new PluginException("Plugin " + filename + " failed to load. " + lastError, ioe); } updateClassList(res); if (!myClasses.contains(metadata.getMainClass())) { lastError = "main class file (" + metadata.getMainClass() + ") not found in jar."; throw new PluginException("Plugin " + filename + " failed to load. " + lastError); } updateProvides(); getDefaults(); } /** * Gets this plugin's meta data object. * * @return Plugin meta data object */ public PluginMetaData getMetaData() { return metadata; } /** * Updates the list of known classes within this plugin from the specified * resource manager. */ private void updateClassList(final ResourceManager res) { myClasses.clear(); for (final String classfilename : res.getResourcesStartingWith("")) { final String classname = classfilename.replace('/', '.'); if (classname.endsWith(".class")) { myClasses.add(classname.substring(0, classname.length() - 6)); } } } /** * Retrieves the injector used to inject parameters into this * plugin's methods. * * @return The injector used for this plugin */ public SimpleInjector getInjector() { final SimpleInjector injector; final SimpleInjector[] parents = new SimpleInjector[metadata.getParents().length]; final Plugin[] plugins = new Plugin[parents.length]; for (int i = 0; i < metadata.getParents().length; i++) { final PluginInfo parent = PluginManager.getPluginManager() .getPluginInfoByName(metadata.getParents()[i]); parents[i] = parent.getInjector(); plugins[i] = parent.getPlugin(); } injector = new SimpleInjector(parents); for (Plugin parentPlugin : plugins) { injector.addParameter(parentPlugin); } injector.addParameter(PluginManager.class, PluginManager.getPluginManager()); injector.addParameter(ActionManager.getActionManager()); injector.addParameter(PluginInfo.class, this); injector.addParameter(PluginMetaData.class, metadata); return injector; } /** * Get the licence for this plugin if it exists. * * @return An InputStream for the licence of this plugin, or null if no * licence found. * @throws IOException if there is an error with the ResourceManager. */ public Map<String, InputStream> getLicenceStreams() throws IOException { final TreeMap<String, InputStream> licences = new TreeMap<String, InputStream>(String.CASE_INSENSITIVE_ORDER); licences.putAll(getResourceManager().getResourcesStartingWithAsInputStreams( "META-INF/licences/")); return licences; } /** * Get the defaults, formatters and icons for this plugin. */ private void getDefaults() { final Identity defaults = IdentityManager.getAddonIdentity(); final String domain = "plugin-" + metadata.getName(); LOGGER.log(Level.FINER, "{0}: Using domain ''{1}''", new Object[]{metadata.getName(), domain}); for (Map.Entry<String, String> entry : metadata.getDefaultSettings().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); defaults.setOption(domain, key, value); } for (Map.Entry<String, String> entry : metadata.getFormatters().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); defaults.setOption("formatter", key, value); } for (Map.Entry<String, String> entry : metadata.getIcons().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); defaults.setOption("icon", key, value); } } /** * Try get the identities for this plugin. * This will unload any identities previously loaded by this plugin. */ private void loadIdentities() { try { final Map<String, InputStream> identityStreams = getResourceManager().getResourcesStartingWithAsInputStreams("META-INF/identities/"); unloadIdentities(); for (Map.Entry<String, InputStream> entry : identityStreams.entrySet()) { final String name = entry.getKey(); final InputStream stream = entry.getValue(); if (name.endsWith("/") || stream == null) { // Don't try to load folders or null streams continue; } synchronized (identities) { try { final Identity thisIdentity = new Identity(stream, false); IdentityManager.addIdentity(thisIdentity); identities.add(thisIdentity); } catch (final InvalidIdentityFileException ex) { Logger.userError(ErrorLevel.MEDIUM, "Error with identity file '" + name + "' in plugin '" + metadata.getName() + "'", ex); } } } } catch (final IOException ioe) { Logger.userError(ErrorLevel.MEDIUM, "Error finding identities in plugin '" + metadata.getName() + "'", ioe); } } /** * Unload any identities loaded by this plugin. */ private void unloadIdentities() { synchronized (identities) { for (Identity identity : identities) { IdentityManager.removeIdentity(identity); } identities.clear(); } } /** * Update provides list. */ private void updateProvides() { // Remove us from any existing provides lists. synchronized (provides) { for (Service service : provides) { service.delProvider(this); } provides.clear(); } // Get services provided by this plugin final Collection<String> providesList = metadata.getServices(); if (providesList != null) { for (String item : providesList) { final String[] bits = item.split(" "); final String name = bits[0]; final String type = bits.length > 1 ? bits[1] : "misc"; if (!name.equalsIgnoreCase("any") && !type.equalsIgnoreCase("export")) { final Service service = PluginManager.getPluginManager().getService(type, name, true); synchronized (provides) { service.addProvider(this); provides.add(service); } } } } updateExports(); } /** * Called when the plugin is updated using the updater. * Reloads metaData and updates the list of files. */ public void pluginUpdated() { try { // Force a new resourcemanager just incase. updateClassList(getResourceManager(true)); updateMetaData(); updateProvides(); getDefaults(); } catch (IOException ioe) { Logger.userError(ErrorLevel.MEDIUM, "There was an error updating " + metadata.getName(), ioe); } } /** * Try to reload the metaData from the plugin.config file. * If this fails, the old data will be used still. * * @return true if metaData was reloaded ok, else false. */ private boolean updateMetaData() { metadata.load(); return !metadata.hasErrors(); } /** * Gets a resource manager for this plugin * * @return The resource manager for this plugin * @throws IOException if there is any problem getting a ResourceManager for this plugin */ public ResourceManager getResourceManager() throws IOException { return getResourceManager(false); } /** * Get the resource manager for this plugin * * @return The resource manager for this plugin * @param forceNew Force a new resource manager rather than using the old one. * @throws IOException if there is any problem getting a ResourceManager for this plugin * @since 0.6 */ public synchronized ResourceManager getResourceManager(final boolean forceNew) throws IOException { if (resourceManager == null || forceNew) { resourceManager = ResourceManager.getResourceManager("jar://" + metadata.getPluginUrl().getPath()); // Clear the resourcemanager in 10 seconds to stop us holding the file open new Timer(filename + "-resourcemanagerTimer").schedule(new TimerTask() { /** {@inheritDoc} */ @Override public void run() { resourceManager = null; } }, 10000); } return resourceManager; } /** {@inheritDoc} */ @Override public final boolean isActive() { return isLoaded(); } /** {@inheritDoc} */ @Override public void activateServices() { loadPlugin(); } /** {@inheritDoc} */ @Override public String getProviderName() { return "Plugin: " + metadata.getFriendlyName() + " (" + metadata.getName() + " / " + getFilename() + ")"; } /** {@inheritDoc} */ @Override public List<Service> getServices() { synchronized (provides) { return new ArrayList<Service>(provides); } } /** * Is this plugin loaded? * * @return True if the plugin is currently (non-temporarily) loaded, false * otherwise */ public boolean isLoaded() { return plugin != null && !tempLoaded; } /** * Is this plugin temporarily loaded? * * @return True if this plugin is currently temporarily loaded, false * otherwise */ public boolean isTempLoaded() { return plugin != null && tempLoaded; } /** * Try to Load the plugin files temporarily. */ public void loadPluginTemp() { if (isLoaded() || isTempLoaded()) { // Already loaded, don't do anything return; } tempLoaded = true; loadPlugin(); } /** * Load any required plugins or services. * * @return True if all requirements have been satisfied, false otherwise */ protected boolean loadRequirements() { return loadRequiredPlugins() && loadRequiredServices(); } /** * Attempts to load all services that are required by this plugin. * * @return True iff all required services were found and satisfied */ protected boolean loadRequiredServices() { final ServiceManager manager = PluginManager.getPluginManager(); for (String serviceInfo : metadata.getRequiredServices()) { final String[] parts = serviceInfo.split(" ", 2); if ("any".equals(parts[0])) { Service best = null; boolean found = false; for (Service service : manager.getServicesByType(parts[1])) { if (service.isActive()) { found = true; break; } best = service; } if (!found && best != null) { found = best.activate(); } if (!found) { return false; } } else { final Service service = manager.getService(parts[1], parts[0]); if (service == null || !service.activate()) { return false; } } } return true; } /** * Attempts to load all plugins that are required by this plugin. * * @return True if all required plugins were found and loaded */ protected boolean loadRequiredPlugins() { final String required = metadata.getRequirements().get("plugins"); if (required != null) { for (String pluginName : required.split(",")) { final String[] data = pluginName.split(":"); if (!data[0].trim().isEmpty() && !loadRequiredPlugin(data[0])) { return false; } } } for (String parent : metadata.getParents()) { return loadRequiredPlugin(parent); } return true; } /** * Attempts to load the specified required plugin. * * @param name The name of the plugin to be loaded * @return True if the plugin was found and loaded, false otherwise */ protected boolean loadRequiredPlugin(final String name) { LOGGER.log(Level.FINE, "Loading required plugin '{0}' for plugin {1}", new Object[] { name, metadata.getName() }); final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(name); if (pi == null) { return false; } if (tempLoaded) { pi.loadPluginTemp(); } else { pi.loadPlugin(); } return true; } /** * Load the plugin files. */ public void loadPlugin() { if (isLoaded() || isLoading) { lastError = "Not Loading: (" + isLoaded() + "||" + isLoading + ")"; return; } updateProvides(); if (isTempLoaded()) { tempLoaded = false; if (!loadRequirements()) { tempLoaded = true; lastError = "Unable to satisfy dependencies for " + metadata.getName(); return; } try { plugin.onLoad(); } catch (LinkageError e) { lastError = "Error in onLoad for " + metadata.getName() + ":" + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); unloadPlugin(); } catch (Exception e) { lastError = "Error in onLoad for " + metadata.getName() + ":" + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); unloadPlugin(); } } else { isLoading = true; if (!loadRequirements()) { isLoading = false; lastError = "Unable to satisfy dependencies for " + metadata.getName(); return; } loadIdentities(); loadClass(metadata.getMainClass()); if (isLoaded()) { ActionManager.getActionManager().triggerEvent( CoreActionType.PLUGIN_LOADED, null, this); } isLoading = false; } } /** * Add the given Plugin as a child of this plugin. * * @param child Child to add */ public void addChild(final PluginInfo child) { children.add(child); } /** * Remove the given Plugin as a child of this plugin. * * @param child Child to remove */ public void delChild(final PluginInfo child) { children.remove(child); } /** * Returns a list of this plugin's children. * * @return List of child plugins */ public List<PluginInfo> getChildren() { return Collections.unmodifiableList(children); } /** * Checks if this plugin has any children. * * @return true iff this plugin has children */ public boolean hasChildren() { return !children.isEmpty(); } /** * Initialises this plugin's classloader. */ private void initialiseClassLoader() { if (classloader == null) { final PluginClassLoader[] loaders = new PluginClassLoader[metadata.getParents().length]; for (int i = 0; i < metadata.getParents().length; i++) { final String parentName = metadata.getParents()[i]; final PluginInfo parent = PluginManager.getPluginManager() .getPluginInfoByName(parentName); parent.addChild(this); loaders[i] = parent.getPluginClassLoader(); if (loaders[i] == null) { // Not loaded? Try again... parent.loadPlugin(); loaders[i] = parent.getPluginClassLoader(); if (loaders[i] == null) { lastError = "Unable to get classloader from required parent '" + parentName + "' for " + metadata.getName(); return; } } } classloader = new PluginClassLoader(this, loaders); } } /** * Load the given classname. * * @param classname Class to load */ private void loadClass(final String classname) { try { initialiseClassLoader(); // Don't reload a class if its already loaded. if (classloader.isClassLoaded(classname, true)) { lastError = "Classloader says we are already loaded."; return; } final Class<?> clazz = classloader.loadClass(classname); if (clazz == null) { lastError = "Class '" + classname + "' was not able to load."; return; } // Only try and construct the main class, anything else should be constructed // by the plugin itself. if (classname.equals(metadata.getMainClass())) { final Object temp = getInjector().createInstance(clazz); if (temp instanceof Plugin) { final ValidationResponse prerequisites = ((Plugin) temp).checkPrerequisites(); if (prerequisites.isFailure()) { if (!tempLoaded) { lastError = "Prerequisites for plugin not met. ('" + filename + ":" + metadata.getMainClass() + "' -> '" + prerequisites.getFailureReason() + "') "; Logger.userError(ErrorLevel.LOW, lastError); } } else { plugin = (Plugin) temp; LOGGER.log(Level.FINER, "{0}: Setting domain ''plugin-{0}''", new Object[]{metadata.getName()}); plugin.setDomain("plugin-" + metadata.getName()); if (!tempLoaded) { try { plugin.onLoad(); } catch (LinkageError e) { lastError = "Error in onLoad for " + metadata.getName() + ":" + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); unloadPlugin(); } catch (Exception e) { lastError = "Error in onLoad for " + metadata.getName() + ":" + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); unloadPlugin(); } } } } } } catch (ClassNotFoundException cnfe) { lastError = "Class not found ('" + filename + ":" + classname + ":" + classname.equals(metadata.getMainClass()) + "') - " + cnfe.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, cnfe); } catch (NoClassDefFoundError ncdf) { lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(metadata.getMainClass()) + "') - Unable to find class: " + ncdf.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ncdf); } catch (VerifyError ve) { lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(metadata.getMainClass()) + "') - Incompatible: " + ve.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ve); } catch (IllegalArgumentException ex) { lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(metadata.getMainClass()) + "') - Unable to construct: " + ex.getMessage(); Logger.userError(ErrorLevel.LOW, lastError, ex); } } /** * Unload the plugin if possible. */ public void unloadPlugin() { unloadPlugin(false); } /** * Can this plugin be unloaded? * Will return false if: * - The plugin is persistent (all its classes are loaded into the global class loader) * - The plugin isn't currently loaded * - The metadata key "unloadable" is set to false, no or 0 * * @return true if plugin can be unloaded */ public boolean isUnloadable() { return !isPersistent() && (isTempLoaded() || isLoaded()) && metadata.isUnloadable(); } /** * Unload the plugin if possible. * * @param parentUnloading is our parent already unloading? (if so, don't call delChild) */ private void unloadPlugin(final boolean parentUnloading) { if (isUnloadable()) { if (!isTempLoaded()) { // Unload all children for (PluginInfo child : children) { child.unloadPlugin(true); } // Delete ourself as a child of our parent. if (!parentUnloading) { for (String parent : metadata.getParents()) { final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(parent); if (pi != null) { pi.delChild(this); } } } // Now unload ourself try { plugin.onUnload(); } catch (Exception e) { lastError = "Error in onUnload for " + metadata.getName() + ":" + e + " - " + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); } catch (LinkageError e) { lastError = "Error in onUnload for " + metadata.getName() + ":" + e + " - " + e.getMessage(); Logger.userError(ErrorLevel.MEDIUM, lastError, e); } ActionManager.getActionManager().triggerEvent( CoreActionType.PLUGIN_UNLOADED, null, this); synchronized (provides) { for (Service service : provides) { service.delProvider(this); } provides.clear(); } } unloadIdentities(); tempLoaded = false; plugin = null; classloader = null; } } /** * Get the last Error * * @return last Error * @since 0.6 */ public String getLastError() { return lastError; } /** * Get the list of Classes * * @return Classes this plugin has */ public List<String> getClassList() { return Collections.unmodifiableList(myClasses); } /** * Get the Plugin for this plugin. * * @return Plugin */ public Plugin getPlugin() { return plugin; } /** * Get the PluginClassLoader for this plugin. * * @return PluginClassLoader */ protected PluginClassLoader getPluginClassLoader() { return classloader; } /** * Is this a persistent plugin? * * @return true if persistent, else false */ public boolean isPersistent() { return metadata.getPersistentClasses().contains("*"); } /** * Does this plugin contain any persistent classes? * * @return true if this plugin contains any persistent classes, else false */ public boolean hasPersistent() { return !metadata.getPersistentClasses().isEmpty(); } /** * Get a list of all persistent classes in this plugin * * @return List of all persistent classes in this plugin */ public Collection<String> getPersistentClasses() { if (isPersistent()) { return getClassList(); } else { return metadata.getPersistentClasses(); } } /** * Is this a persistent class? * * @param classname class to check persistence of * @return true if file (or whole plugin) is persistent, else false */ public boolean isPersistent(final String classname) { return isPersistent() || metadata.getPersistentClasses().contains(classname); } /** * Get the plugin Filename. * * @return Filename of plugin */ public String getFilename() { return filename; } /** * String Representation of this plugin * * @return String Representation of this plugin */ @Override public String toString() { return metadata.getFriendlyName() + " - " + filename; } /** {@inheritDoc} */ @Override public int compareTo(final PluginInfo o) { return toString().compareTo(o.toString()); } /** * Update exports list. */ private void updateExports() { exports.clear(); // Get exports provided by this plugin final Collection<String> exportsList = metadata.getExports(); for (String item : exportsList) { final String[] bits = item.split(" "); if (bits.length > 2) { final String methodName = bits[0]; final String methodClass = bits[2]; final String serviceName = bits.length > 4 ? bits[4] : bits[0]; // Add a provides for this final Service service = PluginManager.getPluginManager().getService("export", serviceName, true); synchronized (provides) { service.addProvider(this); provides.add(service); } // Add is as an export exports.put(serviceName, new ExportInfo(methodName, methodClass, this)); } } } /** {@inheritDoc} */ @Override public ExportedService getExportedService(final String name) { if (exports.containsKey(name)) { return exports.get(name).getExportedService(); } else { return null; } } /** * Does this plugin export the specified service? * * @param name Name of the service to check * * @return true iff the plugin exports the service */ public boolean hasExportedService(final String name) { return exports.containsKey(name); } /** * Get the Plugin object for this plugin. * * @return Plugin object for the plugin */ protected Plugin getPluginObject() { return plugin; } }
Add support for IdentityManager to be injected into plugins. Change-Id: Ib71ce92ce324a364b6e95f20e7ab107d44c71481 Reviewed-on: http://gerrit.dmdirc.com/2239 Automatic-Compile: DMDirc Build Manager Reviewed-by: Chris Smith <[email protected]>
src/com/dmdirc/plugins/PluginInfo.java
Add support for IdentityManager to be injected into plugins.
Java
mit
bd228787aa310932ce39788c0327ae75481fa32f
0
aviolette/foodtrucklocator,aviolette/foodtrucklocator,aviolette/foodtrucklocator,aviolette/foodtrucklocator
package foodtruck.server.job; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.google.inject.Inject; import com.google.inject.Singleton; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import foodtruck.dao.TruckDAO; import foodtruck.truckstops.FoodTruckStopService; import foodtruck.twitter.TwitterService; import foodtruck.util.Clock; /** * @author [email protected] * @since Jul 13, 2011 */ @Singleton public class RecacheServlet extends HttpServlet { private final FoodTruckStopService service; private final Clock clock; private final TwitterService twitterService; private final TruckDAO truckDAO; private final DateTimeFormatter timeFormatter; private static final Logger log = Logger.getLogger(RecacheServlet.class.getName()); @Inject public RecacheServlet(FoodTruckStopService service, Clock clock, TwitterService twitterService, TruckDAO truckDAO, DateTimeZone zone) { this.twitterService = twitterService; this.service = service; this.clock = clock; this.truckDAO = truckDAO; this.timeFormatter = DateTimeFormat.forPattern("YYYYMMdd").withZone(zone); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String truck = req.getParameter("truck"); final String date = req.getParameter("date"); LocalDate when = parseDate(date); if (!Strings.isNullOrEmpty(truck)) { service.updateStopsForTruck(when, truckDAO.findById(truck)); } else { service.updateStopsFor(when); } twitterService.twittalyze(); } private LocalDate parseDate(String date) { if (!Strings.isNullOrEmpty(date)) { try { return timeFormatter.parseDateTime(date).toDateMidnight().toLocalDate(); } catch (Exception e) { log.log(Level.WARNING, "Error formatting time", e); Throwables.propagate(e); } } return clock.currentDay(); } }
src/main/java/foodtruck/server/job/RecacheServlet.java
package foodtruck.server.job; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.common.base.Strings; import com.google.inject.Inject; import com.google.inject.Singleton; import foodtruck.dao.TruckDAO; import foodtruck.truckstops.FoodTruckStopService; import foodtruck.twitter.TwitterService; import foodtruck.util.Clock; /** * @author [email protected] * @since Jul 13, 2011 */ @Singleton public class RecacheServlet extends HttpServlet { private final FoodTruckStopService service; private final Clock clock; private final TwitterService twitterService; private final TruckDAO truckDAO; @Inject public RecacheServlet(FoodTruckStopService service, Clock clock, TwitterService twitterService, TruckDAO truckDAO) { this.twitterService = twitterService; this.service = service; this.clock = clock; this.truckDAO = truckDAO; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String truck = req.getParameter("truck"); if (!Strings.isNullOrEmpty(truck)) { service.updateStopsForTruck(clock.currentDay(), truckDAO.findById(truck)); } else { service.updateStopsFor(clock.currentDay()); } twitterService.twittalyze(); } }
Allow specification of a date on the recache servlet
src/main/java/foodtruck/server/job/RecacheServlet.java
Allow specification of a date on the recache servlet
Java
mit
1514affb86d439f7976440fab9526dd32b3d88e1
0
nh0815/jrgb
package ui; import rgb.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.swing.filechooser.*; /** * Created by nick on 10/22/15. */ public class RGBWindow extends JFrame{ private RGBPanel panel; public RGBWindow(){ super("jrgb"); this.panel = new RGBPanel(); JMenuBar menuBar = new JMenuBar(); JMenu file = new JMenu("File"); JMenu image = new JMenu("Image"); JMenuItem open = new JMenuItem("Open"); open.addActionListener(new OpenFileActionListener()); file.add(open); JMenuItem original = new JMenuItem("Original"); original.addActionListener(new OriginalActionListener()); image.add(original); JMenuItem invert = new JMenuItem("Invert"); invert.addActionListener(new InvertActionListener()); image.add(invert); JMenuItem sepia = new JMenuItem("Sepia"); sepia.addActionListener(new SepiaActionListener()); image.add(sepia); JMenuItem red = new JMenuItem("Red"); red.addActionListener(new RedActionListener()); image.add(red); JMenuItem green = new JMenuItem("Green"); green.addActionListener(new GreenActionListener()); image.add(green); JMenuItem blue = new JMenuItem("Blue"); blue.addActionListener(new BlueActionListener()); image.add(blue); menuBar.add(file); menuBar.add(image); setJMenuBar(menuBar); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setContentPane(panel); pack(); setVisible(true); } private class OpenFileActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent actionEvent) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new ImageFilter()); int returnVal = chooser.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION){ File file = chooser.getSelectedFile(); try { BufferedImage image = ImageIO.read(file); panel.setImage(image); pack(); } catch (IOException e) { e.printStackTrace(); } } } } private class OriginalActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { panel.setRGBStrategy(new VanillaRGBStrategy()); panel.convert(); } } private class InvertActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { panel.setRGBStrategy(new InvertRGBStrategy()); panel.convert(); } } private class SepiaActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { panel.setRGBStrategy(new SepiaRGBStrategy()); panel.convert(); } } private class RedActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { panel.setRGBStrategy(new RedRGBStrategy()); panel.convert(); } } private class GreenActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { panel.setRGBStrategy(new GreenRGBStrategy()); panel.convert(); } } private class BlueActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { panel.setRGBStrategy(new BlueRGBStrategy()); panel.convert(); } } private static class ImageFilter extends FileFilter { public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = Utils.getExtension(f); if (extension != null) { if (extension.equals(Utils.tiff) || extension.equals(Utils.tif) || extension.equals(Utils.gif) || extension.equals(Utils.jpeg) || extension.equals(Utils.jpg) || extension.equals(Utils.png)) { return true; } else { return false; } } return false; } public String getDescription() { return "Just Images"; } } private static class Utils { public final static String jpeg = "jpeg"; public final static String jpg = "jpg"; public final static String gif = "gif"; public final static String tiff = "tiff"; public final static String tif = "tif"; public final static String png = "png"; /* * Get the extension of a file. */ public static String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i+1).toLowerCase(); } return ext; } } }
src/ui/RGBWindow.java
package ui; import rgb.InvertRGBStrategy; import rgb.SepiaRGBStrategy; import rgb.VanillaRGBStrategy; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.swing.filechooser.*; /** * Created by nick on 10/22/15. */ public class RGBWindow extends JFrame{ private RGBPanel panel; public RGBWindow(){ super("jrgb"); this.panel = new RGBPanel(); JMenuBar menuBar = new JMenuBar(); JMenu file = new JMenu("File"); JMenu image = new JMenu("Image"); JMenuItem open = new JMenuItem("Open"); open.addActionListener(new OpenFileActionListener()); file.add(open); JMenuItem original = new JMenuItem("Original"); original.addActionListener(new OriginalActionListener()); image.add(original); JMenuItem invert = new JMenuItem("Invert"); invert.addActionListener(new InvertActionListener()); image.add(invert); JMenuItem sepia = new JMenuItem("Sepia"); sepia.addActionListener(new SepiaActionListener()); image.add(sepia); menuBar.add(file); menuBar.add(image); setJMenuBar(menuBar); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setContentPane(panel); pack(); setVisible(true); } private class OpenFileActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent actionEvent) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new ImageFilter()); int returnVal = chooser.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION){ File file = chooser.getSelectedFile(); try { BufferedImage image = ImageIO.read(file); panel.setImage(image); pack(); } catch (IOException e) { e.printStackTrace(); } } } } private class OriginalActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { panel.setRGBStrategy(new VanillaRGBStrategy()); panel.convert(); } } private class InvertActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { panel.setRGBStrategy(new InvertRGBStrategy()); panel.convert(); } } private class SepiaActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { panel.setRGBStrategy(new SepiaRGBStrategy()); panel.convert(); } } private static class ImageFilter extends FileFilter { public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = Utils.getExtension(f); if (extension != null) { if (extension.equals(Utils.tiff) || extension.equals(Utils.tif) || extension.equals(Utils.gif) || extension.equals(Utils.jpeg) || extension.equals(Utils.jpg) || extension.equals(Utils.png)) { return true; } else { return false; } } return false; } public String getDescription() { return "Just Images"; } } private static class Utils { public final static String jpeg = "jpeg"; public final static String jpg = "jpg"; public final static String gif = "gif"; public final static String tiff = "tiff"; public final static String tif = "tif"; public final static String png = "png"; /* * Get the extension of a file. */ public static String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i+1).toLowerCase(); } return ext; } } }
Add buttons for single channel filters
src/ui/RGBWindow.java
Add buttons for single channel filters
Java
mit
8a9f3acf98ec67a6682a9fbd8ceacde625063497
0
javadev/underscore-java,javadev/underscore-java
/* * The MIT License (MIT) * * Copyright 2015-2018 Valentyn Kolesnikov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.underscore; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.junit.Test; import static java.util.Arrays.asList; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Underscore library unit test. * * @author Valentyn Kolesnikov */ public class FunctionsTest { /* var func = function(greeting){ return greeting + ': ' + this.name }; func = _.bind(func, {name: 'moe'}, 'hi'); func(); => 'hi: moe' */ @Test public void bind() { class GreetingFunction implements Function<String, String> { private final String name; public GreetingFunction(final String name) { this.name = name; } public String apply(final String greeting) { return greeting + ": " + this.name; } } assertEquals("hi: moe", U.bind(new GreetingFunction("moe")).apply("hi")); } /* var subtract = function(a, b) { return b - a; }; sub5 = _.partial(subtract, 5); sub5(20); => 15 */ @Test public void partial() { class SubtractFunction implements Function<Integer, Integer> { private final Integer arg1; public SubtractFunction(final Integer arg1) { this.arg1 = arg1; } public Integer apply(final Integer arg2) { return arg2 - arg1; } } Function<Integer, Integer> sub5 = new SubtractFunction(5); assertEquals(15, sub5.apply(20).intValue()); } /* var fibonacci = _.memoize(function(n) { return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2); }); */ @Test public void memoize() { class FibonacciFuncion1 extends MemoizeFunction<Integer, Integer> { public Integer calc(final Integer n) { return n < 2 ? n : apply(n - 1) + apply(n - 2); } } assertEquals(55, new FibonacciFuncion1().apply(10).intValue()); Function<Integer, Integer> memoizeFunction = U.memoize( new Function<Integer, Integer>() { public Integer apply(final Integer n) { return n < 2 ? n : apply(n - 1) + apply(n - 2); } }); assertEquals(55, memoizeFunction.apply(10).intValue()); } /* var counter = 0; var incr = function(){ counter++; }; var throttleIncr = _.throttle(incr, 32); throttleIncr(); throttleIncr(); _.delay(throttleIncr, 16); _.delay(function(){ equal(counter, 1, 'incr was throttled'); }, 96); */ @Test public void throttle() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { counter[0]++; return null; } }; final Supplier<Void> throttleIncr = U.throttle(incr, 50); throttleIncr.get(); throttleIncr.get(); U.delay(throttleIncr, 16); U.delay(new Supplier<Void>() { public Void get() { assertEquals("incr was throttled", 1, counter[0].intValue()); return null; } }, 60); await().atMost(180, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { throttleIncr.get(); return true; } }); } /* var counter = 0; var incr = function(){ counter++; }; var debouncedIncr = _.debounce(incr, 32); debouncedIncr(); debouncedIncr(); _.delay(debouncedIncr, 16); _.delay(function(){ equal(counter, 1, 'incr was debounced'); }, 96); */ @Test public void debounce() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { counter[0]++; return null; } }; Supplier<Void> debouncedIncr = U.debounce(incr, 50); debouncedIncr.get(); debouncedIncr.get(); U.delay(debouncedIncr, 16); U.delay(new Supplier<Void>() { public Void get() { assertEquals("incr was debounced", 1, counter[0].intValue()); return null; } }, 60); await().atMost(120, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { return true; } }); } /* _.defer(function(){ alert('deferred'); }); // Returns from the function before the alert runs. */ @Test public void defer() throws Exception { final Integer[] counter = new Integer[] {0}; U.defer(new Supplier<Void>() { public Void get() { try { TimeUnit.MILLISECONDS.sleep(16); } catch (Exception e) { e.getMessage(); } counter[0]++; return null; } }); assertEquals("incr was debounced", 0, counter[0].intValue()); await().atLeast(60, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertEquals("incr was debounced", 1, counter[0].intValue()); return true; } }); } /* var initialize = _.once(createApplication); initialize(); initialize(); // Application is only created once. */ @Test public void once() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Integer> incr = new Supplier<Integer>() { public Integer get() { counter[0]++; return counter[0]; } }; final Supplier<Integer> onceIncr = U.once(incr); onceIncr.get(); onceIncr.get(); await().atLeast(60, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertEquals("incr was called only once", 1, counter[0].intValue()); assertEquals("stores a memo to the last value", 1, onceIncr.get().intValue()); return true; } }); } /* var hello = function(name) { return "hello: " + name; }; hello = _.wrap(hello, function(func) { return "before, " + func("moe") + ", after"; }); hello(); => 'before, hello: moe, after' */ @Test public void wrap() { Function<String, String> hello = new Function<String, String>() { public String apply(final String name) { return "hello: " + name; } }; Function<Void, String> result = U.wrap(hello, new Function<Function<String, String>, String>() { public String apply(final Function<String, String> func) { return "before, " + func.apply("moe") + ", after"; } }); assertEquals("before, hello: moe, after", result.apply(null)); } /* var isFalsy = _.negate(Boolean); _.find([-2, -1, 0, 1, 2], isFalsy); => 0 */ @Test public void negate() { Predicate<Integer> isFalsy = U.negate(new Predicate<Integer>() { public boolean test(final Integer item) { return item != 0; } }); Optional<Integer> result = U.find(asList(-2, -1, 0, 1, 2), isFalsy); assertEquals(0, result.get().intValue()); } /* var greet = function(name){ return "hi: " + name; }; var exclaim = function(statement){ return statement.toUpperCase() + "!"; }; var welcome = _.compose(greet, exclaim); welcome('moe'); => 'hi: MOE!' */ @Test @SuppressWarnings("unchecked") public void compose() { Function<String, String> greet = new Function<String, String>() { public String apply(final String name) { return "hi: " + name; } }; Function<String, String> exclaim = new Function<String, String>() { public String apply(final String statement) { return statement.toUpperCase() + "!"; } }; Function<String, String> welcome = U.compose(greet, exclaim); assertEquals("hi: MOE!", welcome.apply("moe")); } /* var renderNotes = _.after(notes.length, render); _.each(notes, function(note) { note.asyncSave({success: renderNotes}); }); // renderNotes is run once, after all notes have saved. */ @Test public void after() { final List<Integer> notes = asList(1, 2, 3); final Supplier<Integer> renderNotes = U.after(notes.size(), new Supplier<Integer>() { public Integer get() { return 4; } }); final List<Integer> result = new ArrayList<Integer>(); U.<Integer>each(notes, new Consumer<Integer>() { public void accept(Integer item) { result.add(item); Integer afterResult = renderNotes.get(); if (afterResult != null) { result.add(afterResult); } } }); assertEquals("[1, 2, 3, 4]", result.toString()); } /* var monthlyMeeting = _.before(3, askForRaise); monthlyMeeting(); monthlyMeeting(); monthlyMeeting(); // the result of any subsequent calls is the same as the second call */ @Test public void before() { final List<Integer> notes = asList(1, 2, 3); final Supplier<Integer> renderNotes = U.before(notes.size() - 1, new Supplier<Integer>() { public Integer get() { return 4; } }); final List<Integer> result = new ArrayList<Integer>(); U.<Integer>each(notes, new Consumer<Integer>() { public void accept(Integer item) { result.add(item); Integer afterResult = renderNotes.get(); if (afterResult != null) { result.add(afterResult); } } }); assertEquals("[1, 4, 2, 4, 3, 4]", result.toString()); } /* var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}]; _.map(stooges, _.iteratee('age')); => [25, 21, 23] */ @Test @SuppressWarnings("unchecked") public void iteratee() { List<Map<String, Object>> stooges = Arrays.<Map<String, Object>>asList( new LinkedHashMap<String, Object>() { { put("name", "curly"); put("age", 25); } }, new LinkedHashMap<String, Object>() { { put("name", "moe"); put("age", 21); } }, new LinkedHashMap<String, Object>() { { put("name", "larry"); put("age", 23); } } ); final List<Object> result = U.map(stooges, U.iteratee("age")); assertEquals("[25, 21, 23]", result.toString()); } @Test public void setTimeout() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { counter[0]++; return null; } }; U.setTimeout(incr, 0); await().atLeast(40, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertEquals(1, counter[0].intValue()); return true; } }); } @Test public void clearTimeout() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { counter[0]++; return null; } }; java.util.concurrent.ScheduledFuture future = U.setTimeout(incr, 20); U.clearTimeout(future); U.clearTimeout(null); await().atLeast(40, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertEquals(0, counter[0].intValue()); return true; } }); } @Test public void setInterval() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { if (counter[0] < 4) { counter[0]++; } return null; } }; U.setInterval(incr, 10); await().atLeast(45, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertTrue("Counter is not in range [0, 4] " + counter[0], asList(0, 4).contains(counter[0])); return true; } }); } @Test public void clearInterval() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { counter[0]++; return null; } }; java.util.concurrent.ScheduledFuture future = U.setInterval(incr, 20); U.clearInterval(future); U.clearInterval(null); await().atLeast(40, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertEquals(0, counter[0].intValue()); return true; } }); } }
src/test/java/com/github/underscore/FunctionsTest.java
/* * The MIT License (MIT) * * Copyright 2015-2018 Valentyn Kolesnikov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.underscore; import static org.awaitility.Awaitility.await; import java.util.concurrent.TimeUnit; import java.util.*; import org.junit.Test; import static java.util.Arrays.asList; import java.util.concurrent.Callable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Underscore library unit test. * * @author Valentyn Kolesnikov */ public class FunctionsTest { /* var func = function(greeting){ return greeting + ': ' + this.name }; func = _.bind(func, {name: 'moe'}, 'hi'); func(); => 'hi: moe' */ @Test public void bind() { class GreetingFunction implements Function<String, String> { private final String name; public GreetingFunction(final String name) { this.name = name; } public String apply(final String greeting) { return greeting + ": " + this.name; } } assertEquals("hi: moe", U.bind(new GreetingFunction("moe")).apply("hi")); } /* var subtract = function(a, b) { return b - a; }; sub5 = _.partial(subtract, 5); sub5(20); => 15 */ @Test public void partial() { class SubtractFunction implements Function<Integer, Integer> { private final Integer arg1; public SubtractFunction(final Integer arg1) { this.arg1 = arg1; } public Integer apply(final Integer arg2) { return arg2 - arg1; } } Function<Integer, Integer> sub5 = new SubtractFunction(5); assertEquals(15, sub5.apply(20).intValue()); } /* var fibonacci = _.memoize(function(n) { return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2); }); */ @Test public void memoize() { class FibonacciFuncion1 extends MemoizeFunction<Integer, Integer> { public Integer calc(final Integer n) { return n < 2 ? n : apply(n - 1) + apply(n - 2); } } assertEquals(55, new FibonacciFuncion1().apply(10).intValue()); Function<Integer, Integer> memoizeFunction = U.memoize( new Function<Integer, Integer>() { public Integer apply(final Integer n) { return n < 2 ? n : apply(n - 1) + apply(n - 2); } }); assertEquals(55, memoizeFunction.apply(10).intValue()); } /* var counter = 0; var incr = function(){ counter++; }; var throttleIncr = _.throttle(incr, 32); throttleIncr(); throttleIncr(); _.delay(throttleIncr, 16); _.delay(function(){ equal(counter, 1, 'incr was throttled'); }, 96); */ @Test public void throttle() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { counter[0]++; return null; } }; final Supplier<Void> throttleIncr = U.throttle(incr, 50); throttleIncr.get(); throttleIncr.get(); U.delay(throttleIncr, 16); U.delay(new Supplier<Void>() { public Void get() { assertEquals("incr was throttled", 1, counter[0].intValue()); return null; } }, 60); await().atMost(180, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { throttleIncr.get(); return true; } }); } /* var counter = 0; var incr = function(){ counter++; }; var debouncedIncr = _.debounce(incr, 32); debouncedIncr(); debouncedIncr(); _.delay(debouncedIncr, 16); _.delay(function(){ equal(counter, 1, 'incr was debounced'); }, 96); */ @Test public void debounce() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { counter[0]++; return null; } }; Supplier<Void> debouncedIncr = U.debounce(incr, 50); debouncedIncr.get(); debouncedIncr.get(); U.delay(debouncedIncr, 16); U.delay(new Supplier<Void>() { public Void get() { assertEquals("incr was debounced", 1, counter[0].intValue()); return null; } }, 60); await().atMost(120, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { return true; } }); } /* _.defer(function(){ alert('deferred'); }); // Returns from the function before the alert runs. */ @Test public void defer() throws Exception { final Integer[] counter = new Integer[] {0}; U.defer(new Supplier<Void>() { public Void get() { try { TimeUnit.MILLISECONDS.sleep(16); } catch (Exception e) { e.getMessage(); } counter[0]++; return null; } }); assertEquals("incr was debounced", 0, counter[0].intValue()); await().atLeast(60, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertEquals("incr was debounced", 1, counter[0].intValue()); return true; } }); } /* var initialize = _.once(createApplication); initialize(); initialize(); // Application is only created once. */ @Test public void once() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Integer> incr = new Supplier<Integer>() { public Integer get() { counter[0]++; return counter[0]; } }; final Supplier<Integer> onceIncr = U.once(incr); onceIncr.get(); onceIncr.get(); await().atLeast(60, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertEquals("incr was called only once", 1, counter[0].intValue()); assertEquals("stores a memo to the last value", 1, onceIncr.get().intValue()); return true; } }); } /* var hello = function(name) { return "hello: " + name; }; hello = _.wrap(hello, function(func) { return "before, " + func("moe") + ", after"; }); hello(); => 'before, hello: moe, after' */ @Test public void wrap() { Function<String, String> hello = new Function<String, String>() { public String apply(final String name) { return "hello: " + name; } }; Function<Void, String> result = U.wrap(hello, new Function<Function<String, String>, String>() { public String apply(final Function<String, String> func) { return "before, " + func.apply("moe") + ", after"; } }); assertEquals("before, hello: moe, after", result.apply(null)); } /* var isFalsy = _.negate(Boolean); _.find([-2, -1, 0, 1, 2], isFalsy); => 0 */ @Test public void negate() { Predicate<Integer> isFalsy = U.negate(new Predicate<Integer>() { public boolean test(final Integer item) { return item != 0; } }); Optional<Integer> result = U.find(asList(-2, -1, 0, 1, 2), isFalsy); assertEquals(0, result.get().intValue()); } /* var greet = function(name){ return "hi: " + name; }; var exclaim = function(statement){ return statement.toUpperCase() + "!"; }; var welcome = _.compose(greet, exclaim); welcome('moe'); => 'hi: MOE!' */ @Test @SuppressWarnings("unchecked") public void compose() { Function<String, String> greet = new Function<String, String>() { public String apply(final String name) { return "hi: " + name; } }; Function<String, String> exclaim = new Function<String, String>() { public String apply(final String statement) { return statement.toUpperCase() + "!"; } }; Function<String, String> welcome = U.compose(greet, exclaim); assertEquals("hi: MOE!", welcome.apply("moe")); } /* var renderNotes = _.after(notes.length, render); _.each(notes, function(note) { note.asyncSave({success: renderNotes}); }); // renderNotes is run once, after all notes have saved. */ @Test public void after() { final List<Integer> notes = asList(1, 2, 3); final Supplier<Integer> renderNotes = U.after(notes.size(), new Supplier<Integer>() { public Integer get() { return 4; } }); final List<Integer> result = new ArrayList<Integer>(); U.<Integer>each(notes, new Consumer<Integer>() { public void accept(Integer item) { result.add(item); Integer afterResult = renderNotes.get(); if (afterResult != null) { result.add(afterResult); } } }); assertEquals("[1, 2, 3, 4]", result.toString()); } /* var monthlyMeeting = _.before(3, askForRaise); monthlyMeeting(); monthlyMeeting(); monthlyMeeting(); // the result of any subsequent calls is the same as the second call */ @Test public void before() { final List<Integer> notes = asList(1, 2, 3); final Supplier<Integer> renderNotes = U.before(notes.size() - 1, new Supplier<Integer>() { public Integer get() { return 4; } }); final List<Integer> result = new ArrayList<Integer>(); U.<Integer>each(notes, new Consumer<Integer>() { public void accept(Integer item) { result.add(item); Integer afterResult = renderNotes.get(); if (afterResult != null) { result.add(afterResult); } } }); assertEquals("[1, 4, 2, 4, 3, 4]", result.toString()); } /* var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}]; _.map(stooges, _.iteratee('age')); => [25, 21, 23] */ @Test @SuppressWarnings("unchecked") public void iteratee() { List<Map<String, Object>> stooges = Arrays.<Map<String, Object>>asList( new LinkedHashMap<String, Object>() { { put("name", "curly"); put("age", 25); } }, new LinkedHashMap<String, Object>() { { put("name", "moe"); put("age", 21); } }, new LinkedHashMap<String, Object>() { { put("name", "larry"); put("age", 23); } } ); final List<Object> result = U.map(stooges, U.iteratee("age")); assertEquals("[25, 21, 23]", result.toString()); } @Test public void setTimeout() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { counter[0]++; return null; } }; U.setTimeout(incr, 0); await().atLeast(40, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertEquals(1, counter[0].intValue()); return true; } }); } @Test public void clearTimeout() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { counter[0]++; return null; } }; java.util.concurrent.ScheduledFuture future = U.setTimeout(incr, 20); U.clearTimeout(future); U.clearTimeout(null); await().atLeast(40, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertEquals(0, counter[0].intValue()); return true; } }); } @Test public void setInterval() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { if (counter[0] < 4) { counter[0]++; } return null; } }; U.setInterval(incr, 10); await().atLeast(45, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertTrue("Counter is not in range [0, 4] " + counter[0], asList(0, 4).contains(counter[0])); return true; } }); } @Test public void clearInterval() throws Exception { final Integer[] counter = new Integer[] {0}; Supplier<Void> incr = new Supplier<Void>() { public Void get() { counter[0]++; return null; } }; java.util.concurrent.ScheduledFuture future = U.setInterval(incr, 20); U.clearInterval(future); U.clearInterval(null); await().atLeast(40, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { assertEquals(0, counter[0].intValue()); return true; } }); } }
Fix unit test improts.
src/test/java/com/github/underscore/FunctionsTest.java
Fix unit test improts.
Java
mit
7300a85bb29bdc7408bc0c68663411744934d29c
0
pballart/Memorize4me
package com.best.memorize4me.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.best.memorize4me.db.table.SearchItemPhoto; import com.best.memorize4me.db.table.Category; import com.best.memorize4me.db.table.SearchItem; import static com.best.memorize4me.db.table.Category.*; import static com.best.memorize4me.db.table.SearchItem.*; import static com.best.memorize4me.db.table.SearchItemPhoto.*; public class DbHelper extends SQLiteOpenHelper{ public static final int DATABASE_VERSION = 4; private static final String TEXT_TYPE = " TEXT"; private static final String COMMA_SEP = ","; private static final String INTEGER_TYPE = " INTEGER"; private static final String DATE_TYPE = " DATE"; private static final String SQL_CREATE_CATEGORIES = "CREATE TABLE " + CategoryEntry.TABLE_NAME + " (" + CategoryEntry.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + CategoryEntry.COLUMN_TITLE + TEXT_TYPE + COMMA_SEP + CategoryEntry.COLUMN_DATE + INTEGER_TYPE + " )" ; private static final String SQL_CREATE_SEARCH_ITEMS = "CREATE TABLE " + SearchItemEntry.TABLE_NAME + " (" + SearchItemEntry.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SearchItemEntry.COLUMN_CATEGORY_ID + INTEGER_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_TITLE + TEXT_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_DATE + DATE_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_PRICE + INTEGER_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_RATE + INTEGER_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_NAME + TEXT_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_EMAIL + TEXT_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_PHONE_NUMBER + TEXT_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_DESCRIPTION + TEXT_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_LOCATION + TEXT_TYPE + " )" ; private static final String SQL_CREATE_SEARCH_ITEM_PHOTOS = "CREATE TABLE " + SearchItemPhotoEntry.TABLE_NAME + " (" + SearchItemPhotoEntry.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SearchItemPhotoEntry.COLUMN_TITLE + TEXT_TYPE + COMMA_SEP + SearchItemPhotoEntry.COLUMN_URL + TEXT_TYPE + COMMA_SEP + SearchItemPhotoEntry.COLUMN_SEARCH_ITEM_ID + INTEGER_TYPE + " )" ; private static final String SQL_DELETE_CATEGORIES = "DROP TABLE IF EXISTS " + Category.CategoryEntry.TABLE_NAME; private static final String SQL_DELETE_SEARCH_ITEMS = "DROP TABLE IF EXISTS " + SearchItem.SearchItemEntry.TABLE_NAME; private static final String SQL_DELETE_SEARCH_ITEM_PHOTOS = "DROP TABLE IF EXISTS " + SearchItemPhotoEntry.TABLE_NAME; public DbHelper(Context context) { super(context, "MemorizeForMe.db", null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_CATEGORIES); db.execSQL(SQL_CREATE_SEARCH_ITEMS); db.execSQL(SQL_CREATE_SEARCH_ITEM_PHOTOS); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DELETE_SEARCH_ITEM_PHOTOS); db.execSQL(SQL_DELETE_SEARCH_ITEMS); db.execSQL(SQL_DELETE_CATEGORIES); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } }
app/src/main/java/com/best/memorize4me/db/DbHelper.java
package com.best.memorize4me.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.best.memorize4me.db.table.SearchItemPhoto; import com.best.memorize4me.db.table.Category; import com.best.memorize4me.db.table.SearchItem; import static com.best.memorize4me.db.table.Category.*; import static com.best.memorize4me.db.table.SearchItem.*; import static com.best.memorize4me.db.table.SearchItemPhoto.*; public class DbHelper extends SQLiteOpenHelper{ public static final int DATABASE_VERSION = 3; private static final String TEXT_TYPE = " TEXT"; private static final String COMMA_SEP = ","; private static final String INTEGER_TYPE = " INTEGER"; private static final String DATE_TYPE = " DATE"; private static final String SQL_CREATE_CATEGORIES = "CREATE TABLE " + CategoryEntry.TABLE_NAME + " (" + CategoryEntry.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + CategoryEntry.COLUMN_TITLE + TEXT_TYPE + COMMA_SEP + CategoryEntry.COLUMN_DATE + INTEGER_TYPE + " )" ; private static final String SQL_CREATE_SEARCH_ITEMS = "CREATE TABLE " + SearchItemEntry.TABLE_NAME + " (" + SearchItemEntry.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SearchItemEntry.COLUMN_CATEGORY_ID + INTEGER_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_TITLE + TEXT_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_DATE + DATE_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_PRICE + INTEGER_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_RATE + INTEGER_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_NAME + TEXT_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_EMAIL + TEXT_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_PHONE_NUMBER + TEXT_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_DESCRIPTION + TEXT_TYPE + COMMA_SEP + SearchItemEntry.COLUMN_LOCATION + TEXT_TYPE + " )" ; private static final String SQL_CREATE_SEARCH_ITEM_PHOTOS = "CREATE TABLE " + SearchItemPhotoEntry.TABLE_NAME + " (" + SearchItemPhotoEntry.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SearchItemPhotoEntry.COLUMN_TITLE + TEXT_TYPE + COMMA_SEP + SearchItemPhotoEntry.COLUMN_URL + TEXT_TYPE + COMMA_SEP + SearchItemPhotoEntry.COLUMN_SEARCH_ITEM_ID + INTEGER_TYPE + " )" ; private static final String SQL_DELETE_CATEGORIES = "DROP TABLE IF EXISTS " + Category.CategoryEntry.TABLE_NAME; private static final String SQL_DELETE_SEARCH_ITEMS = "DROP TABLE IF EXISTS " + SearchItem.SearchItemEntry.TABLE_NAME; private static final String SQL_DELETE_SEARCH_ITEM_PHOTOS = "DROP TABLE IF EXISTS " + SearchItemPhotoEntry.TABLE_NAME; public DbHelper(Context context) { super(context, "MemorizeForMe.db", null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_CATEGORIES); db.execSQL(SQL_CREATE_SEARCH_ITEMS); db.execSQL(SQL_CREATE_SEARCH_ITEM_PHOTOS); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DELETE_SEARCH_ITEM_PHOTOS); db.execSQL(SQL_DELETE_SEARCH_ITEMS); db.execSQL(SQL_DELETE_CATEGORIES); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } }
Database fix
app/src/main/java/com/best/memorize4me/db/DbHelper.java
Database fix
Java
mit
30ec6cac78d9d8875e959c4aa6771cb9c631053e
0
denkers/graphi
//========================================= // Kyle Russell // AUT University 2015 // https://github.com/denkers/graphi //========================================= package com.graphi.display; import cern.colt.matrix.impl.SparseDoubleMatrix2D; import static com.graphi.display.Window.HEIGHT; import static com.graphi.display.Window.WIDTH; import com.graphi.io.Storage; import com.graphi.util.Edge; import com.graphi.sim.Network; import com.graphi.util.EdgeFactory; import com.graphi.util.EdgeLabelTransformer; import com.graphi.util.GraphUtilities; import com.graphi.util.MatrixTools; import com.graphi.util.Node; import com.graphi.util.NodeFactory; import com.graphi.util.ObjectFillTransformer; import com.graphi.util.VertexLabelTransformer; import com.graphi.util.WeightTransformer; import edu.uci.ics.jung.algorithms.layout.AggregateLayout; import edu.uci.ics.jung.algorithms.layout.FRLayout; import edu.uci.ics.jung.algorithms.matrix.GraphMatrixOperations; import edu.uci.ics.jung.algorithms.scoring.BetweennessCentrality; import edu.uci.ics.jung.algorithms.scoring.ClosenessCentrality; import edu.uci.ics.jung.algorithms.scoring.EigenvectorCentrality; import edu.uci.ics.jung.algorithms.scoring.PageRank; import edu.uci.ics.jung.algorithms.scoring.VertexScorer; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.SparseMultigraph; import edu.uci.ics.jung.graph.util.EdgeType; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.CrossoverScalingControl; import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse; import edu.uci.ics.jung.visualization.control.GraphMouseListener; import edu.uci.ics.jung.visualization.control.ModalGraphMouse; import edu.uci.ics.jung.visualization.control.ScalingControl; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.util.List; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.geom.Ellipse2D; import java.io.File; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; import net.miginfocom.swing.MigLayout; import org.apache.commons.collections15.Transformer; public class LayoutPanel extends JPanel { private final ControlPanel controlPanel; private final ScreenPanel screenPanel; private final JSplitPane splitPane; private final JScrollPane controlScroll; public static final Color TRANSPARENT = new Color(255, 255, 255, 0); public static final Color PRESET_BG = new Color(200, 200, 200); private Graph<Node, Edge> currentGraph; private final Map<Integer, Node> currentNodes; private final Map<Integer, Edge> currentEdges; private NodeFactory nodeFactory; private EdgeFactory edgeFactory; private Object[] selectedItems; private MainMenu menu; private JFrame frame; public LayoutPanel(MainMenu menu, JFrame frame) { //setPreferredSize(new Dimension(950, 650)); setPreferredSize(new Dimension((int)(Window.WIDTH * 0.7), (int) (Window.HEIGHT * 0.85))); setLayout(new BorderLayout()); this.menu = menu; this.frame = frame; nodeFactory = new NodeFactory(); edgeFactory = new EdgeFactory(); currentGraph = new SparseMultigraph<>(); currentNodes = new HashMap<>(); currentEdges = new HashMap<>(); controlPanel = new ControlPanel(); screenPanel = new ScreenPanel(); splitPane = new JSplitPane(); controlScroll = new JScrollPane(controlPanel); controlScroll.setBorder(null); splitPane.setLeftComponent(screenPanel); splitPane.setRightComponent(controlScroll); splitPane.setResizeWeight(0.7); add(splitPane, BorderLayout.CENTER); } private void sendToOutput(String output) { SimpleDateFormat sdf = new SimpleDateFormat("K:MM a dd.MM.yy"); String date = sdf.format(new Date()); String prefix = "\n[" + date + "] "; JTextArea outputArea = screenPanel.outputPanel.outputArea; SwingUtilities.invokeLater(()-> { outputArea.setText(outputArea.getText() + prefix + output); }); } private File getFile(boolean open, String desc, String...extensions) { JFileChooser jfc = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter(desc, extensions); jfc.setFileFilter(filter); if(open) jfc.showOpenDialog(null); else jfc.showSaveDialog(null); return jfc.getSelectedFile(); } public static JPanel wrapComponents(Border border, Component... components) { JPanel panel = new JPanel(); panel.setBorder(border); for(Component component : components) panel.add(component); return panel; } //-------------------------------------- // CONTROL PANEL //-------------------------------------- private class ControlPanel extends JPanel implements ActionListener { private final String BA_PANEL_CARD = "ba_panel"; private final String KL_PANEL_CARD = "kl_panel"; private final String CLUSTER_PANEL_CARD = "cluster_panel"; private final String SPATH_PANEL_CARD = "spath_panel"; private final String CENTRALITY_PANEL_CARD = "centrality_panel"; private JPanel dataControlPanel, outputControlPanel, displayControlPanel; private JPanel modePanel; private JPanel simPanel; private JRadioButton editCheck, selectCheck, moveCheck; private ButtonGroup modeGroup; private JComboBox genAlgorithmsBox; private JButton resetGeneratorBtn, executeGeneratorBtn; private JPanel genPanel, baGenPanel, klGenPanel; private JSpinner latticeSpinner, clusteringSpinner; private JSpinner initialNSpinner, addNSpinner; private IOPanel ioPanel; private JPanel editPanel; private JLabel selectedLabel; private JButton gObjAddBtn, gObjEditBtn, gObjRemoveBtn; private JPanel computePanel; private JPanel computeInnerPanel; private JPanel clusterPanel, spathPanel; private JSpinner clusterEdgeRemoveSpinner; private JCheckBox clusterTransformCheck; private JComboBox computeBox; private JTextField spathFromField, spathToField; private JButton computeBtn; private JPanel centralityPanel; private JComboBox centralityTypeBox; private ButtonGroup centralityOptions; private JCheckBox centralityMorphCheck; private ButtonGroup editObjGroup; private JRadioButton editVertexRadio, editEdgeRadio; private JPanel viewerPanel; private JCheckBox viewerVLabelsCheck; private JCheckBox viewerELabelsCheck; private JButton viewerBGBtn, vertexBGBtn, edgeBGBtn; public ControlPanel() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBorder(BorderFactory.createEmptyBorder(15, 0, 3, 8)); setPreferredSize(new Dimension(230, 1200)); ioPanel = new IOPanel(); modePanel = new JPanel(); simPanel = new JPanel(new MigLayout("fillx")); modePanel.setPreferredSize(new Dimension(230, 65)); modePanel.setBorder(BorderFactory.createTitledBorder("Mode controls")); simPanel.setBorder(BorderFactory.createTitledBorder("Simulation controls")); modeGroup = new ButtonGroup(); editCheck = new JRadioButton("Edit"); selectCheck = new JRadioButton("Select"); moveCheck = new JRadioButton("Move"); editCheck.addActionListener(this); selectCheck.addActionListener(this); moveCheck.addActionListener(this); modeGroup.add(editCheck); modeGroup.add(selectCheck); modeGroup.add(moveCheck); modePanel.add(editCheck); modePanel.add(selectCheck); modePanel.add(moveCheck); selectCheck.setSelected(true); genAlgorithmsBox = new JComboBox(); genAlgorithmsBox.addItem("Kleinberg"); genAlgorithmsBox.addItem("Barabasi-Albert"); genAlgorithmsBox.addActionListener(this); resetGeneratorBtn = new JButton("Reset"); executeGeneratorBtn = new JButton("Generate"); executeGeneratorBtn.addActionListener(this); resetGeneratorBtn.addActionListener(this); resetGeneratorBtn.setBackground(Color.WHITE); executeGeneratorBtn.setBackground(Color.WHITE); genPanel = new JPanel(new CardLayout()); baGenPanel = new JPanel(new MigLayout()); klGenPanel = new JPanel(new MigLayout()); genPanel.add(klGenPanel, KL_PANEL_CARD); genPanel.add(baGenPanel, BA_PANEL_CARD); genPanel.setBackground(TRANSPARENT); baGenPanel.setBackground(TRANSPARENT); klGenPanel.setBackground(TRANSPARENT); latticeSpinner = new JSpinner(new SpinnerNumberModel(15, 0, 100, 1)); clusteringSpinner = new JSpinner(new SpinnerNumberModel(2, 0, 10, 1)); latticeSpinner.setPreferredSize(new Dimension(50, 20)); clusteringSpinner.setPreferredSize(new Dimension(50, 20)); latticeSpinner.setOpaque(true); clusteringSpinner.setOpaque(true); initialNSpinner = new JSpinner(new SpinnerNumberModel(2, 0, 1000, 1)); addNSpinner = new JSpinner(new SpinnerNumberModel(100, 0, 1000, 1)); initialNSpinner.setOpaque(true); addNSpinner.setOpaque(true); baGenPanel.add(new JLabel("Initial nodes")); baGenPanel.add(initialNSpinner, "wrap"); baGenPanel.add(new JLabel("Generated nodes")); baGenPanel.add(addNSpinner); klGenPanel.add(new JLabel("Lattice size")); klGenPanel.add(latticeSpinner, "wrap"); klGenPanel.add(new JLabel("Clustering exp.")); klGenPanel.add(clusteringSpinner); simPanel.add(new JLabel("Generator"), "al right"); simPanel.add(genAlgorithmsBox, "wrap"); simPanel.add(genPanel, "wrap, span 2, al center"); simPanel.add(resetGeneratorBtn, "al right"); simPanel.add(executeGeneratorBtn, ""); //simPanel.add(simMigPanel); JPanel simWrapperPanel = new JPanel(new BorderLayout()); simWrapperPanel.add(simPanel); editPanel = new JPanel(new GridLayout(3, 1)); editPanel.setBorder(BorderFactory.createTitledBorder("Graph object Controls")); editPanel.setBackground(TRANSPARENT); editObjGroup = new ButtonGroup(); editVertexRadio = new JRadioButton("Vertex"); editEdgeRadio = new JRadioButton("Edge"); gObjAddBtn = new JButton("Add"); gObjEditBtn = new JButton("Edit"); gObjRemoveBtn = new JButton("Delete"); selectedLabel = new JLabel("None"); gObjAddBtn.setBackground(Color.WHITE); gObjEditBtn.setBackground(Color.WHITE); gObjRemoveBtn.setBackground(Color.WHITE); selectedLabel.setFont(new Font("Arial", Font.BOLD, 12)); gObjAddBtn.addActionListener(this); gObjEditBtn.addActionListener(this); gObjRemoveBtn.addActionListener(this); editObjGroup.add(editVertexRadio); editObjGroup.add(editEdgeRadio); editVertexRadio.setSelected(true); JPanel selectedPanel = wrapComponents(null, new JLabel("Selected: "), selectedLabel); JPanel editObjPanel = wrapComponents(null, editVertexRadio, editEdgeRadio); JPanel gObjOptsPanel = wrapComponents(null, gObjAddBtn, gObjEditBtn, gObjRemoveBtn); selectedPanel.setBackground(PRESET_BG); gObjOptsPanel.setBackground(PRESET_BG); editObjPanel.setBackground(PRESET_BG); editPanel.add(selectedPanel); editPanel.add(editObjPanel); editPanel.add(gObjOptsPanel); computePanel = new JPanel(new MigLayout("fillx")); computeInnerPanel = new JPanel(new CardLayout()); clusterPanel = new JPanel(); centralityPanel = new JPanel(new MigLayout()); spathPanel = new JPanel(); computeBox = new JComboBox(); computeBtn = new JButton("Execute"); computePanel.setPreferredSize(new Dimension(230, 180)); computePanel.setBorder(BorderFactory.createTitledBorder("Computation controls")); spathPanel.setLayout(new BoxLayout(spathPanel, BoxLayout.Y_AXIS)); spathPanel.setBackground(TRANSPARENT); computeBtn.setBackground(Color.WHITE); computeBtn.addActionListener(this); computeBox.addItem("Clusters"); computeBox.addItem("Centrality"); computeBox.addActionListener(this); clusterEdgeRemoveSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 100, 1)); clusterTransformCheck = new JCheckBox("Transform graph"); clusterEdgeRemoveSpinner.setPreferredSize(new Dimension(50, 20)); JPanel clusterEdgesPanel = wrapComponents(null, new JLabel("Delete edges"), clusterEdgeRemoveSpinner); clusterPanel.setLayout(new MigLayout()); clusterPanel.add(clusterEdgesPanel, "wrap"); clusterPanel.add(clusterTransformCheck); clusterEdgesPanel.setBackground(PRESET_BG); clusterPanel.setBackground(PRESET_BG); spathFromField = new JTextField(); spathToField = new JTextField(); spathFromField.setPreferredSize(new Dimension(50, 20)); spathToField.setPreferredSize(new Dimension(50, 20)); JLabel tLabel = new JLabel("To ID"); JPanel spathFromPanel = wrapComponents(null, new JLabel("From ID"), spathFromField); JPanel spathToPanel = wrapComponents(null, tLabel, spathToField); JPanel spathWrapper = new JPanel(new MigLayout()); spathWrapper.add(spathFromPanel, "wrap"); spathWrapper.add(spathToPanel); spathWrapper.setBackground(TRANSPARENT); spathFromPanel.setBackground(TRANSPARENT); spathToPanel.setBackground(TRANSPARENT); spathPanel.add(spathWrapper); centralityTypeBox = new JComboBox(); centralityOptions = new ButtonGroup(); centralityMorphCheck = new JCheckBox("Transform graph"); centralityTypeBox.addItem("Eigenvector"); centralityTypeBox.addItem("PageRank"); centralityTypeBox.addItem("Closeness"); centralityTypeBox.addItem("Betweenness"); centralityTypeBox.addActionListener(this); JPanel cenTypePanel = wrapComponents(null, new JLabel("Type"), centralityTypeBox); centralityPanel.add(cenTypePanel, "wrap"); centralityPanel.add(centralityMorphCheck); cenTypePanel.setBackground(PRESET_BG); centralityPanel.setBackground(PRESET_BG); computeInnerPanel.add(clusterPanel, CLUSTER_PANEL_CARD); computeInnerPanel.add(spathPanel, SPATH_PANEL_CARD); computeInnerPanel.add(centralityPanel, CENTRALITY_PANEL_CARD); computePanel.add(new JLabel("Compute "), "al right"); computePanel.add(computeBox, "wrap"); computePanel.add(computeInnerPanel, "wrap, span 2, al center"); computePanel.add(computeBtn, "span 2, al center"); JPanel computeWrapperPanel = new JPanel(new BorderLayout()); computeWrapperPanel.add(computePanel); CardLayout clusterInnerLayout = (CardLayout) computeInnerPanel.getLayout(); clusterInnerLayout.show(computeInnerPanel, CLUSTER_PANEL_CARD); viewerPanel = new JPanel(); JPanel innerViewerPanel = new JPanel(new MigLayout()); viewerVLabelsCheck = new JCheckBox("Vertex labels"); viewerELabelsCheck = new JCheckBox("Edge labels"); viewerBGBtn = new JButton("Choose"); vertexBGBtn = new JButton("Choose"); edgeBGBtn = new JButton("Choose"); viewerBGBtn.addActionListener(this); vertexBGBtn.addActionListener(this); edgeBGBtn.addActionListener(this); viewerVLabelsCheck.addActionListener(this); viewerELabelsCheck.addActionListener(this); viewerPanel.setBorder(BorderFactory.createTitledBorder("Viewer controls")); viewerPanel.setPreferredSize(new Dimension(500, 200)); innerViewerPanel.setBackground(PRESET_BG); innerViewerPanel.add(viewerVLabelsCheck, "wrap, span 2"); innerViewerPanel.add(viewerELabelsCheck, "wrap, span 2"); innerViewerPanel.add(new JLabel("Vertex background")); innerViewerPanel.add(vertexBGBtn, "wrap"); innerViewerPanel.add(new JLabel("Edge background")); innerViewerPanel.add(edgeBGBtn, "wrap"); innerViewerPanel.add(new JLabel("Viewer background")); innerViewerPanel.add(viewerBGBtn, "wrap"); viewerPanel.add(innerViewerPanel); menu.exitItem.addActionListener(this); menu.miniItem.addActionListener(this); menu.maxItem.addActionListener(this); menu.importGraphItem.addActionListener(this); menu.exportGraphItem.addActionListener(this); menu.importLogItem.addActionListener(this); menu.exportLogItem.addActionListener(this); menu.vLabelsItem.addActionListener(this); menu.eLabelsItem.addActionListener(this); menu.viewerBGItem.addActionListener(this); menu.edgeBGItem.addActionListener(this); menu.vertexBGItem.addActionListener(this); menu.clearLogItem.addActionListener(this); menu.resetGraphItem.addActionListener(this); menu.addVertexItem.addActionListener(this); menu.editVertexItem.addActionListener(this); menu.removeVertexItem.addActionListener(this); menu.addEdgeItem.addActionListener(this); menu.editEdgeItem.addActionListener(this); menu.removeEdgeItem.addActionListener(this); menu.aboutItem.addActionListener(this); add(modePanel); add(Box.createRigidArea(new Dimension(230, 30))); add(simWrapperPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(ioPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(editPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(computeWrapperPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(viewerPanel); } private void updateSelectedComponents() { if(selectedItems == null || selectedItems.length == 0) selectedLabel.setText("None"); else { if(selectedItems.length > 1) selectedLabel.setText(selectedItems.length + " objects"); else { Object selectedObj = selectedItems[0]; if(selectedObj instanceof Node) selectedLabel.setText("Node (ID=" + ((Node) selectedObj).getID() + ")"); else if(selectedObj instanceof Edge) selectedLabel.setText("Edge (ID=" + ((Edge) selectedObj).getID() + ")"); } } } private void computeExecute() { int selectedIndex = computeBox.getSelectedIndex(); switch(selectedIndex) { case 0: screenPanel.graphPanel.showCluster(); case 1: screenPanel.graphPanel.showCentrality(); } } private void showGeneratorSim() { int genIndex = genAlgorithmsBox.getSelectedIndex(); nodeFactory.setLastID(0); edgeFactory.setLastID(0); switch(genIndex) { case 0: showKleinbergSim(); break; case 1: showBASim(); break; } screenPanel.graphPanel.reloadGraph(); } private void showAbout() { JLabel nameLabel = new JLabel("Kyle Russell 2015", SwingConstants.CENTER); JLabel locLabel = new JLabel("AUT University"); JLabel repoLabel = new JLabel("https://github.com/denkers/graphi"); JPanel aboutPanel = new JPanel(); aboutPanel.setLayout(new BoxLayout(aboutPanel, BoxLayout.Y_AXIS)); aboutPanel.add(nameLabel); aboutPanel.add(locLabel); aboutPanel.add(repoLabel); JOptionPane.showMessageDialog(null, aboutPanel, "Graphi - Author", JOptionPane.INFORMATION_MESSAGE); } private void resetSim() { currentGraph = new SparseMultigraph(); screenPanel.graphPanel.reloadGraph(); } private void showKleinbergSim() { int latticeSize = (int) latticeSpinner.getValue(); int clusterExp = (int) clusteringSpinner.getValue(); currentGraph = Network.generateKleinberg(latticeSize, clusterExp, new NodeFactory(), new EdgeFactory()); } private void showBASim() { int m = (int) initialNSpinner.getValue(); int n = (int) addNSpinner.getValue(); currentGraph = Network.generateBerbasiAlbert(new NodeFactory(), new EdgeFactory(), n, m); } private void showVertexBGChange() { Color selectedColour = JColorChooser.showDialog(null, "Choose vertex colour", Color.BLACK); if(selectedColour != null) screenPanel.graphPanel.setVertexColour(selectedColour, null); } private void showEdgeBGChange() { Color selectedColour = JColorChooser.showDialog(null, "Choose edge colour", Color.BLACK); if(selectedColour != null) screenPanel.graphPanel.setEdgeColour(selectedColour, null); } private void showViewerBGChange() { Color selectedColour = JColorChooser.showDialog(null, "Choose viewer background colour", Color.WHITE); if(selectedColour != null) screenPanel.graphPanel.gViewer.setBackground(selectedColour); } //-------------------------------------- // IO PANEL //-------------------------------------- private class IOPanel extends JPanel implements ActionListener { private JButton exportBtn, importBtn; private JLabel currentStorageLabel; private ButtonGroup storageGroup; private JRadioButton storageGraphRadio, storageLogRadio; public IOPanel() { setLayout(new GridLayout(3, 1)); setBorder(BorderFactory.createTitledBorder("I/O Controls")); currentStorageLabel = new JLabel("None"); importBtn = new JButton("Import"); exportBtn = new JButton("Export"); storageGroup = new ButtonGroup(); storageGraphRadio = new JRadioButton("Graph"); storageLogRadio = new JRadioButton("Log"); storageGroup.add(storageGraphRadio); storageGroup.add(storageLogRadio); importBtn.addActionListener(this); exportBtn.addActionListener(this); storageGraphRadio.addActionListener(this); storageLogRadio.addActionListener(this); importBtn.setBackground(Color.WHITE); exportBtn.setBackground(Color.WHITE); storageGraphRadio.setSelected(true); JPanel storageBtnWrapper = wrapComponents(null, importBtn, exportBtn); JPanel currentGraphWrapper = wrapComponents(null, new JLabel("Active: "), currentStorageLabel); JPanel storageOptsWrapper = wrapComponents(null, storageGraphRadio, storageLogRadio); storageBtnWrapper.setBackground(PRESET_BG); currentGraphWrapper.setBackground(PRESET_BG); storageOptsWrapper.setBackground(PRESET_BG); add(currentGraphWrapper); add(storageOptsWrapper); add(storageBtnWrapper); currentStorageLabel.setFont(new Font("Arial", Font.BOLD, 12)); } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == importBtn) { if(storageGraphRadio.isSelected()) importGraph(); else importLog(); } else if(src == exportBtn) { if(storageGraphRadio.isSelected()) exportGraph(); else exportLog(); } } } private void showCurrentComputePanel() { int selectedIndex = computeBox.getSelectedIndex(); String card; switch(selectedIndex) { case 0: card = CLUSTER_PANEL_CARD; break; case 1: card = CENTRALITY_PANEL_CARD; break; case 2: card = SPATH_PANEL_CARD; break; default: return; } CardLayout clusterInnerLayout = (CardLayout) computeInnerPanel.getLayout(); clusterInnerLayout.show(computeInnerPanel, card); } private void showSimPanel() { int selectedIndex = genAlgorithmsBox.getSelectedIndex(); String card; switch(selectedIndex) { case 0: card = KL_PANEL_CARD; break; case 1: card = BA_PANEL_CARD; break; default: return; } CardLayout gLayout = (CardLayout) genPanel.getLayout(); gLayout.show(genPanel, card); } private void exportGraph() { File file = getFile(false, "Graphi .graph file", "graph"); if(file != null && currentGraph != null) Storage.saveGraph(currentGraph, file); } private void importGraph() { File file = getFile(true, "Graphi .graph file", "graph"); if(file != null) { nodeFactory.setLastID(0); edgeFactory.setLastID(0); currentGraph = Storage.openGraph(file); ioPanel.currentStorageLabel.setText(file.getName()); initCurrentNodes(); initCurrentEdges(); screenPanel.graphPanel.gLayout.setGraph(currentGraph); screenPanel.graphPanel.gViewer.repaint(); screenPanel.dataPanel.loadNodes(currentGraph); screenPanel.dataPanel.loadEdges(currentGraph); } } private void initCurrentNodes() { if(currentGraph == null) return; currentNodes.clear(); Collection<Node> nodes = currentGraph.getVertices(); for(Node node : nodes) currentNodes.put(node.getID(), node); } private void initCurrentEdges() { if(currentGraph == null) return; currentEdges.clear(); Collection<Edge> edges = currentGraph.getEdges(); for(Edge edge : edges) currentEdges.put(edge.getID(), edge); } private void exportLog() { File file = getFile(false, "Graphi .log file", "log"); if(file != null) Storage.saveOutputLog(screenPanel.outputPanel.outputArea.getText(), file); } private void importLog() { File file = getFile(true, "Graphi .log file", "log"); if(file != null) { ioPanel.currentStorageLabel.setText(file.getName()); screenPanel.outputPanel.outputArea.setText(Storage.openOutputLog(file)); } } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == computeBox) showCurrentComputePanel(); else if(src == gObjAddBtn) { if(editVertexRadio.isSelected()) screenPanel.dataPanel.addVertex(); else screenPanel.dataPanel.addEdge(); } else if(src == gObjEditBtn) { if(editVertexRadio.isSelected()) screenPanel.dataPanel.editVertex(); else screenPanel.dataPanel.editEdge(); } else if(src == gObjRemoveBtn) { if(editVertexRadio.isSelected()) screenPanel.dataPanel.removeVertex(); else screenPanel.dataPanel.removeEdge(); } else if(src == editCheck) { screenPanel.graphPanel.mouse.setMode(ModalGraphMouse.Mode.EDITING); screenPanel.graphPanel.mouse.remove(screenPanel.graphPanel.mouse.getPopupEditingPlugin()); } else if(src == moveCheck) screenPanel.graphPanel.mouse.setMode(ModalGraphMouse.Mode.TRANSFORMING); else if(src == selectCheck) screenPanel.graphPanel.mouse.setMode(ModalGraphMouse.Mode.PICKING); else if(src == executeGeneratorBtn) showGeneratorSim(); else if(src == resetGeneratorBtn) resetSim(); else if(src == computeBtn) computeExecute(); else if(src == genAlgorithmsBox) showSimPanel(); else if(src == vertexBGBtn) showVertexBGChange(); else if(src == edgeBGBtn) showEdgeBGChange(); else if(src == viewerBGBtn) showViewerBGChange(); else if(src == viewerVLabelsCheck) screenPanel.graphPanel.showVertexLabels(viewerVLabelsCheck.isSelected()); else if(src == viewerELabelsCheck) screenPanel.graphPanel.showEdgeLabels(viewerELabelsCheck.isSelected()); else if(src == menu.aboutItem) showAbout(); else if(src == menu.exitItem) System.exit(0); else if(src == menu.miniItem) frame.setState(JFrame.ICONIFIED); else if(src == menu.maxItem) frame.setExtendedState(JFrame.MAXIMIZED_BOTH); else if(src == menu.importGraphItem) importGraph(); else if(src == menu.exportGraphItem) exportGraph(); else if(src == menu.importLogItem) importLog(); else if(src == menu.exportLogItem) exportLog(); else if(src == menu.vLabelsItem) screenPanel.graphPanel.showVertexLabels(true); else if(src == menu.eLabelsItem) screenPanel.graphPanel.showEdgeLabels(true); else if(src == menu.viewerBGItem) showViewerBGChange(); else if(src == menu.edgeBGItem) showEdgeBGChange(); else if(src == menu.vertexBGItem) showVertexBGChange(); else if(src == menu.clearLogItem) screenPanel.outputPanel.clearLog(); else if(src == menu.resetGraphItem) screenPanel.graphPanel.resetGraph(); else if(src == menu.addVertexItem) screenPanel.dataPanel.addVertex(); else if(src == menu.editVertexItem) screenPanel.dataPanel.editVertex(); else if(src == menu.removeVertexItem) screenPanel.dataPanel.removeVertex(); else if(src == menu.addEdgeItem) screenPanel.dataPanel.addEdge(); else if(src == menu.editEdgeItem) screenPanel.dataPanel.editEdge(); else if(src == menu.removeEdgeItem) screenPanel.dataPanel.removeEdge(); } } //-------------------------------------- // SCREEN PANEL //-------------------------------------- private class ScreenPanel extends JPanel { private final DataPanel dataPanel; private final GraphPanel graphPanel; private final OutputPanel outputPanel; private final JTabbedPane tabPane; public ScreenPanel() { setLayout(new BorderLayout()); setBorder(BorderFactory.createEmptyBorder(15, 5, 5, 5)); tabPane = new JTabbedPane(); dataPanel = new DataPanel(); graphPanel = new GraphPanel(); outputPanel = new OutputPanel(); tabPane.addTab("Display", graphPanel); tabPane.addTab("Data", dataPanel); tabPane.addTab("Output", outputPanel); add(tabPane); } private class DataPanel extends JPanel { private final JTable vertexTable, edgeTable; private final DefaultTableModel vertexDataModel, edgeDataModel; private final JTabbedPane dataTabPane; private final JScrollPane vertexScroller, edgeScroller; public DataPanel() { setLayout(new BorderLayout()); dataTabPane = new JTabbedPane(); vertexDataModel = new DefaultTableModel(); vertexTable = new JTable(vertexDataModel) { @Override public boolean isCellEditable(int row, int col) { return false; }; }; edgeDataModel = new DefaultTableModel(); edgeTable = new JTable(edgeDataModel) { @Override public boolean isCellEditable(int row, int col) { return false; } }; vertexScroller = new JScrollPane(vertexTable); edgeScroller = new JScrollPane(edgeTable); vertexTable.setPreferredScrollableViewportSize(new Dimension(630, 500)); vertexDataModel.addColumn("ID"); vertexDataModel.addColumn("Name"); edgeDataModel.addColumn("ID"); edgeDataModel.addColumn("FromVertex"); edgeDataModel.addColumn("ToVertex"); edgeDataModel.addColumn("Weight"); edgeDataModel.addColumn("EdgeType"); dataTabPane.addTab("Vertex table", vertexScroller); dataTabPane.addTab("Edge table", edgeScroller); add(dataTabPane); } private void loadNodes(Graph graph) { ArrayList<Node> vertices = new ArrayList<>(graph.getVertices()); Collections.sort(vertices, (Node n1, Node n2) -> Integer.compare(n1.getID(), n2.getID())); currentNodes.clear(); SwingUtilities.invokeLater(() -> { vertexDataModel.setRowCount(0); for(Node vertex : vertices) { int vID = vertex.getID(); String vName = vertex.getName(); currentNodes.put(vID, vertex); vertexDataModel.addRow(new Object[] { vID, vName }); if(vID > nodeFactory.getLastID()) nodeFactory.setLastID(vID); } }); } private void loadEdges(Graph graph) { ArrayList<Edge> edges = new ArrayList<>(graph.getEdges()); Collections.sort(edges, (Edge e1, Edge e2) -> Integer.compare(e1.getID(), e2.getID())); currentEdges.clear(); SwingUtilities.invokeLater(() -> { edgeDataModel.setRowCount(0); for(Edge edge : edges) { int eID = edge.getID(); double weight = edge.getWeight(); Collection<Node> vertices = graph.getIncidentVertices(edge); String edgeType = graph.getEdgeType(edge).toString(); Node n1, n2; int n1_id, n2_id; Iterator<Node> iter = vertices.iterator(); n1 = iter.next(); n2 = iter.next(); edge.setSourceNode(n1); edge.setDestNode(n2); if(n1 != null) n1_id = n1.getID(); else n1_id = -1; if(n2 != null) n2_id = n2.getID(); else n2_id = -1; currentEdges.put(eID, edge); edgeDataModel.addRow(new Object[] { eID, n1_id, n2_id, weight, edgeType }); if(eID > edgeFactory.getLastID()) edgeFactory.setLastID(eID); } }); } private void addVertex() { VertexAddPanel addPanel = new VertexAddPanel(); int option = JOptionPane.showConfirmDialog(null, addPanel, "Add vertex", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { int id = (int) addPanel.idSpinner.getValue(); if(currentNodes.containsKey(id)) { JOptionPane.showMessageDialog(null, "Vertex already exists"); return; } String name = addPanel.nameField.getText(); Node node = new Node(id, name); currentGraph.addVertex(node); graphPanel.gViewer.repaint(); loadNodes(currentGraph); currentNodes.put(id, node); } } private void editVertex() { Node editNode; Set<Node> selectedVertices = graphPanel.gViewer.getPickedVertexState().getPicked(); if(selectedVertices.size() == 1) editNode = selectedVertices.iterator().next(); else { int[] selectedRows = dataPanel.vertexTable.getSelectedRows(); if(selectedRows.length == 1) { int id = (int) dataPanel.vertexDataModel.getValueAt(selectedRows[0], 0); editNode = currentNodes.get(id); } else { int id = getDialogID("Enter vertex ID to edit", currentNodes); if(id != -1) editNode = currentNodes.get(id); else return; } } VertexAddPanel editPanel = new VertexAddPanel(); editPanel.idSpinner.setValue(editNode.getID()); editPanel.nameField.setText(editNode.getName()); editPanel.idSpinner.setEnabled(false); editPanel.autoCheck.setVisible(false); int option = JOptionPane.showConfirmDialog(null, editPanel, "Edit vertex", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { editNode.setID((int) editPanel.idSpinner.getValue()); editNode.setName(editPanel.nameField.getText()); loadNodes(currentGraph); } } private void removeVertices(Set<Node> vertices) { if(vertices.isEmpty()) return; for(Node node : vertices) { int id = node.getID(); currentNodes.remove(id); currentGraph.removeVertex(node); graphPanel.gViewer.repaint(); loadNodes(currentGraph); } } private void removeVertex() { Set<Node> pickedNodes = graphPanel.gViewer.getPickedVertexState().getPicked(); if(!pickedNodes.isEmpty()) removeVertices(pickedNodes); else { int[] selectedRows = dataPanel.vertexTable.getSelectedRows(); if(selectedRows.length > 0) { Set<Node> selectedNodes = new HashSet<>(); for(int row : selectedRows) { int id = (int) dataPanel.vertexDataModel.getValueAt(row, 0); Node current = currentNodes.get(id); if(current != null) selectedNodes.add(current); } removeVertices(selectedNodes); } else { int id = getDialogID("Enter vertex ID to remove", currentNodes); if(id != -1) { Node removedNode = currentNodes.remove(id); currentGraph.removeVertex(removedNode); loadNodes(currentGraph); graphPanel.gViewer.repaint(); } } } } private void addEdge() { EdgeAddPanel addPanel = new EdgeAddPanel(); int option = JOptionPane.showConfirmDialog(null, addPanel, "Add edge", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { int id = (int) addPanel.idSpinner.getValue(); if(currentEdges.containsKey(id)) { JOptionPane.showMessageDialog(null, "Edge ID already exists"); return; } int fromID = (int) addPanel.fromSpinner.getValue(); int toID = (int) addPanel.toSpinner.getValue(); double weight = (double) addPanel.weightSpinner.getValue(); int eType = addPanel.edgeTypeBox.getSelectedIndex(); EdgeType edgeType = (eType == 0)? EdgeType.UNDIRECTED : EdgeType.DIRECTED; if(currentNodes.containsKey(fromID) && currentNodes.containsKey(toID)) { Edge edge = new Edge(id, weight, edgeType); Node n1 = currentNodes.get(fromID); Node n2 = currentNodes.get(toID); edge.setSourceNode(n1); edge.setDestNode(n2); currentEdges.put(id, edge); currentGraph.addEdge(edge, n1, n2, edgeType); loadEdges(currentGraph); graphPanel.gViewer.repaint(); } else JOptionPane.showMessageDialog(null, "Vertex ID does not exist"); } } private void editEdge() { Edge editEdge; Set<Edge> selectedEdges = graphPanel.gViewer.getPickedEdgeState().getPicked(); if(selectedEdges.size() == 1) editEdge = selectedEdges.iterator().next(); else { int[] selectedRows = dataPanel.edgeTable.getSelectedRows(); if(selectedRows.length == 1) { int id = (int) dataPanel.edgeDataModel.getValueAt(selectedRows[0], 0); editEdge = currentEdges.get(id); } else { int id = getDialogID("Enter edge ID to edit", currentEdges); if(id != -1) editEdge = currentEdges.get(id); else return; } } EdgeAddPanel editPanel = new EdgeAddPanel(); editPanel.idSpinner.setValue(editEdge.getID()); editPanel.fromSpinner.setValue(editEdge.getSourceNode().getID()); editPanel.toSpinner.setValue(editEdge.getDestNode().getID()); editPanel.weightSpinner.setValue(editEdge.getWeight()); editPanel.edgeTypeBox.setSelectedIndex(editEdge.getEdgeType() == EdgeType.UNDIRECTED? 0 : 1); editPanel.fromSpinner.setEnabled(false); editPanel.toSpinner.setEnabled(false); editPanel.idSpinner.setEnabled(false); editPanel.autoCheck.setVisible(false); int option = JOptionPane.showConfirmDialog(null, editPanel, "Edit edge", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { editEdge.setWeight((double) editPanel.weightSpinner.getValue()); editEdge.setEdgeType(editPanel.edgeTypeBox.getSelectedIndex() == 0? EdgeType.UNDIRECTED : EdgeType.DIRECTED); loadEdges(currentGraph); graphPanel.gViewer.repaint(); } } private void removeEdge() { Set<Edge> selectedEdges = graphPanel.gViewer.getPickedEdgeState().getPicked(); if(selectedEdges.isEmpty()) { int[] selectedRows = dataPanel.edgeTable.getSelectedRows(); if(selectedRows.length > 0) { for(int row : selectedRows) { int id = (int) dataPanel.edgeDataModel.getValueAt(row, 0); Edge current = currentEdges.remove(id); currentGraph.removeEdge(current); } } else { int id = getDialogID("Enter edge ID to remove", currentEdges); if(id != -1) { Edge removeEdge = currentEdges.remove(id); currentGraph.removeEdge(removeEdge); } else return; } } else { for(Edge edge : selectedEdges) { currentEdges.remove(edge.getID()); currentGraph.removeEdge(edge); } } loadEdges(currentGraph); graphPanel.gViewer.repaint(); } private int getDialogID(String message, Map collection) { String idStr = JOptionPane.showInputDialog(message); int id = -1; while(idStr != null && id == -1) { try { id = Integer.parseInt(idStr); if(collection.containsKey(id)) break; else { id = -1; JOptionPane.showMessageDialog(null, "ID was not found"); idStr = JOptionPane.showInputDialog(message); } } catch(NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid input found"); idStr = JOptionPane.showInputDialog(message); } } return id; } //-------------------------------------- // VERTEX ADD PANEL //-------------------------------------- private class VertexAddPanel extends JPanel implements ActionListener { private JSpinner idSpinner; private JCheckBox autoCheck; private JTextField nameField; public VertexAddPanel() { setLayout(new MigLayout()); idSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 10000, 1)); autoCheck = new JCheckBox("Auto"); nameField = new JTextField(); autoCheck.setSelected(true); idSpinner.setValue(nodeFactory.getLastID() + 1); idSpinner.setEnabled(false); add(new JLabel("ID ")); add(idSpinner, "width :40:"); add(autoCheck, "wrap"); add(new JLabel("Name: ")); add(nameField, "span 3, width :100:"); autoCheck.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == autoCheck) idSpinner.setEnabled(!autoCheck.isSelected()); } } //-------------------------------------- // EDGE ADD PANEL //-------------------------------------- private class EdgeAddPanel extends JPanel implements ActionListener { private JSpinner idSpinner, fromSpinner, toSpinner, weightSpinner; private JCheckBox autoCheck; private JComboBox edgeTypeBox; public EdgeAddPanel() { setLayout(new MigLayout()); idSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); fromSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); toSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); weightSpinner = new JSpinner(new SpinnerNumberModel(0.0, 0.0, 10000.0, 0.1)); autoCheck = new JCheckBox("Auto"); edgeTypeBox = new JComboBox(); edgeTypeBox.addItem("Undirected"); edgeTypeBox.addItem("Directed"); idSpinner.setValue(edgeFactory.getLastID() + 1); idSpinner.setEnabled(false); autoCheck.setSelected(true); autoCheck.addActionListener(this); add(new JLabel("ID ")); add(idSpinner, "width :40:"); add(autoCheck, "wrap"); add(new JLabel("From vertex ID")); add(fromSpinner, "span 2, width :40:, wrap"); add(new JLabel("To vertex ID")); add(toSpinner, "span 2, width :40:, wrap"); add(new JLabel("Weight")); add(weightSpinner, "span 2, width :70:, wrap"); add(new JLabel("Type")); add(edgeTypeBox, "span 2"); } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == autoCheck) idSpinner.setEnabled(!autoCheck.isSelected()); } } } //-------------------------------------- // GRAPH PANEL //-------------------------------------- private class GraphPanel extends JPanel implements ItemListener, GraphMouseListener { private final VisualizationViewer<Node, Edge> gViewer; private AggregateLayout<Node, Edge> gLayout; private EditingModalGraphMouse mouse; public GraphPanel() { setLayout(new BorderLayout()); gLayout = new AggregateLayout(new FRLayout(currentGraph)); gViewer = new VisualizationViewer<>(gLayout); ScalingControl scaler = new CrossoverScalingControl(); scaler.scale(gViewer, 0.7f, gViewer.getCenter()); gViewer.scaleToLayout(scaler); gViewer.setBackground(Color.WHITE); gViewer.getRenderContext().setVertexFillPaintTransformer(new ObjectFillTransformer<>(gViewer.getPickedVertexState())); gViewer.getRenderContext().setEdgeDrawPaintTransformer(new ObjectFillTransformer(gViewer.getPickedEdgeState())); gViewer.getPickedVertexState().addItemListener(this); gViewer.getPickedEdgeState().addItemListener(this); add(gViewer); mouse = new EditingModalGraphMouse(gViewer.getRenderContext(), nodeFactory, edgeFactory); mouse.setMode(ModalGraphMouse.Mode.PICKING); gViewer.addGraphMouseListener(this); mouse.remove(mouse.getPopupEditingPlugin()); gViewer.setGraphMouse(mouse); } @Override public void graphClicked(Object v, MouseEvent me) {} @Override public void graphPressed(Object v, MouseEvent me) {} @Override public void graphReleased(Object v, MouseEvent me) { if(controlPanel.editCheck.isSelected()) { dataPanel.loadNodes(currentGraph); dataPanel.loadEdges(currentGraph); } } //-------------------------------------- // CENTRALITY TRANSFORMER //-------------------------------------- private class CentralityTransformer implements Transformer<Node, Shape> { List<Node> centralNodes; int numRanks; public CentralityTransformer(List<Node> centralNodes, int numRanks) { this.centralNodes = centralNodes; this.numRanks = numRanks; } @Override public Shape transform(Node node) { for(int i = 0; i < numRanks; i++) { if(node.equals(centralNodes.get(i))) { int size = 20 + ((numRanks - i) * 10); return new Ellipse2D.Double(-10, -10, size, size); } } return new Ellipse2D.Double(-10, -10, 20, 20); } } private void setVertexColour(Color colour, Collection<Node> vertices) { if(vertices == null) vertices = currentGraph.getVertices(); for(Node vertex : vertices) vertex.setFill(colour); gViewer.repaint(); } private void setEdgeColour(Color colour, Collection<Edge> edges) { if(edges == null) edges = currentGraph.getEdges(); for(Edge edge : edges) edge.setFill(colour); gViewer.repaint(); } private void showVertexLabels(boolean show) { gViewer.getRenderContext().setVertexLabelTransformer(new VertexLabelTransformer(show)); gViewer.repaint(); } private void showEdgeLabels(boolean show) { gViewer.getRenderContext().setEdgeLabelTransformer(new EdgeLabelTransformer(show)); gViewer.repaint(); } private void showCluster() { int numRemoved = (int) controlPanel.clusterEdgeRemoveSpinner.getValue(); boolean group = controlPanel.clusterTransformCheck.isSelected(); GraphUtilities.cluster(gLayout, currentGraph, numRemoved, group); gViewer.repaint(); } private void showCentrality() { Map<Node, Double> centrality; if(currentGraph.getVertexCount() <= 1) return; SparseDoubleMatrix2D matrix = GraphMatrixOperations.graphToSparseMatrix(currentGraph); int selectedCentrality = controlPanel.centralityTypeBox.getSelectedIndex(); boolean transform = controlPanel.centralityMorphCheck.isSelected(); String prefix; switch(selectedCentrality) { case 0: centrality = MatrixTools.getScores(MatrixTools.powerIterationFull(matrix), currentGraph); prefix = "EigenVector"; break; case 1: centrality = MatrixTools.getScores(MatrixTools.pageRankPI(matrix), currentGraph); prefix = "PageRank"; break; /* case 2: centrality = new ClosenessCentrality(currentGraph, new WeightTransformer()); prefix = "Closeness"; break; case 3: centrality = new BetweennessCentrality(currentGraph, new WeightTransformer()); prefix = "Betweenness"; break; */ default: return; } Collection<Node> vertices = currentGraph.getVertices(); PriorityQueue<SimpleEntry<Node, Double>> scores = null; if(transform) { scores = new PriorityQueue<>((SimpleEntry<Node, Double> a1, SimpleEntry<Node, Double> a2) -> Double.compare(a2.getValue(), a1.getValue())); } for(Node node : vertices) { double score = centrality.get(node); String output = MessageFormat.format("({0}) Vertex: {1}, Score: {2}", prefix, node.getID(), score); sendToOutput(output); if(transform) scores.add(new SimpleEntry(node, score)); } if(transform) { ArrayList<Node> centralNodes = new ArrayList<>(); Color[] centralColours = new Color[] { Color.RED, Color.ORANGE, Color.BLUE }; for(int i = 0; i < 3; i++) { SimpleEntry<Node, Double> entry = scores.poll(); centralNodes.add(entry.getKey()); entry.getKey().setFill(centralColours[i]); } graphPanel.gViewer.getRenderContext().setVertexShapeTransformer(new CentralityTransformer(centralNodes, 3)); graphPanel.gViewer.repaint(); } } private void reloadGraph() { gLayout.removeAll(); gLayout.setGraph(currentGraph); gViewer.repaint(); dataPanel.loadNodes(currentGraph); dataPanel.loadEdges(currentGraph); } private void resetGraph() { currentGraph = new SparseMultigraph<>(); reloadGraph(); } @Override public void itemStateChanged(ItemEvent e) { if(controlPanel.selectCheck.isSelected()) { selectedItems = e.getItemSelectable().getSelectedObjects(); controlPanel.updateSelectedComponents(); } } } //-------------------------------------- // OUTPUT PANEL //-------------------------------------- private class OutputPanel extends JPanel { private JTextArea outputArea; public OutputPanel() { setLayout(new BorderLayout()); outputArea = new JTextArea(""); outputArea.setBackground(Color.WHITE); outputArea.setEditable(false); JScrollPane outputScroller = new JScrollPane(outputArea); outputScroller.setPreferredSize(new Dimension(650, 565)); outputScroller.setBorder(null); add(outputScroller); } private void clearLog() { outputArea.setText(""); } } } }
src/com/graphi/display/LayoutPanel.java
//========================================= // Kyle Russell // AUT University 2015 // https://github.com/denkers/graphi //========================================= package com.graphi.display; import cern.colt.matrix.impl.SparseDoubleMatrix2D; import static com.graphi.display.Window.HEIGHT; import static com.graphi.display.Window.WIDTH; import com.graphi.io.Storage; import com.graphi.util.Edge; import com.graphi.sim.Network; import com.graphi.util.EdgeFactory; import com.graphi.util.EdgeLabelTransformer; import com.graphi.util.GraphUtilities; import com.graphi.util.MatrixTools; import com.graphi.util.Node; import com.graphi.util.NodeFactory; import com.graphi.util.ObjectFillTransformer; import com.graphi.util.VertexLabelTransformer; import com.graphi.util.WeightTransformer; import edu.uci.ics.jung.algorithms.layout.AggregateLayout; import edu.uci.ics.jung.algorithms.layout.FRLayout; import edu.uci.ics.jung.algorithms.matrix.GraphMatrixOperations; import edu.uci.ics.jung.algorithms.scoring.BetweennessCentrality; import edu.uci.ics.jung.algorithms.scoring.ClosenessCentrality; import edu.uci.ics.jung.algorithms.scoring.EigenvectorCentrality; import edu.uci.ics.jung.algorithms.scoring.PageRank; import edu.uci.ics.jung.algorithms.scoring.VertexScorer; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.SparseMultigraph; import edu.uci.ics.jung.graph.util.EdgeType; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.CrossoverScalingControl; import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse; import edu.uci.ics.jung.visualization.control.GraphMouseListener; import edu.uci.ics.jung.visualization.control.ModalGraphMouse; import edu.uci.ics.jung.visualization.control.ScalingControl; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.util.List; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.geom.Ellipse2D; import java.io.File; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; import net.miginfocom.swing.MigLayout; import org.apache.commons.collections15.Transformer; public class LayoutPanel extends JPanel { private final ControlPanel controlPanel; private final ScreenPanel screenPanel; private final JSplitPane splitPane; private final JScrollPane controlScroll; public static final Color TRANSPARENT = new Color(255, 255, 255, 0); public static final Color PRESET_BG = new Color(200, 200, 200); private Graph<Node, Edge> currentGraph; private final Map<Integer, Node> currentNodes; private final Map<Integer, Edge> currentEdges; private NodeFactory nodeFactory; private EdgeFactory edgeFactory; private Object[] selectedItems; private MainMenu menu; private JFrame frame; public LayoutPanel(MainMenu menu, JFrame frame) { //setPreferredSize(new Dimension(950, 650)); setPreferredSize(new Dimension((int)(Window.WIDTH * 0.7), (int) (Window.HEIGHT * 0.85))); setLayout(new BorderLayout()); this.menu = menu; this.frame = frame; nodeFactory = new NodeFactory(); edgeFactory = new EdgeFactory(); currentGraph = new SparseMultigraph<>(); currentNodes = new HashMap<>(); currentEdges = new HashMap<>(); controlPanel = new ControlPanel(); screenPanel = new ScreenPanel(); splitPane = new JSplitPane(); controlScroll = new JScrollPane(controlPanel); controlScroll.setBorder(null); splitPane.setLeftComponent(screenPanel); splitPane.setRightComponent(controlScroll); splitPane.setResizeWeight(0.7); add(splitPane, BorderLayout.CENTER); } private void sendToOutput(String output) { SimpleDateFormat sdf = new SimpleDateFormat("K:MM a dd.MM.yy"); String date = sdf.format(new Date()); String prefix = "\n[" + date + "] "; JTextArea outputArea = screenPanel.outputPanel.outputArea; SwingUtilities.invokeLater(()-> { outputArea.setText(outputArea.getText() + prefix + output); }); } private File getFile(boolean open, String desc, String...extensions) { JFileChooser jfc = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter(desc, extensions); jfc.setFileFilter(filter); if(open) jfc.showOpenDialog(null); else jfc.showSaveDialog(null); return jfc.getSelectedFile(); } public static JPanel wrapComponents(Border border, Component... components) { JPanel panel = new JPanel(); panel.setBorder(border); for(Component component : components) panel.add(component); return panel; } //-------------------------------------- // CONTROL PANEL //-------------------------------------- private class ControlPanel extends JPanel implements ActionListener { private final String BA_PANEL_CARD = "ba_panel"; private final String KL_PANEL_CARD = "kl_panel"; private final String CLUSTER_PANEL_CARD = "cluster_panel"; private final String SPATH_PANEL_CARD = "spath_panel"; private final String CENTRALITY_PANEL_CARD = "centrality_panel"; private JPanel dataControlPanel, outputControlPanel, displayControlPanel; private JPanel modePanel; private JPanel simPanel; private JRadioButton editCheck, selectCheck, moveCheck; private ButtonGroup modeGroup; private JComboBox genAlgorithmsBox; private JButton resetGeneratorBtn, executeGeneratorBtn; private JPanel genPanel, baGenPanel, klGenPanel; private JSpinner latticeSpinner, clusteringSpinner; private JSpinner initialNSpinner, addNSpinner; private IOPanel ioPanel; private JPanel editPanel; private JLabel selectedLabel; private JButton gObjAddBtn, gObjEditBtn, gObjRemoveBtn; private JPanel computePanel; private JPanel computeInnerPanel; private JPanel clusterPanel, spathPanel; private JSpinner clusterEdgeRemoveSpinner; private JCheckBox clusterTransformCheck; private JComboBox computeBox; private JTextField spathFromField, spathToField; private JButton computeBtn; private JPanel centralityPanel; private JComboBox centralityTypeBox; private ButtonGroup centralityOptions; private JCheckBox centralityMorphCheck; private ButtonGroup editObjGroup; private JRadioButton editVertexRadio, editEdgeRadio; private JPanel viewerPanel; private JCheckBox viewerVLabelsCheck; private JCheckBox viewerELabelsCheck; private JButton viewerBGBtn, vertexBGBtn, edgeBGBtn; public ControlPanel() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBorder(BorderFactory.createEmptyBorder(15, 0, 3, 8)); setPreferredSize(new Dimension(230, 1200)); ioPanel = new IOPanel(); modePanel = new JPanel(); simPanel = new JPanel(new MigLayout()); modePanel.setPreferredSize(new Dimension(230, 65)); modePanel.setBorder(BorderFactory.createTitledBorder("Mode controls")); simPanel.setPreferredSize(new Dimension(230, 150)); simPanel.setBorder(BorderFactory.createTitledBorder("Simulation controls")); modeGroup = new ButtonGroup(); editCheck = new JRadioButton("Edit"); selectCheck = new JRadioButton("Select"); moveCheck = new JRadioButton("Move"); editCheck.addActionListener(this); selectCheck.addActionListener(this); moveCheck.addActionListener(this); modeGroup.add(editCheck); modeGroup.add(selectCheck); modeGroup.add(moveCheck); modePanel.add(editCheck); modePanel.add(selectCheck); modePanel.add(moveCheck); selectCheck.setSelected(true); genAlgorithmsBox = new JComboBox(); genAlgorithmsBox.addItem("Kleinberg"); genAlgorithmsBox.addItem("Barabasi-Albert"); genAlgorithmsBox.addActionListener(this); resetGeneratorBtn = new JButton("Reset"); executeGeneratorBtn = new JButton("Generate"); executeGeneratorBtn.addActionListener(this); resetGeneratorBtn.addActionListener(this); resetGeneratorBtn.setBackground(Color.WHITE); executeGeneratorBtn.setBackground(Color.WHITE); genPanel = new JPanel(new CardLayout()); baGenPanel = new JPanel(new MigLayout()); klGenPanel = new JPanel(new MigLayout()); genPanel.add(klGenPanel, KL_PANEL_CARD); genPanel.add(baGenPanel, BA_PANEL_CARD); genPanel.setBackground(TRANSPARENT); baGenPanel.setBackground(TRANSPARENT); klGenPanel.setBackground(TRANSPARENT); latticeSpinner = new JSpinner(new SpinnerNumberModel(15, 0, 100, 1)); clusteringSpinner = new JSpinner(new SpinnerNumberModel(2, 0, 10, 1)); latticeSpinner.setPreferredSize(new Dimension(50, 20)); clusteringSpinner.setPreferredSize(new Dimension(50, 20)); latticeSpinner.setOpaque(true); clusteringSpinner.setOpaque(true); initialNSpinner = new JSpinner(new SpinnerNumberModel(2, 0, 1000, 1)); addNSpinner = new JSpinner(new SpinnerNumberModel(100, 0, 1000, 1)); initialNSpinner.setOpaque(true); addNSpinner.setOpaque(true); baGenPanel.add(new JLabel("Initial nodes")); baGenPanel.add(initialNSpinner, "wrap"); baGenPanel.add(new JLabel("Generated nodes")); baGenPanel.add(addNSpinner); klGenPanel.add(new JLabel("Lattice size")); klGenPanel.add(latticeSpinner, "wrap"); klGenPanel.add(new JLabel("Clustering exp.")); klGenPanel.add(clusteringSpinner); JPanel simMigPanel = new JPanel(new MigLayout()); simMigPanel.setBackground(PRESET_BG); simPanel.add(new JLabel("Generator"), ""); simPanel.add(genAlgorithmsBox, "wrap"); simPanel.add(genPanel, "wrap, span 2"); simPanel.add(resetGeneratorBtn, ""); simPanel.add(executeGeneratorBtn, ""); //simPanel.add(simMigPanel); editPanel = new JPanel(new GridLayout(3, 1)); editPanel.setBorder(BorderFactory.createTitledBorder("Graph object Controls")); editPanel.setBackground(TRANSPARENT); editObjGroup = new ButtonGroup(); editVertexRadio = new JRadioButton("Vertex"); editEdgeRadio = new JRadioButton("Edge"); gObjAddBtn = new JButton("Add"); gObjEditBtn = new JButton("Edit"); gObjRemoveBtn = new JButton("Delete"); selectedLabel = new JLabel("None"); gObjAddBtn.setBackground(Color.WHITE); gObjEditBtn.setBackground(Color.WHITE); gObjRemoveBtn.setBackground(Color.WHITE); selectedLabel.setFont(new Font("Arial", Font.BOLD, 12)); gObjAddBtn.addActionListener(this); gObjEditBtn.addActionListener(this); gObjRemoveBtn.addActionListener(this); editObjGroup.add(editVertexRadio); editObjGroup.add(editEdgeRadio); editVertexRadio.setSelected(true); JPanel selectedPanel = wrapComponents(null, new JLabel("Selected: "), selectedLabel); JPanel editObjPanel = wrapComponents(null, editVertexRadio, editEdgeRadio); JPanel gObjOptsPanel = wrapComponents(null, gObjAddBtn, gObjEditBtn, gObjRemoveBtn); selectedPanel.setBackground(PRESET_BG); gObjOptsPanel.setBackground(PRESET_BG); editObjPanel.setBackground(PRESET_BG); editPanel.add(selectedPanel); editPanel.add(editObjPanel); editPanel.add(gObjOptsPanel); computePanel = new JPanel(); computeInnerPanel = new JPanel(new CardLayout()); clusterPanel = new JPanel(); centralityPanel = new JPanel(new MigLayout()); spathPanel = new JPanel(); computeBox = new JComboBox(); computeBtn = new JButton("Execute"); computePanel.setPreferredSize(new Dimension(230, 180)); computePanel.setBorder(BorderFactory.createTitledBorder("Computation controls")); spathPanel.setLayout(new BoxLayout(spathPanel, BoxLayout.Y_AXIS)); spathPanel.setBackground(TRANSPARENT); computeBtn.setBackground(Color.WHITE); computeBtn.addActionListener(this); computeBox.addItem("Clusters"); computeBox.addItem("Centrality"); computeBox.addActionListener(this); clusterEdgeRemoveSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 100, 1)); clusterTransformCheck = new JCheckBox("Transform graph"); clusterEdgeRemoveSpinner.setPreferredSize(new Dimension(50, 20)); JPanel clusterEdgesPanel = wrapComponents(null, new JLabel("Delete edges"), clusterEdgeRemoveSpinner); clusterPanel.setLayout(new MigLayout()); clusterPanel.add(clusterEdgesPanel, "wrap"); clusterPanel.add(clusterTransformCheck); clusterEdgesPanel.setBackground(PRESET_BG); clusterPanel.setBackground(PRESET_BG); spathFromField = new JTextField(); spathToField = new JTextField(); spathFromField.setPreferredSize(new Dimension(50, 20)); spathToField.setPreferredSize(new Dimension(50, 20)); JLabel tLabel = new JLabel("To ID"); JPanel spathFromPanel = wrapComponents(null, new JLabel("From ID"), spathFromField); JPanel spathToPanel = wrapComponents(null, tLabel, spathToField); JPanel spathWrapper = new JPanel(new MigLayout()); spathWrapper.add(spathFromPanel, "wrap"); spathWrapper.add(spathToPanel); spathWrapper.setBackground(TRANSPARENT); spathFromPanel.setBackground(TRANSPARENT); spathToPanel.setBackground(TRANSPARENT); spathPanel.add(spathWrapper); centralityTypeBox = new JComboBox(); centralityOptions = new ButtonGroup(); centralityMorphCheck = new JCheckBox("Transform graph"); centralityTypeBox.addItem("Eigenvector"); centralityTypeBox.addItem("PageRank"); centralityTypeBox.addItem("Closeness"); centralityTypeBox.addItem("Betweenness"); centralityTypeBox.addActionListener(this); JPanel cenTypePanel = wrapComponents(null, new JLabel("Type"), centralityTypeBox); centralityPanel.add(cenTypePanel, "wrap"); centralityPanel.add(centralityMorphCheck); cenTypePanel.setBackground(PRESET_BG); centralityPanel.setBackground(PRESET_BG); computeInnerPanel.add(clusterPanel, CLUSTER_PANEL_CARD); computeInnerPanel.add(spathPanel, SPATH_PANEL_CARD); computeInnerPanel.add(centralityPanel, CENTRALITY_PANEL_CARD); JPanel computeMigPanel = new JPanel(new MigLayout()); computeMigPanel.setBackground(PRESET_BG); computeMigPanel.add(new JLabel("Compute ")); computeMigPanel.add(computeBox, "wrap"); computeMigPanel.add(computeInnerPanel, "wrap, span 2"); computeMigPanel.add(computeBtn, "span 2, al center"); computePanel.add(computeMigPanel); CardLayout clusterInnerLayout = (CardLayout) computeInnerPanel.getLayout(); clusterInnerLayout.show(computeInnerPanel, CLUSTER_PANEL_CARD); viewerPanel = new JPanel(); JPanel innerViewerPanel = new JPanel(new MigLayout()); viewerVLabelsCheck = new JCheckBox("Vertex labels"); viewerELabelsCheck = new JCheckBox("Edge labels"); viewerBGBtn = new JButton("Choose"); vertexBGBtn = new JButton("Choose"); edgeBGBtn = new JButton("Choose"); viewerBGBtn.addActionListener(this); vertexBGBtn.addActionListener(this); edgeBGBtn.addActionListener(this); viewerVLabelsCheck.addActionListener(this); viewerELabelsCheck.addActionListener(this); viewerPanel.setBorder(BorderFactory.createTitledBorder("Viewer controls")); viewerPanel.setPreferredSize(new Dimension(500, 200)); innerViewerPanel.setBackground(PRESET_BG); innerViewerPanel.add(viewerVLabelsCheck, "wrap, span 2"); innerViewerPanel.add(viewerELabelsCheck, "wrap, span 2"); innerViewerPanel.add(new JLabel("Vertex background")); innerViewerPanel.add(vertexBGBtn, "wrap"); innerViewerPanel.add(new JLabel("Edge background")); innerViewerPanel.add(edgeBGBtn, "wrap"); innerViewerPanel.add(new JLabel("Viewer background")); innerViewerPanel.add(viewerBGBtn, "wrap"); viewerPanel.add(innerViewerPanel); menu.exitItem.addActionListener(this); menu.miniItem.addActionListener(this); menu.maxItem.addActionListener(this); menu.importGraphItem.addActionListener(this); menu.exportGraphItem.addActionListener(this); menu.importLogItem.addActionListener(this); menu.exportLogItem.addActionListener(this); menu.vLabelsItem.addActionListener(this); menu.eLabelsItem.addActionListener(this); menu.viewerBGItem.addActionListener(this); menu.edgeBGItem.addActionListener(this); menu.vertexBGItem.addActionListener(this); menu.clearLogItem.addActionListener(this); menu.resetGraphItem.addActionListener(this); menu.addVertexItem.addActionListener(this); menu.editVertexItem.addActionListener(this); menu.removeVertexItem.addActionListener(this); menu.addEdgeItem.addActionListener(this); menu.editEdgeItem.addActionListener(this); menu.removeEdgeItem.addActionListener(this); menu.aboutItem.addActionListener(this); add(modePanel); add(Box.createRigidArea(new Dimension(230, 30))); add(simPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(ioPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(editPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(computePanel); add(Box.createRigidArea(new Dimension(230, 30))); add(viewerPanel); } private void updateSelectedComponents() { if(selectedItems == null || selectedItems.length == 0) selectedLabel.setText("None"); else { if(selectedItems.length > 1) selectedLabel.setText(selectedItems.length + " objects"); else { Object selectedObj = selectedItems[0]; if(selectedObj instanceof Node) selectedLabel.setText("Node (ID=" + ((Node) selectedObj).getID() + ")"); else if(selectedObj instanceof Edge) selectedLabel.setText("Edge (ID=" + ((Edge) selectedObj).getID() + ")"); } } } private void computeExecute() { int selectedIndex = computeBox.getSelectedIndex(); switch(selectedIndex) { case 0: screenPanel.graphPanel.showCluster(); case 1: screenPanel.graphPanel.showCentrality(); } } private void showGeneratorSim() { int genIndex = genAlgorithmsBox.getSelectedIndex(); nodeFactory.setLastID(0); edgeFactory.setLastID(0); switch(genIndex) { case 0: showKleinbergSim(); break; case 1: showBASim(); break; } screenPanel.graphPanel.reloadGraph(); } private void showAbout() { JLabel nameLabel = new JLabel("Kyle Russell 2015", SwingConstants.CENTER); JLabel locLabel = new JLabel("AUT University"); JLabel repoLabel = new JLabel("https://github.com/denkers/graphi"); JPanel aboutPanel = new JPanel(); aboutPanel.setLayout(new BoxLayout(aboutPanel, BoxLayout.Y_AXIS)); aboutPanel.add(nameLabel); aboutPanel.add(locLabel); aboutPanel.add(repoLabel); JOptionPane.showMessageDialog(null, aboutPanel, "Graphi - Author", JOptionPane.INFORMATION_MESSAGE); } private void resetSim() { currentGraph = new SparseMultigraph(); screenPanel.graphPanel.reloadGraph(); } private void showKleinbergSim() { int latticeSize = (int) latticeSpinner.getValue(); int clusterExp = (int) clusteringSpinner.getValue(); currentGraph = Network.generateKleinberg(latticeSize, clusterExp, new NodeFactory(), new EdgeFactory()); } private void showBASim() { int m = (int) initialNSpinner.getValue(); int n = (int) addNSpinner.getValue(); currentGraph = Network.generateBerbasiAlbert(new NodeFactory(), new EdgeFactory(), n, m); } private void showVertexBGChange() { Color selectedColour = JColorChooser.showDialog(null, "Choose vertex colour", Color.BLACK); if(selectedColour != null) screenPanel.graphPanel.setVertexColour(selectedColour, null); } private void showEdgeBGChange() { Color selectedColour = JColorChooser.showDialog(null, "Choose edge colour", Color.BLACK); if(selectedColour != null) screenPanel.graphPanel.setEdgeColour(selectedColour, null); } private void showViewerBGChange() { Color selectedColour = JColorChooser.showDialog(null, "Choose viewer background colour", Color.WHITE); if(selectedColour != null) screenPanel.graphPanel.gViewer.setBackground(selectedColour); } //-------------------------------------- // IO PANEL //-------------------------------------- private class IOPanel extends JPanel implements ActionListener { private JButton exportBtn, importBtn; private JLabel currentStorageLabel; private ButtonGroup storageGroup; private JRadioButton storageGraphRadio, storageLogRadio; public IOPanel() { setLayout(new GridLayout(3, 1)); setBorder(BorderFactory.createTitledBorder("I/O Controls")); currentStorageLabel = new JLabel("None"); importBtn = new JButton("Import"); exportBtn = new JButton("Export"); storageGroup = new ButtonGroup(); storageGraphRadio = new JRadioButton("Graph"); storageLogRadio = new JRadioButton("Log"); storageGroup.add(storageGraphRadio); storageGroup.add(storageLogRadio); importBtn.addActionListener(this); exportBtn.addActionListener(this); storageGraphRadio.addActionListener(this); storageLogRadio.addActionListener(this); importBtn.setBackground(Color.WHITE); exportBtn.setBackground(Color.WHITE); storageGraphRadio.setSelected(true); JPanel storageBtnWrapper = wrapComponents(null, importBtn, exportBtn); JPanel currentGraphWrapper = wrapComponents(null, new JLabel("Active: "), currentStorageLabel); JPanel storageOptsWrapper = wrapComponents(null, storageGraphRadio, storageLogRadio); storageBtnWrapper.setBackground(PRESET_BG); currentGraphWrapper.setBackground(PRESET_BG); storageOptsWrapper.setBackground(PRESET_BG); add(currentGraphWrapper); add(storageOptsWrapper); add(storageBtnWrapper); currentStorageLabel.setFont(new Font("Arial", Font.BOLD, 12)); } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == importBtn) { if(storageGraphRadio.isSelected()) importGraph(); else importLog(); } else if(src == exportBtn) { if(storageGraphRadio.isSelected()) exportGraph(); else exportLog(); } } } private void showCurrentComputePanel() { int selectedIndex = computeBox.getSelectedIndex(); String card; switch(selectedIndex) { case 0: card = CLUSTER_PANEL_CARD; break; case 1: card = CENTRALITY_PANEL_CARD; break; case 2: card = SPATH_PANEL_CARD; break; default: return; } CardLayout clusterInnerLayout = (CardLayout) computeInnerPanel.getLayout(); clusterInnerLayout.show(computeInnerPanel, card); } private void showSimPanel() { int selectedIndex = genAlgorithmsBox.getSelectedIndex(); String card; switch(selectedIndex) { case 0: card = KL_PANEL_CARD; break; case 1: card = BA_PANEL_CARD; break; default: return; } CardLayout gLayout = (CardLayout) genPanel.getLayout(); gLayout.show(genPanel, card); } private void exportGraph() { File file = getFile(false, "Graphi .graph file", "graph"); if(file != null && currentGraph != null) Storage.saveGraph(currentGraph, file); } private void importGraph() { File file = getFile(true, "Graphi .graph file", "graph"); if(file != null) { nodeFactory.setLastID(0); edgeFactory.setLastID(0); currentGraph = Storage.openGraph(file); ioPanel.currentStorageLabel.setText(file.getName()); initCurrentNodes(); initCurrentEdges(); screenPanel.graphPanel.gLayout.setGraph(currentGraph); screenPanel.graphPanel.gViewer.repaint(); screenPanel.dataPanel.loadNodes(currentGraph); screenPanel.dataPanel.loadEdges(currentGraph); } } private void initCurrentNodes() { if(currentGraph == null) return; currentNodes.clear(); Collection<Node> nodes = currentGraph.getVertices(); for(Node node : nodes) currentNodes.put(node.getID(), node); } private void initCurrentEdges() { if(currentGraph == null) return; currentEdges.clear(); Collection<Edge> edges = currentGraph.getEdges(); for(Edge edge : edges) currentEdges.put(edge.getID(), edge); } private void exportLog() { File file = getFile(false, "Graphi .log file", "log"); if(file != null) Storage.saveOutputLog(screenPanel.outputPanel.outputArea.getText(), file); } private void importLog() { File file = getFile(true, "Graphi .log file", "log"); if(file != null) { ioPanel.currentStorageLabel.setText(file.getName()); screenPanel.outputPanel.outputArea.setText(Storage.openOutputLog(file)); } } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == computeBox) showCurrentComputePanel(); else if(src == gObjAddBtn) { if(editVertexRadio.isSelected()) screenPanel.dataPanel.addVertex(); else screenPanel.dataPanel.addEdge(); } else if(src == gObjEditBtn) { if(editVertexRadio.isSelected()) screenPanel.dataPanel.editVertex(); else screenPanel.dataPanel.editEdge(); } else if(src == gObjRemoveBtn) { if(editVertexRadio.isSelected()) screenPanel.dataPanel.removeVertex(); else screenPanel.dataPanel.removeEdge(); } else if(src == editCheck) { screenPanel.graphPanel.mouse.setMode(ModalGraphMouse.Mode.EDITING); screenPanel.graphPanel.mouse.remove(screenPanel.graphPanel.mouse.getPopupEditingPlugin()); } else if(src == moveCheck) screenPanel.graphPanel.mouse.setMode(ModalGraphMouse.Mode.TRANSFORMING); else if(src == selectCheck) screenPanel.graphPanel.mouse.setMode(ModalGraphMouse.Mode.PICKING); else if(src == executeGeneratorBtn) showGeneratorSim(); else if(src == resetGeneratorBtn) resetSim(); else if(src == computeBtn) computeExecute(); else if(src == genAlgorithmsBox) showSimPanel(); else if(src == vertexBGBtn) showVertexBGChange(); else if(src == edgeBGBtn) showEdgeBGChange(); else if(src == viewerBGBtn) showViewerBGChange(); else if(src == viewerVLabelsCheck) screenPanel.graphPanel.showVertexLabels(viewerVLabelsCheck.isSelected()); else if(src == viewerELabelsCheck) screenPanel.graphPanel.showEdgeLabels(viewerELabelsCheck.isSelected()); else if(src == menu.aboutItem) showAbout(); else if(src == menu.exitItem) System.exit(0); else if(src == menu.miniItem) frame.setState(JFrame.ICONIFIED); else if(src == menu.maxItem) frame.setExtendedState(JFrame.MAXIMIZED_BOTH); else if(src == menu.importGraphItem) importGraph(); else if(src == menu.exportGraphItem) exportGraph(); else if(src == menu.importLogItem) importLog(); else if(src == menu.exportLogItem) exportLog(); else if(src == menu.vLabelsItem) screenPanel.graphPanel.showVertexLabels(true); else if(src == menu.eLabelsItem) screenPanel.graphPanel.showEdgeLabels(true); else if(src == menu.viewerBGItem) showViewerBGChange(); else if(src == menu.edgeBGItem) showEdgeBGChange(); else if(src == menu.vertexBGItem) showVertexBGChange(); else if(src == menu.clearLogItem) screenPanel.outputPanel.clearLog(); else if(src == menu.resetGraphItem) screenPanel.graphPanel.resetGraph(); else if(src == menu.addVertexItem) screenPanel.dataPanel.addVertex(); else if(src == menu.editVertexItem) screenPanel.dataPanel.editVertex(); else if(src == menu.removeVertexItem) screenPanel.dataPanel.removeVertex(); else if(src == menu.addEdgeItem) screenPanel.dataPanel.addEdge(); else if(src == menu.editEdgeItem) screenPanel.dataPanel.editEdge(); else if(src == menu.removeEdgeItem) screenPanel.dataPanel.removeEdge(); } } //-------------------------------------- // SCREEN PANEL //-------------------------------------- private class ScreenPanel extends JPanel { private final DataPanel dataPanel; private final GraphPanel graphPanel; private final OutputPanel outputPanel; private final JTabbedPane tabPane; public ScreenPanel() { setLayout(new BorderLayout()); setBorder(BorderFactory.createEmptyBorder(15, 5, 5, 5)); tabPane = new JTabbedPane(); dataPanel = new DataPanel(); graphPanel = new GraphPanel(); outputPanel = new OutputPanel(); tabPane.addTab("Display", graphPanel); tabPane.addTab("Data", dataPanel); tabPane.addTab("Output", outputPanel); add(tabPane); } private class DataPanel extends JPanel { private final JTable vertexTable, edgeTable; private final DefaultTableModel vertexDataModel, edgeDataModel; private final JTabbedPane dataTabPane; private final JScrollPane vertexScroller, edgeScroller; public DataPanel() { setLayout(new BorderLayout()); dataTabPane = new JTabbedPane(); vertexDataModel = new DefaultTableModel(); vertexTable = new JTable(vertexDataModel) { @Override public boolean isCellEditable(int row, int col) { return false; }; }; edgeDataModel = new DefaultTableModel(); edgeTable = new JTable(edgeDataModel) { @Override public boolean isCellEditable(int row, int col) { return false; } }; vertexScroller = new JScrollPane(vertexTable); edgeScroller = new JScrollPane(edgeTable); vertexTable.setPreferredScrollableViewportSize(new Dimension(630, 500)); vertexDataModel.addColumn("ID"); vertexDataModel.addColumn("Name"); edgeDataModel.addColumn("ID"); edgeDataModel.addColumn("FromVertex"); edgeDataModel.addColumn("ToVertex"); edgeDataModel.addColumn("Weight"); edgeDataModel.addColumn("EdgeType"); dataTabPane.addTab("Vertex table", vertexScroller); dataTabPane.addTab("Edge table", edgeScroller); add(dataTabPane); } private void loadNodes(Graph graph) { ArrayList<Node> vertices = new ArrayList<>(graph.getVertices()); Collections.sort(vertices, (Node n1, Node n2) -> Integer.compare(n1.getID(), n2.getID())); currentNodes.clear(); SwingUtilities.invokeLater(() -> { vertexDataModel.setRowCount(0); for(Node vertex : vertices) { int vID = vertex.getID(); String vName = vertex.getName(); currentNodes.put(vID, vertex); vertexDataModel.addRow(new Object[] { vID, vName }); if(vID > nodeFactory.getLastID()) nodeFactory.setLastID(vID); } }); } private void loadEdges(Graph graph) { ArrayList<Edge> edges = new ArrayList<>(graph.getEdges()); Collections.sort(edges, (Edge e1, Edge e2) -> Integer.compare(e1.getID(), e2.getID())); currentEdges.clear(); SwingUtilities.invokeLater(() -> { edgeDataModel.setRowCount(0); for(Edge edge : edges) { int eID = edge.getID(); double weight = edge.getWeight(); Collection<Node> vertices = graph.getIncidentVertices(edge); String edgeType = graph.getEdgeType(edge).toString(); Node n1, n2; int n1_id, n2_id; Iterator<Node> iter = vertices.iterator(); n1 = iter.next(); n2 = iter.next(); edge.setSourceNode(n1); edge.setDestNode(n2); if(n1 != null) n1_id = n1.getID(); else n1_id = -1; if(n2 != null) n2_id = n2.getID(); else n2_id = -1; currentEdges.put(eID, edge); edgeDataModel.addRow(new Object[] { eID, n1_id, n2_id, weight, edgeType }); if(eID > edgeFactory.getLastID()) edgeFactory.setLastID(eID); } }); } private void addVertex() { VertexAddPanel addPanel = new VertexAddPanel(); int option = JOptionPane.showConfirmDialog(null, addPanel, "Add vertex", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { int id = (int) addPanel.idSpinner.getValue(); if(currentNodes.containsKey(id)) { JOptionPane.showMessageDialog(null, "Vertex already exists"); return; } String name = addPanel.nameField.getText(); Node node = new Node(id, name); currentGraph.addVertex(node); graphPanel.gViewer.repaint(); loadNodes(currentGraph); currentNodes.put(id, node); } } private void editVertex() { Node editNode; Set<Node> selectedVertices = graphPanel.gViewer.getPickedVertexState().getPicked(); if(selectedVertices.size() == 1) editNode = selectedVertices.iterator().next(); else { int[] selectedRows = dataPanel.vertexTable.getSelectedRows(); if(selectedRows.length == 1) { int id = (int) dataPanel.vertexDataModel.getValueAt(selectedRows[0], 0); editNode = currentNodes.get(id); } else { int id = getDialogID("Enter vertex ID to edit", currentNodes); if(id != -1) editNode = currentNodes.get(id); else return; } } VertexAddPanel editPanel = new VertexAddPanel(); editPanel.idSpinner.setValue(editNode.getID()); editPanel.nameField.setText(editNode.getName()); editPanel.idSpinner.setEnabled(false); editPanel.autoCheck.setVisible(false); int option = JOptionPane.showConfirmDialog(null, editPanel, "Edit vertex", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { editNode.setID((int) editPanel.idSpinner.getValue()); editNode.setName(editPanel.nameField.getText()); loadNodes(currentGraph); } } private void removeVertices(Set<Node> vertices) { if(vertices.isEmpty()) return; for(Node node : vertices) { int id = node.getID(); currentNodes.remove(id); currentGraph.removeVertex(node); graphPanel.gViewer.repaint(); loadNodes(currentGraph); } } private void removeVertex() { Set<Node> pickedNodes = graphPanel.gViewer.getPickedVertexState().getPicked(); if(!pickedNodes.isEmpty()) removeVertices(pickedNodes); else { int[] selectedRows = dataPanel.vertexTable.getSelectedRows(); if(selectedRows.length > 0) { Set<Node> selectedNodes = new HashSet<>(); for(int row : selectedRows) { int id = (int) dataPanel.vertexDataModel.getValueAt(row, 0); Node current = currentNodes.get(id); if(current != null) selectedNodes.add(current); } removeVertices(selectedNodes); } else { int id = getDialogID("Enter vertex ID to remove", currentNodes); if(id != -1) { Node removedNode = currentNodes.remove(id); currentGraph.removeVertex(removedNode); loadNodes(currentGraph); graphPanel.gViewer.repaint(); } } } } private void addEdge() { EdgeAddPanel addPanel = new EdgeAddPanel(); int option = JOptionPane.showConfirmDialog(null, addPanel, "Add edge", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { int id = (int) addPanel.idSpinner.getValue(); if(currentEdges.containsKey(id)) { JOptionPane.showMessageDialog(null, "Edge ID already exists"); return; } int fromID = (int) addPanel.fromSpinner.getValue(); int toID = (int) addPanel.toSpinner.getValue(); double weight = (double) addPanel.weightSpinner.getValue(); int eType = addPanel.edgeTypeBox.getSelectedIndex(); EdgeType edgeType = (eType == 0)? EdgeType.UNDIRECTED : EdgeType.DIRECTED; if(currentNodes.containsKey(fromID) && currentNodes.containsKey(toID)) { Edge edge = new Edge(id, weight, edgeType); Node n1 = currentNodes.get(fromID); Node n2 = currentNodes.get(toID); edge.setSourceNode(n1); edge.setDestNode(n2); currentEdges.put(id, edge); currentGraph.addEdge(edge, n1, n2, edgeType); loadEdges(currentGraph); graphPanel.gViewer.repaint(); } else JOptionPane.showMessageDialog(null, "Vertex ID does not exist"); } } private void editEdge() { Edge editEdge; Set<Edge> selectedEdges = graphPanel.gViewer.getPickedEdgeState().getPicked(); if(selectedEdges.size() == 1) editEdge = selectedEdges.iterator().next(); else { int[] selectedRows = dataPanel.edgeTable.getSelectedRows(); if(selectedRows.length == 1) { int id = (int) dataPanel.edgeDataModel.getValueAt(selectedRows[0], 0); editEdge = currentEdges.get(id); } else { int id = getDialogID("Enter edge ID to edit", currentEdges); if(id != -1) editEdge = currentEdges.get(id); else return; } } EdgeAddPanel editPanel = new EdgeAddPanel(); editPanel.idSpinner.setValue(editEdge.getID()); editPanel.fromSpinner.setValue(editEdge.getSourceNode().getID()); editPanel.toSpinner.setValue(editEdge.getDestNode().getID()); editPanel.weightSpinner.setValue(editEdge.getWeight()); editPanel.edgeTypeBox.setSelectedIndex(editEdge.getEdgeType() == EdgeType.UNDIRECTED? 0 : 1); editPanel.fromSpinner.setEnabled(false); editPanel.toSpinner.setEnabled(false); editPanel.idSpinner.setEnabled(false); editPanel.autoCheck.setVisible(false); int option = JOptionPane.showConfirmDialog(null, editPanel, "Edit edge", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { editEdge.setWeight((double) editPanel.weightSpinner.getValue()); editEdge.setEdgeType(editPanel.edgeTypeBox.getSelectedIndex() == 0? EdgeType.UNDIRECTED : EdgeType.DIRECTED); loadEdges(currentGraph); graphPanel.gViewer.repaint(); } } private void removeEdge() { Set<Edge> selectedEdges = graphPanel.gViewer.getPickedEdgeState().getPicked(); if(selectedEdges.isEmpty()) { int[] selectedRows = dataPanel.edgeTable.getSelectedRows(); if(selectedRows.length > 0) { for(int row : selectedRows) { int id = (int) dataPanel.edgeDataModel.getValueAt(row, 0); Edge current = currentEdges.remove(id); currentGraph.removeEdge(current); } } else { int id = getDialogID("Enter edge ID to remove", currentEdges); if(id != -1) { Edge removeEdge = currentEdges.remove(id); currentGraph.removeEdge(removeEdge); } else return; } } else { for(Edge edge : selectedEdges) { currentEdges.remove(edge.getID()); currentGraph.removeEdge(edge); } } loadEdges(currentGraph); graphPanel.gViewer.repaint(); } private int getDialogID(String message, Map collection) { String idStr = JOptionPane.showInputDialog(message); int id = -1; while(idStr != null && id == -1) { try { id = Integer.parseInt(idStr); if(collection.containsKey(id)) break; else { id = -1; JOptionPane.showMessageDialog(null, "ID was not found"); idStr = JOptionPane.showInputDialog(message); } } catch(NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid input found"); idStr = JOptionPane.showInputDialog(message); } } return id; } //-------------------------------------- // VERTEX ADD PANEL //-------------------------------------- private class VertexAddPanel extends JPanel implements ActionListener { private JSpinner idSpinner; private JCheckBox autoCheck; private JTextField nameField; public VertexAddPanel() { setLayout(new MigLayout()); idSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 10000, 1)); autoCheck = new JCheckBox("Auto"); nameField = new JTextField(); autoCheck.setSelected(true); idSpinner.setValue(nodeFactory.getLastID() + 1); idSpinner.setEnabled(false); add(new JLabel("ID ")); add(idSpinner, "width :40:"); add(autoCheck, "wrap"); add(new JLabel("Name: ")); add(nameField, "span 3, width :100:"); autoCheck.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == autoCheck) idSpinner.setEnabled(!autoCheck.isSelected()); } } //-------------------------------------- // EDGE ADD PANEL //-------------------------------------- private class EdgeAddPanel extends JPanel implements ActionListener { private JSpinner idSpinner, fromSpinner, toSpinner, weightSpinner; private JCheckBox autoCheck; private JComboBox edgeTypeBox; public EdgeAddPanel() { setLayout(new MigLayout()); idSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); fromSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); toSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); weightSpinner = new JSpinner(new SpinnerNumberModel(0.0, 0.0, 10000.0, 0.1)); autoCheck = new JCheckBox("Auto"); edgeTypeBox = new JComboBox(); edgeTypeBox.addItem("Undirected"); edgeTypeBox.addItem("Directed"); idSpinner.setValue(edgeFactory.getLastID() + 1); idSpinner.setEnabled(false); autoCheck.setSelected(true); autoCheck.addActionListener(this); add(new JLabel("ID ")); add(idSpinner, "width :40:"); add(autoCheck, "wrap"); add(new JLabel("From vertex ID")); add(fromSpinner, "span 2, width :40:, wrap"); add(new JLabel("To vertex ID")); add(toSpinner, "span 2, width :40:, wrap"); add(new JLabel("Weight")); add(weightSpinner, "span 2, width :70:, wrap"); add(new JLabel("Type")); add(edgeTypeBox, "span 2"); } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == autoCheck) idSpinner.setEnabled(!autoCheck.isSelected()); } } } //-------------------------------------- // GRAPH PANEL //-------------------------------------- private class GraphPanel extends JPanel implements ItemListener, GraphMouseListener { private final VisualizationViewer<Node, Edge> gViewer; private AggregateLayout<Node, Edge> gLayout; private EditingModalGraphMouse mouse; public GraphPanel() { setLayout(new BorderLayout()); gLayout = new AggregateLayout(new FRLayout(currentGraph)); gViewer = new VisualizationViewer<>(gLayout); ScalingControl scaler = new CrossoverScalingControl(); scaler.scale(gViewer, 0.7f, gViewer.getCenter()); gViewer.scaleToLayout(scaler); gViewer.setBackground(Color.WHITE); gViewer.getRenderContext().setVertexFillPaintTransformer(new ObjectFillTransformer<>(gViewer.getPickedVertexState())); gViewer.getRenderContext().setEdgeDrawPaintTransformer(new ObjectFillTransformer(gViewer.getPickedEdgeState())); gViewer.getPickedVertexState().addItemListener(this); gViewer.getPickedEdgeState().addItemListener(this); add(gViewer); mouse = new EditingModalGraphMouse(gViewer.getRenderContext(), nodeFactory, edgeFactory); mouse.setMode(ModalGraphMouse.Mode.PICKING); gViewer.addGraphMouseListener(this); mouse.remove(mouse.getPopupEditingPlugin()); gViewer.setGraphMouse(mouse); } @Override public void graphClicked(Object v, MouseEvent me) {} @Override public void graphPressed(Object v, MouseEvent me) {} @Override public void graphReleased(Object v, MouseEvent me) { if(controlPanel.editCheck.isSelected()) { dataPanel.loadNodes(currentGraph); dataPanel.loadEdges(currentGraph); } } //-------------------------------------- // CENTRALITY TRANSFORMER //-------------------------------------- private class CentralityTransformer implements Transformer<Node, Shape> { List<Node> centralNodes; int numRanks; public CentralityTransformer(List<Node> centralNodes, int numRanks) { this.centralNodes = centralNodes; this.numRanks = numRanks; } @Override public Shape transform(Node node) { for(int i = 0; i < numRanks; i++) { if(node.equals(centralNodes.get(i))) { int size = 20 + ((numRanks - i) * 10); return new Ellipse2D.Double(-10, -10, size, size); } } return new Ellipse2D.Double(-10, -10, 20, 20); } } private void setVertexColour(Color colour, Collection<Node> vertices) { if(vertices == null) vertices = currentGraph.getVertices(); for(Node vertex : vertices) vertex.setFill(colour); gViewer.repaint(); } private void setEdgeColour(Color colour, Collection<Edge> edges) { if(edges == null) edges = currentGraph.getEdges(); for(Edge edge : edges) edge.setFill(colour); gViewer.repaint(); } private void showVertexLabels(boolean show) { gViewer.getRenderContext().setVertexLabelTransformer(new VertexLabelTransformer(show)); gViewer.repaint(); } private void showEdgeLabels(boolean show) { gViewer.getRenderContext().setEdgeLabelTransformer(new EdgeLabelTransformer(show)); gViewer.repaint(); } private void showCluster() { int numRemoved = (int) controlPanel.clusterEdgeRemoveSpinner.getValue(); boolean group = controlPanel.clusterTransformCheck.isSelected(); GraphUtilities.cluster(gLayout, currentGraph, numRemoved, group); gViewer.repaint(); } private void showCentrality() { Map<Node, Double> centrality; if(currentGraph.getVertexCount() <= 1) return; SparseDoubleMatrix2D matrix = GraphMatrixOperations.graphToSparseMatrix(currentGraph); int selectedCentrality = controlPanel.centralityTypeBox.getSelectedIndex(); boolean transform = controlPanel.centralityMorphCheck.isSelected(); String prefix; switch(selectedCentrality) { case 0: centrality = MatrixTools.getScores(MatrixTools.powerIterationFull(matrix), currentGraph); prefix = "EigenVector"; break; case 1: centrality = MatrixTools.getScores(MatrixTools.pageRankPI(matrix), currentGraph); prefix = "PageRank"; break; /* case 2: centrality = new ClosenessCentrality(currentGraph, new WeightTransformer()); prefix = "Closeness"; break; case 3: centrality = new BetweennessCentrality(currentGraph, new WeightTransformer()); prefix = "Betweenness"; break; */ default: return; } Collection<Node> vertices = currentGraph.getVertices(); PriorityQueue<SimpleEntry<Node, Double>> scores = null; if(transform) { scores = new PriorityQueue<>((SimpleEntry<Node, Double> a1, SimpleEntry<Node, Double> a2) -> Double.compare(a2.getValue(), a1.getValue())); } for(Node node : vertices) { double score = centrality.get(node); String output = MessageFormat.format("({0}) Vertex: {1}, Score: {2}", prefix, node.getID(), score); sendToOutput(output); if(transform) scores.add(new SimpleEntry(node, score)); } if(transform) { ArrayList<Node> centralNodes = new ArrayList<>(); Color[] centralColours = new Color[] { Color.RED, Color.ORANGE, Color.BLUE }; for(int i = 0; i < 3; i++) { SimpleEntry<Node, Double> entry = scores.poll(); centralNodes.add(entry.getKey()); entry.getKey().setFill(centralColours[i]); } graphPanel.gViewer.getRenderContext().setVertexShapeTransformer(new CentralityTransformer(centralNodes, 3)); graphPanel.gViewer.repaint(); } } private void reloadGraph() { gLayout.removeAll(); gLayout.setGraph(currentGraph); gViewer.repaint(); dataPanel.loadNodes(currentGraph); dataPanel.loadEdges(currentGraph); } private void resetGraph() { currentGraph = new SparseMultigraph<>(); reloadGraph(); } @Override public void itemStateChanged(ItemEvent e) { if(controlPanel.selectCheck.isSelected()) { selectedItems = e.getItemSelectable().getSelectedObjects(); controlPanel.updateSelectedComponents(); } } } //-------------------------------------- // OUTPUT PANEL //-------------------------------------- private class OutputPanel extends JPanel { private JTextArea outputArea; public OutputPanel() { setLayout(new BorderLayout()); outputArea = new JTextArea(""); outputArea.setBackground(Color.WHITE); outputArea.setEditable(false); JScrollPane outputScroller = new JScrollPane(outputArea); outputScroller.setPreferredSize(new Dimension(650, 565)); outputScroller.setBorder(null); add(outputScroller); } private void clearLog() { outputArea.setText(""); } } } }
Updated ControlPanel layout
src/com/graphi/display/LayoutPanel.java
Updated ControlPanel layout
Java
mit
e6af8de17ff69c81a3ba431897fa081617228533
0
seqcode/seqcode-core,seqcode/seqcode-core,seqcode/seqcode-core,seqcode/seqcode-core
package edu.psu.compbio.seqcode.projects.akshay.chexmix.datasets; import java.io.*; import java.util.*; import edu.psu.compbio.seqcode.projects.akshay.chexmix.analysis.LoadTags; import edu.psu.compbio.seqcode.projects.akshay.chexmix.utils.*; public class BindingLocation { /** * seqpos and seqneg are Seq (edu.psu.compbio.seqcode.projects.akshay.chexmix.datasets.Seq) objects that contain the "+" and the "-" strand sequences * for the given bindinglocation */ public Seq seqpos; public Seq seqneg; /** * vecpos and vecneg are Vec objects (edu.psu.compbio.seqcode.projects.akshay.chexmix.datasets.Vec) that contain the tags/reads in the "+" and "-" strands */ public Vec vecpos; public Vec vecneg; /** * the chromosome (chr7, chr8 ..) in which the current bindinglocation falls */ private String chr; /** * the midpoint (the actual genomic coordinate) of the current binding location */ private int midpoint; /** * the range of the current binding location (the actual size of the location is 2*range) */ private int range; /** * the first element of this list is the start coordinate of the binding locaiton (inclusive) * the second element of this list is the end coordinate of the binding location (not inclusive) */ private List<Integer> coords = new ArrayList<Integer>(); /** * The only constructor for this class * @param midpoint * @param chr * @param range */ public BindingLocation(int midpoint, String chr, Config conf) { this.chr = chr; this.midpoint = midpoint; int start = midpoint - range; int end = midpoint + range; this.coords.add(start); this.coords.add(end); this.range = conf.getBlsize(); } @Override public boolean equals(Object obj){ if(obj == this){ return true; } BindingLocation bl = (BindingLocation) obj; return this.midpoint == bl.midpoint && this.chr == bl.chr && this.range == bl.range; } @Override public int hashCode(){ int result = 17; int code = (int) this.range; code+= (int) this.midpoint; code += (int) (this.chr == null ? 0 :this.chr.hashCode()); result = result*37 + code; return result; } /** * This mehods fills the seqpos and seqneg objects. Should be called only if you need to work with the sequences. * @param genome * @throws IOException */ public void fillSeqs(Config conf) throws IOException{ if(conf.genome_name == "hg19"){ QueryHg19 seqloader = new QueryHg19(this.chr,this.midpoint, this.range); seqloader.fillGenomePath(); this.seqpos = seqloader.getSeq("+"); this.seqneg = seqloader.getSeq("-"); } if(conf.genome_name == "mm9"){ QueryMm9 seqloader = new QueryMm9(this.chr,this.midpoint,this.range); seqloader.fillGenomePath(); this.seqpos = seqloader.getSeq("+"); this.seqneg = seqloader.getSeq("-"); } if(conf.genome_name == "mm10"){ QueryMm10 seqloader = new QueryMm10(this.chr,this.midpoint,this.range); seqloader.fillGenomePath(); this.seqpos = seqloader.getSeq("+"); this.seqneg = seqloader.getSeq("-"); } } /** * This method fills the vecpos and vecneg objects. Should be called only if you want to work with tags/tag distribution * @param loader (LoadTags class object should be initiated first (it stores all the tags in a 3-d array format, see that class for more details)) */ public void filltags(LoadTags loader){ QueryTags tagsfetcher = new QueryTags(this.midpoint,this.range, this.chr); this.vecpos = tagsfetcher.getTags(loader, "+"); this.vecneg = tagsfetcher.getTags(loader, "-"); } /** * Compares to the current binding location with the given binding location for all possible offsets and reversals and returns the offset and reversal that * gives the most highest similarity score for both binding locations. * This method is only used while constructing the seed profile * @param givenBL * @param range * @param smoothsize * @return (Returns a custom object(edu.psu.compbio.seqcode.projects.akshay.chexmix.datasets.CustomReturn). maxvec1 in the return object is the offset * and reversal that yields the maximum similarity in the current binding location. maxvec2 is for the given binding location) */ public CustomReturn scanBlWithBl(BindingLocation givenBL,int range, int smoothsize){ Vec maxVec1=null; Vec maxVec2=null; double pcc = -2.0; List<Integer> thisvec = this.getListMidpoints(range); List<Integer> givenvec = givenBL.getListMidpoints(range); for(int i=0; i<thisvec.size(); i++){ for(int j=0; j<givenvec.size(); j++){ List<Integer> first = this.getConcatenatedTags(thisvec.get(i), range, "+", smoothsize); List<Integer> second = givenBL.getConcatenatedTags(givenvec.get(j), range, "+", smoothsize); Pearson pccdriver = new Pearson(first,second); double temppcc = pccdriver.doComparision(); if(temppcc>pcc ){ pcc=temppcc; maxVec1= this.getSubVec(thisvec.get(i), range, "+", smoothsize); maxVec2= givenBL.getSubVec(givenvec.get(j), range, "+", smoothsize); } first = this.getConcatenatedTags(thisvec.get(i), range, "+", smoothsize); second = givenBL.getConcatenatedTags(givenvec.get(j),range, "-", smoothsize); pccdriver = new Pearson(first,second); temppcc = pccdriver.doComparision(); if(temppcc>pcc ){ System.out.println(pcc); maxVec1= this.getSubVec(thisvec.get(i), range, "+", smoothsize); maxVec2= givenBL.getSubVec(givenvec.get(j), range, "-", smoothsize); } first = this.getConcatenatedTags(thisvec.get(i), range, "-", smoothsize); second = givenBL.getConcatenatedTags(givenvec.get(j), range, "+", smoothsize); pccdriver = new Pearson(first,second); temppcc = pccdriver.doComparision(); if(temppcc>pcc ){ System.out.println(pcc); maxVec1= this.getSubVec(thisvec.get(i), range, "-", smoothsize); maxVec2= givenBL.getSubVec(givenvec.get(j), range, "+", smoothsize); } first = this.getConcatenatedTags(thisvec.get(i),range, "-", smoothsize); second = givenBL.getConcatenatedTags(givenvec.get(j), range, "-", smoothsize); pccdriver = new Pearson(first,second); temppcc = pccdriver.doComparision(); if(temppcc>pcc ){ pcc=temppcc; maxVec1= this.getSubVec(thisvec.get(i), range, "-", smoothsize); maxVec2= givenBL.getSubVec(givenvec.get(j), range, "-", smoothsize); } } } CustomReturn ret = new CustomReturn(pcc,maxVec1,maxVec2); return ret; } /** * Given a vec (characterised by midpoint, range and orientation) in givenbl, this method finds a vector in the current BL that has the maximum similarity. * This method is used by scheme 1 for building the seed profile * @param givenbl * @param midpoint * @param orientation * @param range * @param smoothsize * @return */ public CustomReturn scanVecWithBl(BindingLocation givenbl, int midpoint, String orientation, int range, int smoothsize){ List<Integer> first = givenbl.getConcatenatedTags(midpoint, range, orientation, smoothsize); List<Integer> thisvec = this.getListMidpoints(range); double maxpcc=-2.0; Vec maxvec = null; for(int i=0; i<thisvec.size(); i++){ List<Integer> second = this.getConcatenatedTags(thisvec.get(i), range, "+", smoothsize); Pearson pcccalculater = new Pearson(first, second); double pcc = pcccalculater.doComparision(); if(pcc>maxpcc){ maxpcc = pcc; maxvec = this.getSubVec(thisvec.get(i), range, "+", smoothsize); } second = this.getConcatenatedTags(thisvec.get(i), range, "-", smoothsize); pcccalculater = new Pearson(first, second); pcc = pcccalculater.doComparision(); if(pcc>maxpcc){ maxpcc = pcc; maxvec = this.getSubVec(thisvec.get(i), range, "-", smoothsize); } } CustomReturn ret = new CustomReturn(maxpcc, maxvec); return ret; } /** * * @param tags * @param smoothsize * @return */ public CustomReturn scanConcVecWithBl(int[] tags, int range, int smoothsize){ List<Integer> first = new ArrayList<Integer>(); for(int j=0; j< tags.length; j++){ first.add(tags[j]); } List<Integer> thisvec = this.getListMidpoints(range); double maxpcc=-2.0; Vec maxvec = null; for(int i=0; i<thisvec.size(); i++){ List<Integer> second = this.getConcatenatedTags(thisvec.get(i), range, "+", smoothsize); Pearson pcccalculater = new Pearson(first, second); double pcc = pcccalculater.doComparision(); if(pcc>maxpcc){ maxpcc = pcc; maxvec = this.getSubVec(thisvec.get(i), range, "+", smoothsize); } second = this.getConcatenatedTags(thisvec.get(i), range, "-", smoothsize); pcccalculater = new Pearson(first, second); pcc = pcccalculater.doComparision(); if(pcc>maxpcc){ maxpcc = pcc; maxvec = this.getSubVec(thisvec.get(i), range, "-", smoothsize); } } CustomReturn ret = new CustomReturn(maxpcc, maxvec); return ret; } // Accessors /** * Given a midpoint and range and orientaton, the methods returns the seq object if it is a subsequence of the current binding location * @param midpoint * @param orientation * @param range * @return */ public Seq getSubSeq(int midpoint, String orientation, int range){ Seq ret = null; if(orientation == "+"){ ret = seqpos.getSub(midpoint, range); } else{ ret = seqneg.getSub(midpoint, range); } return ret; } /** * Returns a concatenated integer list of tags for a given list of input paramenters * @param midpoint * @param chr * @param range * @param Orientation * @param smoothsize * @return */ public List<Integer> getConcatenatedTags(int midpoint, int range, String Orientation, int smoothsize){ List<Integer> ret = new ArrayList<Integer>(); if(Orientation == "+"){ Vec temp = this.getSubVec(midpoint, range, Orientation, smoothsize); Vec rev = this.getSubVec(midpoint, range, "-", smoothsize); List<Integer> tempvalues = new ArrayList<Integer>(temp.tags.values()); List<Integer> revvalues = new ArrayList<Integer>(rev.tags.values()); for(int i =0; i<tempvalues.size(); i++){ ret.add(tempvalues.get(i)); } for(int i= revvalues.size()-1;i>=0 ;i--){ ret.add(revvalues.get(i)); } } if(Orientation == "-"){ Vec temp = this.getSubVec(midpoint, range, Orientation, smoothsize); Vec rev = this.getSubVec(midpoint, range, "+", smoothsize); List<Integer> tempvalues = new ArrayList<Integer>(temp.tags.values()); List<Integer> revvalues = new ArrayList<Integer>(rev.tags.values()); for(int i=revvalues.size()-1;i>=0;i--){ ret.add(revvalues.get(i)); } for(int i=0; i< tempvalues.size(); i++){ ret.add(tempvalues.get(i)); } } return ret; } /** * Returns the vec object for a given input paraments. * It is important to note that this method does not concatenate the tags from both strands. Use getConcatenatedTags to achieve that * @param midpoint * @param range * @param orientation * @param smoothsize * @return */ public Vec getSubVec(int midpoint, int range, String orientation, int smoothsize){ Vec ret = null; if(smoothsize > 0){ if(orientation=="+"){ Smoothing smoo = new Smoothing(); Vec tempret = smoo.doSmoothing(this.vecpos, smoothsize); ret = tempret.getSub(midpoint, range); } if(orientation =="-"){ Smoothing smoo = new Smoothing(); Vec tempret = smoo.doSmoothing(this.vecneg, smoothsize); ret = tempret.getSub(midpoint, range); } } else{ if(orientation=="+"){ ret = vecpos.getSub(midpoint, range); } if(orientation == "-"){ ret =vecneg.getSub(midpoint, range); } } return ret; } /** * returns the name of the current binding location * eg: chr8:777878, where 777878 is the midpoint and the chr7 is the chromosome * @return */ public String getName(){ return this.chr+":"+this.midpoint; } /** * gives the list of vec objects that are a subset of the given binding location * @param range * @param orientation * @param smoothsize * @return */ public List<Vec> getListSubVec(int range, String orientation, int smoothsize){ List<Vec> ret = new ArrayList<Vec>(); for(int i=this.coords.get(0)+range; i<this.coords.get(1)-range; i++){ Vec temp = this.getSubVec(i, range, orientation, smoothsize); ret.add(temp); } return ret; } /** * Similar to getListSubVec but just returns the list of midpoints. * @param range * @return */ public List<Integer> getListMidpoints(int range){ List<Integer> ret = new ArrayList<Integer>(); for(int i=this.coords.get(0)+range; i< this.coords.get(1)-range; i++){ ret.add(i); } return ret; } }
src/edu/psu/compbio/seqcode/projects/akshay/chexmix/datasets/BindingLocation.java
package edu.psu.compbio.seqcode.projects.akshay.chexmix.datasets; import java.io.*; import java.util.*; import edu.psu.compbio.seqcode.projects.akshay.chexmix.analysis.LoadTags; import edu.psu.compbio.seqcode.projects.akshay.chexmix.utils.*; public class BindingLocation { /** * seqpos and seqneg are Seq (edu.psu.compbio.seqcode.projects.akshay.chexmix.datasets.Seq) objects that contain the "+" and the "-" strand sequences * for the given bindinglocation */ public Seq seqpos; public Seq seqneg; /** * vecpos and vecneg are Vec objects (edu.psu.compbio.seqcode.projects.akshay.chexmix.datasets.Vec) that contain the tags/reads in the "+" and "-" strands */ public Vec vecpos; public Vec vecneg; /** * the chromosome (chr7, chr8 ..) in which the current bindinglocation falls */ private String chr; /** * the midpoint (the actual genomic coordinate) of the current binding location */ private int midpoint; /** * the range of the current binding location (the actual size of the location is 2*range) */ private int range; /** * the first element of this list is the start coordinate of the binding locaiton (inclusive) * the second element of this list is the end coordinate of the binding location (not inclusive) */ private List<Integer> coords = new ArrayList<Integer>(); /** * The only constructor for this class * @param midpoint * @param chr * @param range */ public BindingLocation(int midpoint, String chr, Config conf) { this.chr = chr; this.midpoint = midpoint; int start = midpoint - range; int end = midpoint + range; this.coords.add(start); this.coords.add(end); this.range = conf.getBlsize(); } @Override public boolean equals(Object obj){ if(obj == this){ return true; } BindingLocation bl = (BindingLocation) obj; return this.midpoint == bl.midpoint && this.chr == bl.chr && this.range == bl.range; } @Override public int hashCode(){ int result = 17; int code = (int) this.range; code+= (int) this.midpoint; code += (int) (this.chr == null ? 0 :this.chr.hashCode()); result = result*37 + code; return result; } /** * This mehods fills the seqpos and seqneg objects. Should be called only if you need to work with the sequences. * @param genome * @throws IOException */ public void fillSeqs(Config conf) throws IOException{ if(conf.genome_name == "hg19"){ QueryHg19 seqloader = new QueryHg19(this.chr,this.midpoint, this.range); seqloader.fillGenomePath(); this.seqpos = seqloader.getSeq("+"); this.seqneg = seqloader.getSeq("-"); } if(conf.genome_name == "mm9"){ QueryMm9 seqloader = new QueryMm9(this.chr,this.midpoint,this.range); seqloader.fillGenomePath(); this.seqpos = seqloader.getSeq("+"); this.seqneg = seqloader.getSeq("-"); } if(conf.genome_name == "mm10"){ QueryMm10 seqloader = new QueryMm10(this.chr,this.midpoint,this.range); seqloader.fillGenomePath(); this.seqpos = seqloader.getSeq("+"); this.seqneg = seqloader.getSeq("-"); } } /** * This method fills the vecpos and vecneg objects. Should be called only if you want to work with tags/tag distribution * @param loader (LoadTags class object should be initiated first (it stores all the tags in a 3-d array format, see that class for more details)) */ public void filltags(LoadTags loader){ QueryTags tagsfetcher = new QueryTags(this.midpoint,this.range, this.chr); this.vecpos = tagsfetcher.getTags(loader, "+"); this.vecneg = tagsfetcher.getTags(loader, "-"); } /** * Compares to the current binding location with the given binding location for all possible offsets and reversals and returns the offset and reversal that * gives the most highest similarity score for both binding locations. * This method is only used while constructing the seed profile * @param givenBL * @param range * @param smoothsize * @return (Returns a custom object(edu.psu.compbio.seqcode.projects.akshay.chexmix.datasets.CustomReturn). maxvec1 in the return object is the offset * and reversal that yields the maximum similarity in the current binding location. maxvec2 is for the given binding location) */ public CustomReturn scanBlWithBl(BindingLocation givenBL,int range, int smoothsize){ Vec maxVec1=null; Vec maxVec2=null; double pcc = -2.0; List<Integer> thisvec = this.getListMidpoints(range); List<Integer> givenvec = givenBL.getListMidpoints(range); for(int i=0; i<thisvec.size(); i++){ for(int j=0; j<givenvec.size(); j++){ List<Integer> first = this.getConcatenatedTags(thisvec.get(i), range, "+", smoothsize); List<Integer> second = givenBL.getConcatenatedTags(givenvec.get(j), range, "+", smoothsize); Pearson pccdriver = new Pearson(first,second); double temppcc = pccdriver.doComparision(); if(temppcc>pcc ){ pcc=temppcc; // debuggining lines System.out.println(pcc); maxVec1= this.getSubVec(thisvec.get(i), range, "+", smoothsize); maxVec2= givenBL.getSubVec(givenvec.get(j), range, "+", smoothsize); } first = this.getConcatenatedTags(thisvec.get(i), range, "+", smoothsize); second = givenBL.getConcatenatedTags(givenvec.get(j),range, "-", smoothsize); pccdriver = new Pearson(first,second); temppcc = pccdriver.doComparision(); if(temppcc>pcc ){ pcc=temppcc; // debuggining lines System.out.println(pcc); maxVec1= this.getSubVec(thisvec.get(i), range, "+", smoothsize); maxVec2= givenBL.getSubVec(givenvec.get(j), range, "-", smoothsize); } first = this.getConcatenatedTags(thisvec.get(i), range, "-", smoothsize); second = givenBL.getConcatenatedTags(givenvec.get(j), range, "+", smoothsize); pccdriver = new Pearson(first,second); temppcc = pccdriver.doComparision(); if(temppcc>pcc ){ pcc=temppcc; // debuggining lines System.out.println(pcc); maxVec1= this.getSubVec(thisvec.get(i), range, "-", smoothsize); maxVec2= givenBL.getSubVec(givenvec.get(j), range, "+", smoothsize); } first = this.getConcatenatedTags(thisvec.get(i),range, "-", smoothsize); second = givenBL.getConcatenatedTags(givenvec.get(j), range, "-", smoothsize); pccdriver = new Pearson(first,second); temppcc = pccdriver.doComparision(); if(temppcc>pcc ){ pcc=temppcc; // debuggining lines System.out.println(pcc); maxVec1= this.getSubVec(thisvec.get(i), range, "-", smoothsize); maxVec2= givenBL.getSubVec(givenvec.get(j), range, "-", smoothsize); } } } CustomReturn ret = new CustomReturn(pcc,maxVec1,maxVec2); return ret; } /** * Given a vec (characterised by midpoint, range and orientation) in givenbl, this method finds a vector in the current BL that has the maximum similarity. * This method is used by scheme 1 for building the seed profile * @param givenbl * @param midpoint * @param orientation * @param range * @param smoothsize * @return */ public CustomReturn scanVecWithBl(BindingLocation givenbl, int midpoint, String orientation, int range, int smoothsize){ List<Integer> first = givenbl.getConcatenatedTags(midpoint, range, orientation, smoothsize); List<Integer> thisvec = this.getListMidpoints(range); double maxpcc=-2.0; Vec maxvec = null; for(int i=0; i<thisvec.size(); i++){ List<Integer> second = this.getConcatenatedTags(thisvec.get(i), range, "+", smoothsize); Pearson pcccalculater = new Pearson(first, second); double pcc = pcccalculater.doComparision(); if(pcc>maxpcc){ maxpcc = pcc; maxvec = this.getSubVec(thisvec.get(i), range, "+", smoothsize); } second = this.getConcatenatedTags(thisvec.get(i), range, "-", smoothsize); pcccalculater = new Pearson(first, second); pcc = pcccalculater.doComparision(); if(pcc>maxpcc){ maxpcc = pcc; maxvec = this.getSubVec(thisvec.get(i), range, "-", smoothsize); } } CustomReturn ret = new CustomReturn(maxpcc, maxvec); return ret; } /** * * @param tags * @param smoothsize * @return */ public CustomReturn scanConcVecWithBl(int[] tags, int range, int smoothsize){ List<Integer> first = new ArrayList<Integer>(); for(int j=0; j< tags.length; j++){ first.add(tags[j]); } List<Integer> thisvec = this.getListMidpoints(range); double maxpcc=-2.0; Vec maxvec = null; for(int i=0; i<thisvec.size(); i++){ List<Integer> second = this.getConcatenatedTags(thisvec.get(i), range, "+", smoothsize); Pearson pcccalculater = new Pearson(first, second); double pcc = pcccalculater.doComparision(); if(pcc>maxpcc){ maxpcc = pcc; maxvec = this.getSubVec(thisvec.get(i), range, "+", smoothsize); } second = this.getConcatenatedTags(thisvec.get(i), range, "-", smoothsize); pcccalculater = new Pearson(first, second); pcc = pcccalculater.doComparision(); if(pcc>maxpcc){ maxpcc = pcc; maxvec = this.getSubVec(thisvec.get(i), range, "-", smoothsize); } } CustomReturn ret = new CustomReturn(maxpcc, maxvec); return ret; } // Accessors /** * Given a midpoint and range and orientaton, the methods returns the seq object if it is a subsequence of the current binding location * @param midpoint * @param orientation * @param range * @return */ public Seq getSubSeq(int midpoint, String orientation, int range){ Seq ret = null; if(orientation == "+"){ ret = seqpos.getSub(midpoint, range); } else{ ret = seqneg.getSub(midpoint, range); } return ret; } /** * Returns a concatenated integer list of tags for a given list of input paramenters * @param midpoint * @param chr * @param range * @param Orientation * @param smoothsize * @return */ public List<Integer> getConcatenatedTags(int midpoint, int range, String Orientation, int smoothsize){ List<Integer> ret = new ArrayList<Integer>(); if(Orientation == "+"){ Vec temp = this.getSubVec(midpoint, range, Orientation, smoothsize); Vec rev = this.getSubVec(midpoint, range, "-", smoothsize); List<Integer> tempvalues = new ArrayList<Integer>(temp.tags.values()); List<Integer> revvalues = new ArrayList<Integer>(rev.tags.values()); for(int i =0; i<tempvalues.size(); i++){ ret.add(tempvalues.get(i)); } for(int i= revvalues.size()-1;i>=0 ;i--){ ret.add(revvalues.get(i)); } } if(Orientation == "-"){ Vec temp = this.getSubVec(midpoint, range, Orientation, smoothsize); Vec rev = this.getSubVec(midpoint, range, "+", smoothsize); List<Integer> tempvalues = new ArrayList<Integer>(temp.tags.values()); List<Integer> revvalues = new ArrayList<Integer>(rev.tags.values()); for(int i=revvalues.size()-1;i>=0;i--){ ret.add(revvalues.get(i)); } for(int i=0; i< tempvalues.size(); i++){ ret.add(tempvalues.get(i)); } } return ret; } /** * Returns the vec object for a given input paraments. * It is important to note that this method does not concatenate the tags from both strands. Use getConcatenatedTags to achieve that * @param midpoint * @param range * @param orientation * @param smoothsize * @return */ public Vec getSubVec(int midpoint, int range, String orientation, int smoothsize){ Vec ret = null; if(smoothsize > 0){ if(orientation=="+"){ Smoothing smoo = new Smoothing(); Vec tempret = smoo.doSmoothing(this.vecpos, smoothsize); ret = tempret.getSub(midpoint, range); } if(orientation =="-"){ Smoothing smoo = new Smoothing(); Vec tempret = smoo.doSmoothing(this.vecneg, smoothsize); ret = tempret.getSub(midpoint, range); } } else{ if(orientation=="+"){ ret = vecpos.getSub(midpoint, range); } if(orientation == "-"){ ret =vecneg.getSub(midpoint, range); } } return ret; } /** * returns the name of the current binding location * eg: chr8:777878, where 777878 is the midpoint and the chr7 is the chromosome * @return */ public String getName(){ return this.chr+":"+this.midpoint; } /** * gives the list of vec objects that are a subset of the given binding location * @param range * @param orientation * @param smoothsize * @return */ public List<Vec> getListSubVec(int range, String orientation, int smoothsize){ List<Vec> ret = new ArrayList<Vec>(); for(int i=this.coords.get(0)+range; i<this.coords.get(1)-range; i++){ Vec temp = this.getSubVec(i, range, orientation, smoothsize); ret.add(temp); } return ret; } /** * Similar to getListSubVec but just returns the list of midpoints. * @param range * @return */ public List<Integer> getListMidpoints(int range){ List<Integer> ret = new ArrayList<Integer>(); for(int i=this.coords.get(0)+range; i< this.coords.get(1)-range; i++){ ret.add(i); } return ret; } }
debugging
src/edu/psu/compbio/seqcode/projects/akshay/chexmix/datasets/BindingLocation.java
debugging
Java
mit
f3611055a7d1a273bff88a0dc3c4681771c8eb95
0
jbosboom/streamjit,jbosboom/streamjit
package edu.mit.streamjit.impl.distributed; import com.google.common.collect.ImmutableList; import edu.mit.streamjit.impl.blob.AbstractReadOnlyBuffer; import edu.mit.streamjit.impl.blob.Buffer; import edu.mit.streamjit.impl.common.AbstractDrainer; import edu.mit.streamjit.impl.distributed.common.TCPConnection.TCPConnectionInfo; import edu.mit.streamjit.impl.distributed.common.TCPConnection.TCPConnectionProvider; import edu.mit.streamjit.impl.distributed.node.TCPOutputChannel; /** * Head Channel is just a wrapper to TCPOutputChannel that skips * fillUnprocessedData. * * @author Sumanan [email protected] * @since Oct 21, 2013 */ public class HeadChannel extends TCPOutputChannel { public HeadChannel(Buffer buffer, TCPConnectionProvider conProvider, TCPConnectionInfo conInfo, String bufferTokenName, int debugPrint) { super(buffer, conProvider, conInfo, bufferTokenName, debugPrint); } protected void fillUnprocessedData() { this.unProcessedData = ImmutableList.of(); } /** * Head HeadBuffer is just a wrapper to to a buffer that triggers final * draining process if it finds out that there is no more data in the * buffer. This is need for non manual inputs. * * @author Sumanan [email protected] * @since Oct 2, 2013 */ public static class HeadBuffer extends AbstractReadOnlyBuffer { Buffer buffer; AbstractDrainer drainer; public HeadBuffer(Buffer buffer, AbstractDrainer drainer) { this.buffer = buffer; this.drainer = drainer; } // TODO: Need to optimise the buffer reading. I will come back here // later. @Override public Object read() { Object o = buffer.read(); if (buffer.size() == 0) { new DrainerThread().start(); } return o; } @Override public int size() { return buffer.size(); } class DrainerThread extends Thread { DrainerThread() { super("DrainerThread"); } public void run() { System.out.println("Input data finished"); drainer.startDraining(2); } } } }
src/edu/mit/streamjit/impl/distributed/HeadChannel.java
package edu.mit.streamjit.impl.distributed; import com.google.common.collect.ImmutableList; import edu.mit.streamjit.impl.blob.AbstractReadOnlyBuffer; import edu.mit.streamjit.impl.blob.Buffer; import edu.mit.streamjit.impl.common.AbstractDrainer; import edu.mit.streamjit.impl.distributed.common.TCPConnection.TCPConnectionInfo; import edu.mit.streamjit.impl.distributed.common.TCPConnection.TCPConnectionProvider; import edu.mit.streamjit.impl.distributed.node.TCPOutputChannel; /** * Head Channel is just a wrapper to TCPOutputChannel that skips * fillUnprocessedData. * * @author Sumanan [email protected] * @since Oct 21, 2013 */ public class HeadChannel extends TCPOutputChannel { public HeadChannel(Buffer buffer, TCPConnectionProvider conProvider, TCPConnectionInfo conInfo, String bufferTokenName, int debugPrint) { super(buffer, conProvider, conInfo, bufferTokenName, debugPrint); } protected void fillUnprocessedData() { this.unProcessedData = ImmutableList.of(); } /** * Head HeadBuffer is just a wrapper to to a buffer that triggers final * draining process if it finds out that there is no more data in the * buffer. This is need for non manual inputs. * * @author Sumanan [email protected] * @since Oct 2, 2013 */ public static class HeadBuffer extends AbstractReadOnlyBuffer { Buffer buffer; AbstractDrainer drainer; public HeadBuffer(Buffer buffer, AbstractDrainer drainer) { this.buffer = buffer; this.drainer = drainer; } // TODO: Need to optimise the buffer reading. I will come back here // later. @Override public Object read() { Object o = buffer.read(); if (buffer.size() == 0) { new DrainerThread().start(); } return o; } @Override public int size() { return buffer.size(); } class DrainerThread extends Thread { DrainerThread() { super("DrainerThread"); } public void run() { drainer.startDraining(2); } } } }
Print message added
src/edu/mit/streamjit/impl/distributed/HeadChannel.java
Print message added
Java
lgpl-2.1
9d6f6f379fb282df0339fd584c6a40a151dd26ba
0
deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.metadata.persistence.iso.parsing.inspectation; import static org.slf4j.LoggerFactory.getLogger; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import org.apache.axiom.om.OMElement; import org.deegree.commons.xml.NamespaceBindings; import org.deegree.commons.xml.XMLAdapter; import org.deegree.commons.xml.XPath; import org.deegree.metadata.i18n.Messages; import org.deegree.metadata.persistence.MetadataInspectorException; import org.deegree.metadata.persistence.iso.generating.generatingelements.GenerateOMElement; import org.deegree.metadata.persistence.iso.parsing.IdUtils; import org.deegree.metadata.persistence.iso19115.jaxb.FileIdentifierInspector; import org.slf4j.Logger; /** * Inspects whether the fileIdentifier should be set when inserting a metadata or not and what consequences should * occur. * * @author <a href="mailto:[email protected]">Steffen Thomas</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class FIInspector implements RecordInspector { private static final Logger LOG = getLogger( FIInspector.class ); private Connection conn; private final XMLAdapter a; private final FileIdentifierInspector config; public FIInspector( FileIdentifierInspector inspector ) { this.config = inspector; this.a = new XMLAdapter(); } /** * * @param fi * the fileIdentifier that should be determined for one metadata, can be <Code>null</Code>. * @param rsList * the list of resourceIdentifier, not <Code>null</Code>. * @param id * the id-attribute, can be <Code>null<Code>. * @param uuid * the uuid-attribure, can be <Code>null</Code>. * @return the new fileIdentifier. */ private List<String> determineFileIdentifier( String[] fi, List<String> rsList, String id, String uuid ) throws MetadataInspectorException { List<String> idList = new ArrayList<String>(); if ( fi.length != 0 ) { for ( String f : fi ) { LOG.info( Messages.getMessage( "INFO_FI_AVAILABLE", f.trim() ) ); idList.add( f.trim() ); } return idList; } if ( config != null && !config.isRejectEmpty() ) { if ( rsList.size() == 0 && id == null && uuid == null ) { LOG.debug( Messages.getMessage( "INFO_FI_GENERATE_NEW" ) ); idList.add( IdUtils.newInstance( conn ).generateUUID() ); LOG.debug( Messages.getMessage( "INFO_FI_NEW", idList ) ); } else { if ( rsList.size() == 0 && id != null ) { LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_ID", id ) ); idList.add( id ); } else if ( rsList.size() == 0 && uuid != null ) { LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_UUID", uuid ) ); idList.add( uuid ); } else { LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_RSID", rsList.get( 0 ) ) ); idList.add( rsList.get( 0 ) ); } } return idList; } if ( rsList.size() == 0 ) { String msg = Messages.getMessage( "ERROR_REJECT_FI" ); LOG.debug( msg ); throw new MetadataInspectorException( msg ); } LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_RSID", rsList.get( 0 ) ) ); idList.add( rsList.get( 0 ) ); return idList; } @Override public OMElement inspect( OMElement record, Connection conn ) throws MetadataInspectorException { this.conn = conn; a.setRootElement( record ); NamespaceBindings nsContext = a.getNamespaceContext( record ); // NamespaceContext newNSC = generateNSC(nsContext); nsContext.addNamespace( "srv", "http://www.isotc211.org/2005/srv" ); nsContext.addNamespace( "gmd", "http://www.isotc211.org/2005/gmd" ); nsContext.addNamespace( "gco", "http://www.isotc211.org/2005/gco" ); // String GMD_PRE = "gmd"; String[] fileIdentifierString = a.getNodesAsStrings( record, new XPath( "./gmd:fileIdentifier/gco:CharacterString", nsContext ) ); OMElement sv_service_OR_md_dataIdentification = a.getElement( record, new XPath( "./gmd:identificationInfo/srv:SV_ServiceIdentification | ./gmd:identificationInfo/gmd:MD_DataIdentification", nsContext ) ); String dataIdentificationId = sv_service_OR_md_dataIdentification.getAttributeValue( new QName( "id" ) ); String dataIdentificationUuId = sv_service_OR_md_dataIdentification.getAttributeValue( new QName( "uuid" ) ); List<OMElement> identifier = a.getElements( sv_service_OR_md_dataIdentification, new XPath( "./gmd:citation/gmd:CI_Citation/gmd:identifier", nsContext ) ); List<String> resourceIdentifierList = new ArrayList<String>(); for ( OMElement resourceElement : identifier ) { String resourceIdentifier = a.getNodeAsString( resourceElement, new XPath( "./gmd:MD_Identifier/gmd:code/gco:CharacterString | ./gmd:RS_Identifier/gmd:code/gco:CharacterString", nsContext ), null ); LOG.debug( "resourceIdentifier: '" + resourceIdentifier + "' " ); resourceIdentifierList.add( resourceIdentifier ); } List<String> idList = determineFileIdentifier( fileIdentifierString, resourceIdentifierList, dataIdentificationId, dataIdentificationUuId ); // if ( idList.isEmpty() ) { // return null; // } if ( !idList.isEmpty() && fileIdentifierString.length == 0 ) { for ( String id : idList ) { OMElement firstElement = record.getFirstElement(); firstElement.insertSiblingBefore( GenerateOMElement.newInstance().createFileIdentifierElement( id ) ); } } return record; } }
deegree-core/deegree-core-metadata/src/main/java/org/deegree/metadata/persistence/iso/parsing/inspectation/FIInspector.java
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.metadata.persistence.iso.parsing.inspectation; import static org.slf4j.LoggerFactory.getLogger; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import org.apache.axiom.om.OMElement; import org.deegree.commons.xml.NamespaceBindings; import org.deegree.commons.xml.XMLAdapter; import org.deegree.commons.xml.XPath; import org.deegree.metadata.i18n.Messages; import org.deegree.metadata.persistence.MetadataInspectorException; import org.deegree.metadata.persistence.iso.generating.generatingelements.GenerateOMElement; import org.deegree.metadata.persistence.iso.parsing.IdUtils; import org.deegree.metadata.persistence.iso19115.jaxb.FileIdentifierInspector; import org.deegree.protocol.csw.MetadataStoreException; import org.slf4j.Logger; /** * Inspects whether the fileIdentifier should be set when inserting a metadata or not and what consequences should * occur. * * @author <a href="mailto:[email protected]">Steffen Thomas</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class FIInspector implements RecordInspector { private static final Logger LOG = getLogger( FIInspector.class ); private Connection conn; private final XMLAdapter a; private final FileIdentifierInspector config; public FIInspector( FileIdentifierInspector inspector ) { this.config = inspector; this.a = new XMLAdapter(); } /** * * @param fi * the fileIdentifier that should be determined for one metadata, can be <Code>null</Code>. * @param rsList * the list of resourceIdentifier, not <Code>null</Code>. * @param id * the id-attribute, can be <Code>null<Code>. * @param uuid * the uuid-attribure, can be <Code>null</Code>. * @param isFileIdentifierExistenceDesired * true, if the existence of the fileIdentifier is desired in backend. * @return the new fileIdentifier. * @throws MetadataStoreException */ private List<String> determineFileIdentifier( String[] fi, List<String> rsList, String id, String uuid ) throws MetadataInspectorException { List<String> idList = new ArrayList<String>(); if ( fi.length != 0 ) { for ( String f : fi ) { LOG.info( Messages.getMessage( "INFO_FI_AVAILABLE", f ) ); idList.add( f ); } return idList; } else { if ( config != null && !config.isRejectEmpty() ) { if ( rsList.size() == 0 && id == null && uuid == null ) { LOG.debug( Messages.getMessage( "INFO_FI_GENERATE_NEW" ) ); idList.add( IdUtils.newInstance( conn ).generateUUID() ); LOG.debug( Messages.getMessage( "INFO_FI_NEW", idList ) ); } else { if ( rsList.size() == 0 && id != null ) { LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_ID", id ) ); idList.add( id ); } else if ( rsList.size() == 0 && uuid != null ) { LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_UUID", uuid ) ); idList.add( uuid ); } else { LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_RSID", rsList.get( 0 ) ) ); idList.add( rsList.get( 0 ) ); } } return idList; } else { if ( rsList.size() == 0 ) { String msg = Messages.getMessage( "ERROR_REJECT_FI" ); LOG.debug( msg ); throw new MetadataInspectorException( msg ); } else { LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_RSID", rsList.get( 0 ) ) ); idList.add( rsList.get( 0 ) ); return idList; } } } } @Override public OMElement inspect( OMElement record, Connection conn ) throws MetadataInspectorException { this.conn = conn; a.setRootElement( record ); NamespaceBindings nsContext = a.getNamespaceContext( record ); // NamespaceContext newNSC = generateNSC(nsContext); nsContext.addNamespace( "srv", "http://www.isotc211.org/2005/srv" ); nsContext.addNamespace( "gmd", "http://www.isotc211.org/2005/gmd" ); nsContext.addNamespace( "gco", "http://www.isotc211.org/2005/gco" ); // String GMD_PRE = "gmd"; String[] fileIdentifierString = a.getNodesAsStrings( record, new XPath( "./gmd:fileIdentifier/gco:CharacterString", nsContext ) ); OMElement sv_service_OR_md_dataIdentification = a.getElement( record, new XPath( "./gmd:identificationInfo/srv:SV_ServiceIdentification | ./gmd:identificationInfo/gmd:MD_DataIdentification", nsContext ) ); String dataIdentificationId = sv_service_OR_md_dataIdentification.getAttributeValue( new QName( "id" ) ); String dataIdentificationUuId = sv_service_OR_md_dataIdentification.getAttributeValue( new QName( "uuid" ) ); List<OMElement> identifier = a.getElements( sv_service_OR_md_dataIdentification, new XPath( "./gmd:citation/gmd:CI_Citation/gmd:identifier", nsContext ) ); List<String> resourceIdentifierList = new ArrayList<String>(); for ( OMElement resourceElement : identifier ) { String resourceIdentifier = a.getNodeAsString( resourceElement, new XPath( "./gmd:MD_Identifier/gmd:code/gco:CharacterString | ./gmd:RS_Identifier/gmd:code/gco:CharacterString", nsContext ), null ); LOG.debug( "resourceIdentifier: '" + resourceIdentifier + "' " ); resourceIdentifierList.add( resourceIdentifier ); } List<String> idList = determineFileIdentifier( fileIdentifierString, resourceIdentifierList, dataIdentificationId, dataIdentificationUuId ); // if ( idList.isEmpty() ) { // return null; // } if ( !idList.isEmpty() && fileIdentifierString.length == 0 ) { for ( String id : idList ) { OMElement firstElement = record.getFirstElement(); firstElement.insertSiblingBefore( GenerateOMElement.newInstance().createFileIdentifierElement( id ) ); } } return record; } }
cleanup, trim file identifiers
deegree-core/deegree-core-metadata/src/main/java/org/deegree/metadata/persistence/iso/parsing/inspectation/FIInspector.java
cleanup, trim file identifiers
Java
lgpl-2.1
31677ef823fc0a11001f391a497173ba55b4f274
0
zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform
package org.fedorahosted.flies.gwt.model; import java.io.Serializable; public class TransMemory implements Serializable{ private static final long serialVersionUID = -7381018377520206564L; private String source; private String memory; private String sourceComment; // TODO we should probably include transunit id too (useful when we support browser history for TUs) // TODO include obsolete flag and show this info to the user private String targetComment; private String docID; private long projectContainer; public TransMemory() { } @Deprecated public TransMemory(String source, String memory, String documentPath) { this(source, memory, "", "", documentPath, 0); } public TransMemory(String source, String memory, String sourceComment, String targetComment, String documentPath, long projectContainer) { this.source = source; this.memory = memory; this.sourceComment = sourceComment; this.targetComment = targetComment; this.docID = documentPath; this.projectContainer = projectContainer; } public void setDocID(String documentPath) { this.docID = documentPath; } public String getDocID() { return docID; } public void setMemory(String memory) { this.memory = memory; } public String getMemory() { return memory; } public void setSource(String source) { this.source = source; } public String getSource() { return source; } public void setSourceComment(String sourceComment) { this.sourceComment = sourceComment; } public String getSourceComment() { return sourceComment; } public void setTargetComment(String targetComment) { this.targetComment = targetComment; } public String getTargetComment() { return targetComment; } public void setProjectContainer(long projectContainer) { this.projectContainer = projectContainer; } public long getProjectContainer() { return projectContainer; } }
flies-gwt-api/src/main/java/org/fedorahosted/flies/gwt/model/TransMemory.java
package org.fedorahosted.flies.gwt.model; import java.io.Serializable; public class TransMemory implements Serializable{ private static final long serialVersionUID = -7381018377520206564L; private String source; private String memory; private String sourceComment; // TODO we should probably include transunit id too (useful when we support browser history for TUs) // TODO include obsolete flag and show this info to the user private String targetComment; private String docID; private long projectContainer; public TransMemory() { } @Deprecated public TransMemory(String source, String memory, String documentPath) { this(source, memory, "", "", documentPath, 0); } public TransMemory(String source, String memory, String sourceComment, String targetComment, String documentPath, long projectContainer) { this.source = source; this.memory = memory; this.sourceComment = sourceComment; this.targetComment = targetComment; this.docID = documentPath; this.projectContainer = projectContainer; } public void setDocID(String documentPath) { this.docID = documentPath; } public String getDocID() { return docID; } public void setMemory(String memory) { this.memory = memory; } public String getMemory() { return memory; } public void setSource(String source) { this.source = source; } public String getSource() { return source; } }
- Added setter and getter for remainining data in TransMemory object.
flies-gwt-api/src/main/java/org/fedorahosted/flies/gwt/model/TransMemory.java
- Added setter and getter for remainining data in TransMemory object.
Java
lgpl-2.1
04b852df702c83c692735b35145e8d4caceda0b6
0
geotools/geotools,geotools/geotools,geotools/geotools,geotools/geotools
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2011, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.jdbc; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import org.geotools.factory.Hints; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.jdbc.JoinInfo.JoinPart; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; /** * Feature reader that wraps multiple feature readers in a join query. * * @author Justin Deoliveira, OpenGeo * */ public class JDBCJoiningFeatureReader extends JDBCFeatureReader { List<JDBCFeatureReader> joinReaders; SimpleFeatureBuilder joinFeatureBuilder; public JDBCJoiningFeatureReader(String sql, Connection cx, JDBCFeatureSource featureSource, SimpleFeatureType featureType, JoinInfo join, Hints hints) throws SQLException, IOException { //super(sql, cx, featureSource, retype(featureType, join), hints); super(sql, cx, featureSource, featureType, hints); init(cx, featureSource, featureType, join, hints); } public JDBCJoiningFeatureReader(PreparedStatement st, Connection cx, JDBCFeatureSource featureSource, SimpleFeatureType featureType, JoinInfo join, Hints hints) throws SQLException, IOException { super(st, cx, featureSource, featureType, hints); init(cx, featureSource, featureType, join, hints); } void init(Connection cx, JDBCFeatureSource featureSource, SimpleFeatureType featureType, JoinInfo join, Hints hints) throws SQLException, IOException { joinReaders = new ArrayList<JDBCFeatureReader>(); int offset = featureType.getAttributeCount() + getPrimaryKey().getColumns().size(); for (JoinPart part : join.getParts()) { SimpleFeatureType ft = part.getQueryFeatureType(); joinReaders.add(new JDBCFeatureReader(rs, cx, offset, featureSource.getDataStore() .getAbsoluteFeatureSource(ft.getTypeName()), ft, hints) { @Override protected void finalize() throws Throwable { // Do nothing. // // This override protects the injected result set and connection from being // closed by the garbage collector, which is unwanted because this is a // delegate which uses resources that will be closed elsewhere, or so it // is claimed in the comment in the close() method below. See GEOT-4204. } }); } //builder for the final joined feature joinFeatureBuilder = new SimpleFeatureBuilder(retype(featureType, join)); } @Override public boolean hasNext() throws IOException { boolean next = super.hasNext(); for (JDBCFeatureReader r : joinReaders) { r.setNext(next); } return next; } @Override public SimpleFeature next() throws IOException, IllegalArgumentException, NoSuchElementException { //read the regular feature SimpleFeature f = super.next(); //rebuild it with the join feature type joinFeatureBuilder.init(f); f = joinFeatureBuilder.buildFeature(f.getID()); //add additional attributes for joined features for (int i = 0; i < joinReaders.size(); i++) { JDBCFeatureReader r = joinReaders.get(i); f.setAttribute(f.getAttributeCount() - joinReaders.size() + i, r.next()); } return f; } @Override public void close() throws IOException { super.close(); //we don't need to close the delegate readers because they share the same result set // and connection as this reader } static SimpleFeatureType retype(SimpleFeatureType featureType, JoinInfo join) { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.init(featureType); for (JoinPart part : join.getParts()) { b.add(part.getAttributeName(), SimpleFeature.class); } return b.buildFeatureType(); } }
modules/library/jdbc/src/main/java/org/geotools/jdbc/JDBCJoiningFeatureReader.java
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2011, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.jdbc; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import org.geotools.factory.Hints; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.jdbc.JoinInfo.JoinPart; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; /** * Feature reader that wraps multiple feature readers in a join query. * * @author Justin Deoliveira, OpenGeo * */ public class JDBCJoiningFeatureReader extends JDBCFeatureReader { List<JDBCFeatureReader> joinReaders; SimpleFeatureBuilder joinFeatureBuilder; public JDBCJoiningFeatureReader(String sql, Connection cx, JDBCFeatureSource featureSource, SimpleFeatureType featureType, JoinInfo join, Hints hints) throws SQLException, IOException { //super(sql, cx, featureSource, retype(featureType, join), hints); super(sql, cx, featureSource, featureType, hints); init(cx, featureSource, featureType, join, hints); } public JDBCJoiningFeatureReader(PreparedStatement st, Connection cx, JDBCFeatureSource featureSource, SimpleFeatureType featureType, JoinInfo join, Hints hints) throws SQLException, IOException { super(st, cx, featureSource, featureType, hints); init(cx, featureSource, featureType, join, hints); } void init(Connection cx, JDBCFeatureSource featureSource, SimpleFeatureType featureType, JoinInfo join, Hints hints) throws SQLException, IOException { joinReaders = new ArrayList<JDBCFeatureReader>(); int offset = featureType.getAttributeCount() + getPrimaryKey().getColumns().size(); for (JoinPart part : join.getParts()) { SimpleFeatureType ft = part.getQueryFeatureType(); joinReaders.add(new JDBCFeatureReader(rs, cx, offset, featureSource.getDataStore().getAbsoluteFeatureSource(ft.getTypeName()), ft, hints)); } //builder for the final joined feature joinFeatureBuilder = new SimpleFeatureBuilder(retype(featureType, join)); } @Override public boolean hasNext() throws IOException { boolean next = super.hasNext(); for (JDBCFeatureReader r : joinReaders) { r.setNext(next); } return next; } @Override public SimpleFeature next() throws IOException, IllegalArgumentException, NoSuchElementException { //read the regular feature SimpleFeature f = super.next(); //rebuild it with the join feature type joinFeatureBuilder.init(f); f = joinFeatureBuilder.buildFeature(f.getID()); //add additional attributes for joined features for (int i = 0; i < joinReaders.size(); i++) { JDBCFeatureReader r = joinReaders.get(i); f.setAttribute(f.getAttributeCount() - joinReaders.size() + i, r.next()); } return f; } @Override public void close() throws IOException { super.close(); //we don't need to close the delegate readers because they share the same result set // and connection as this reader } static SimpleFeatureType retype(SimpleFeatureType featureType, JoinInfo join) { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.init(featureType); for (JoinPart part : join.getParts()) { b.add(part.getAttributeName(), SimpleFeature.class); } return b.buildFeatureType(); } }
[GEOT-4204] Intermittent JDBCJoinTest failures
modules/library/jdbc/src/main/java/org/geotools/jdbc/JDBCJoiningFeatureReader.java
[GEOT-4204] Intermittent JDBCJoinTest failures
Java
unlicense
c3ba0e6c6c05e38fc68a3ce49eeedc4012f4f8bb
0
ZatmanUfro/UfroTrack
package Ventanas; import Archivos.GestorArchivo; import Procesos.HorarioAlumno; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.*; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileSystemView; public class Inicio extends JFrame implements ActionListener { private String [][] tablaNombre; private String [][] tablaCodigo; private JLabel labelClase; private JTextField textFieldRut, textFieldBuscar, textFieldNombre, textFieldRuta; private JButton botonBuscar, bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8, bt9, bt10, bt11, bt12, bt13, bt14, bt15, bt16, bt17, bt18, bt19,bt20, bt21, bt22, bt23, bt24, bt25, bt26,bt27, bt28, bt29, bt30, bt31, bt32, bt33, bt34, bt35, bt36, bt37, bt38, bt39, bt40, bt41,bt42,bt43,bt44,bt45,bt46,bt47,bt48,bt49,bt50, botonCargar; public Inicio() { super("UfroTrack"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//finaliza el programa cuando se da click en la X this.setSize(900, 500);//configurando tamaño de la ventana this.setResizable(false); // GestorArchivo gestor = new GestorArchivo(); // if(gestor.checkFile()!=true){ FileChooser(); } HorarioAlumno horario =initHorario(gestor); //Labels labelClase = new JLabel("Rut"); labelClase.setText("Rut"); labelClase.setBounds(580, 10, 100, 25); this.add(labelClase); labelClase = new JLabel("Nombre"); labelClase.setText("Nombre"); labelClase.setBounds(10+60, 10, 100, 25); this.add(labelClase); labelClase = new JLabel("Lunes"); labelClase.setText("Lunes"); labelClase.setBounds(10+60, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Martes"); labelClase.setText("Martes"); labelClase.setBounds(110+60, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Miercoles"); labelClase.setText("Miercoles"); labelClase.setBounds(210+60, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Jueves"); labelClase.setText("Jueves"); labelClase.setBounds(310+60, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Viernes"); labelClase.setText("Viernes"); labelClase.setBounds(410+60, 60, 100, 25); this.add(labelClase); //TextFields textFieldRut = new JTextField(); textFieldRut.setEditable(false); textFieldRut.setBounds(650, 10, 100, 25); textFieldRut.setText(horario.getRut()); this.add(textFieldRut); textFieldBuscar = new JTextField(); textFieldBuscar.setBounds(600+60, 110, 100, 25); textFieldBuscar.setText("Buscar"); this.add(textFieldBuscar); textFieldNombre = new JTextField(); textFieldNombre.setEditable(false); textFieldNombre.setBounds(110+60, 10, 100, 25); textFieldNombre.setText(horario.getNombreAlumno()); this.add(textFieldNombre); //JButtons //lunes bt1 = new JButton("Terminar"); bt1.setBounds(0+60, 100, 100, 25); this.add(bt1); setLayout(null); bt1.addActionListener(this); bt2 = new JButton("Terminar"); bt2.setBounds(0+60, 125, 100, 25); this.add(bt2); setLayout(null); bt2.addActionListener(this); bt3 = new JButton("Terminar"); bt3.setBounds(0+60, 175, 100, 25); this.add(bt3); setLayout(null); bt3.addActionListener(this); bt4 = new JButton("Terminar"); bt4.setBounds(0+60, 200, 100, 25); this.add(bt4); setLayout(null); bt4.addActionListener(this); bt5 = new JButton("Terminar"); bt5.setBounds(0+60, 250, 100, 25); this.add(bt5); setLayout(null); bt5.addActionListener(this); bt6 = new JButton("Terminar"); bt6.setBounds(0+60, 275, 100, 25); this.add(bt6); setLayout(null); bt6.addActionListener(this); bt7 = new JButton("Terminar"); bt7.setBounds(0+60, 325, 100, 25); this.add(bt7); setLayout(null); bt7.addActionListener(this); bt8 = new JButton("Terminar"); bt8.setBounds(0+60, 350, 100, 25); this.add(bt8); setLayout(null); bt8.addActionListener(this); bt9 = new JButton("Terminar"); bt9.setBounds(0+60, 400, 100, 25); this.add(bt9); setLayout(null); bt9.addActionListener(this); bt10 = new JButton("Terminar"); bt10.setBounds(0+60, 425, 100, 25); this.add(bt10); setLayout(null); bt10.addActionListener(this); // martes bt11 = new JButton("Terminar"); bt11.setBounds(100+60, 100, 100, 25); this.add(bt11); setLayout(null); bt11.addActionListener(this); bt12 = new JButton("Terminar"); bt12.setBounds(100+60, 125, 100, 25); this.add(bt12); setLayout(null); bt12.addActionListener(this); bt13 = new JButton("Terminar"); bt13.setBounds(100+60, 175, 100, 25); this.add(bt13); setLayout(null); bt13.addActionListener(this); bt14 = new JButton("Terminar"); bt14.setBounds(100+60, 200, 100, 25); this.add(bt14); setLayout(null); bt14.addActionListener(this); bt15 = new JButton("Terminar"); bt15.setBounds(100+60, 250, 100, 25); this.add(bt15); setLayout(null); bt15.addActionListener(this); bt16 = new JButton("Terminar"); bt16.setBounds(100+60, 275, 100, 25); this.add(bt16); setLayout(null); bt16.addActionListener(this); bt17 = new JButton("Terminar"); bt17.setBounds(100+60, 325, 100, 25); this.add(bt17); setLayout(null); bt17.addActionListener(this); bt18 = new JButton("Terminar"); bt18.setBounds(100+60, 350, 100, 25); this.add(bt18); setLayout(null); bt18.addActionListener(this); bt19 = new JButton("Terminar"); bt19.setBounds(100+60, 400, 100, 25); this.add(bt19); setLayout(null); bt19.addActionListener(this); bt20 = new JButton("Terminar"); bt20.setBounds(100+60, 425, 100, 25); this.add(bt20); setLayout(null); bt20.addActionListener(this); bt21 = new JButton("Terminar"); bt21.setBounds(200+60, 100, 100, 25); this.add(bt21); setLayout(null); bt21.addActionListener(this); //Miercoles bt22 = new JButton("Terminar"); bt22.setBounds(200+60, 125, 100, 25); this.add(bt22); setLayout(null); bt22.addActionListener(this); bt23 = new JButton("Terminar"); bt23.setBounds(200+60, 175, 100, 25); this.add(bt23); setLayout(null); bt23.addActionListener(this); bt24 = new JButton("Terminar"); bt24.setBounds(200+60, 200, 100, 25); this.add(bt24); setLayout(null); bt24.addActionListener(this); bt25 = new JButton("Terminar"); bt25.setBounds(200+60, 250, 100, 25); this.add(bt25); setLayout(null); bt25.addActionListener(this); bt26 = new JButton("Terminar"); bt26.setBounds(200+60, 275, 100, 25); this.add(bt26); setLayout(null); bt26.addActionListener(this); bt27 = new JButton("Terminar"); bt27.setBounds(200+60, 325, 100, 25); this.add(bt27); setLayout(null); bt27.addActionListener(this); bt28 = new JButton("Terminar"); bt28.setBounds(200+60, 350, 100, 25); this.add(bt28); setLayout(null); bt28.addActionListener(this); bt29 = new JButton("Terminar"); bt29.setBounds(200+60, 400, 100, 25); this.add(bt29); setLayout(null); bt29.addActionListener(this); bt30 = new JButton("Terminar"); bt30.setBounds(200+60, 425, 100, 25); this.add(bt30); setLayout(null); bt30.addActionListener(this); //Jueves bt31 = new JButton("Terminar"); bt31.setBounds(300+60, 100, 100, 25); this.add(bt31); setLayout(null); bt31.addActionListener(this); bt32 = new JButton("Terminar"); bt32.setBounds(300+60, 125, 100, 25); this.add(bt32); setLayout(null); bt32.addActionListener(this); bt33 = new JButton("Terminar"); bt33.setBounds(300+60, 175, 100, 25); this.add(bt33); setLayout(null); bt33.addActionListener(this); bt34 = new JButton("Terminar"); bt34.setBounds(300+60, 200, 100, 25); this.add(bt34); setLayout(null); bt34.addActionListener(this); bt35 = new JButton("Terminar"); bt35.setBounds(300+60, 250, 100, 25); this.add(bt35); setLayout(null); bt35.addActionListener(this); bt36 = new JButton("Terminar"); bt36.setBounds(300+60, 275, 100, 25); this.add(bt36); setLayout(null); bt36.addActionListener(this); bt37 = new JButton("Terminar"); bt37.setBounds(300+60, 325, 100, 25); this.add(bt37); setLayout(null); bt37.addActionListener(this); bt38 = new JButton("Terminar"); bt38.setBounds(300+60, 350, 100, 25); this.add(bt38); setLayout(null); bt38.addActionListener(this); bt39 = new JButton("Terminar"); bt39.setBounds(300+60, 400, 100, 25); this.add(bt39); setLayout(null); bt39.addActionListener(this); bt40 = new JButton("Terminar"); bt40.setBounds(300+60, 425, 100, 25); this.add(bt40); setLayout(null); bt40.addActionListener(this); //Viernes bt41 = new JButton("Terminar"); bt41.setBounds(400+60, 100, 100, 25); this.add(bt41); setLayout(null); bt41.addActionListener(this); bt42 = new JButton("Terminar"); bt42.setBounds(400+60, 125, 100, 25); this.add(bt42); setLayout(null); bt42.addActionListener(this); bt43 = new JButton("Terminar"); bt43.setBounds(400+60, 175, 100, 25); this.add(bt43); setLayout(null); bt43.addActionListener(this); bt44 = new JButton("Terminar"); bt44.setBounds(400+60, 200, 100, 25); this.add(bt44); setLayout(null); bt44.addActionListener(this); bt45 = new JButton("Terminar"); bt45.setBounds(400+60, 250, 100, 25); this.add(bt45); setLayout(null); bt45.addActionListener(this); bt46 = new JButton("Terminar"); bt46.setBounds(400+60, 275, 100, 25); this.add(bt46); setLayout(null); bt46.addActionListener(this); bt47 = new JButton("Terminar"); bt47.setBounds(400+60, 325, 100, 25); this.add(bt47); setLayout(null); bt47.addActionListener(this); bt48 = new JButton("Terminar"); bt48.setBounds(400+60, 350, 100, 25); this.add(bt48); setLayout(null); bt48.addActionListener(this); bt49 = new JButton("Terminar"); bt49.setBounds(400+60, 400, 100, 25); this.add(bt49); setLayout(null); bt49.addActionListener(this); bt50 = new JButton("Terminar"); bt50.setBounds(400+60, 425, 100, 25); this.add(bt50); setLayout(null); bt50.addActionListener(this); botonBuscar = new JButton("Buscar"); botonBuscar.setBounds(600+60, 135, 100, 25); this.add(botonBuscar); setLayout(null); botonBuscar.addActionListener(this); //Cargar horario labelClase = new JLabel(); labelClase.setText("Ruta"); labelClase.setBounds(630, 225, 100, 25); this.add(labelClase); textFieldRuta = new JTextField(); textFieldRuta.setBounds(630, 250, 200, 25); textFieldRuta.setText(gestor.getAlumno()); textFieldRuta.setEnabled(false); this.add(textFieldRuta); botonCargar = new JButton("Cargar excell"); botonCargar.setBounds(630, 275, 200, 25); this.add(botonCargar); setLayout(null); botonCargar.addActionListener(this); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Inicio().setVisible(true); } }); } @Override public void actionPerformed(ActionEvent ae) { if(ae.getSource() == botonBuscar ){ ResultadoBusqueda ventana = new ResultadoBusqueda(textFieldBuscar.getText()); ventana.setVisible(true); setVisible(false); } if (ae.getSource() == bt1) { } if (ae.getSource() == bt2) { } if (ae.getSource() == bt3) { } if (ae.getSource() == bt4) { } if (ae.getSource() == bt5) { } if (ae.getSource() == bt6) { } if (ae.getSource() == bt7) { } if (ae.getSource() == bt8) { } if (ae.getSource() == bt9) { } if (ae.getSource() == bt10) { } if (ae.getSource() == bt11) { } if (ae.getSource() == bt12) { } if (ae.getSource() == bt13) { } if (ae.getSource() == bt14) { } if (ae.getSource() == bt15) { } if (ae.getSource() == bt16) { } if (ae.getSource() == bt17) { } if (ae.getSource() == bt18) { } if (ae.getSource() == bt19) { } if (ae.getSource() == bt20) { } if (ae.getSource() == bt21) { } if (ae.getSource() == bt22) { } if (ae.getSource() == bt23) { } if (ae.getSource() == bt24) { } if (ae.getSource() == bt25) { } if (ae.getSource() == bt26) { } if (ae.getSource() == bt27) { } if (ae.getSource() == bt28) { } if (ae.getSource() == bt29) { } if (ae.getSource() == bt30) { } if (ae.getSource() == bt31) { } if (ae.getSource() == bt32) { } if (ae.getSource() == bt33) { } if (ae.getSource() == bt34) { } if (ae.getSource() == bt35) { } if (ae.getSource() == bt36) { } if (ae.getSource() == bt37) { } if (ae.getSource() == bt38) { } if (ae.getSource() == bt39) { } if (ae.getSource() == bt40) { } if (ae.getSource() == bt41) { } if (ae.getSource() == bt42) { } if (ae.getSource() == bt43) { } if (ae.getSource() == bt44) { } if (ae.getSource() == bt45) { } if (ae.getSource() == bt46) { } if (ae.getSource() == bt47) { } if (ae.getSource() == bt48) { } if (ae.getSource() == bt49) { } if (ae.getSource() == bt50) { } } private void FileChooser(){ JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); jfc.setDialogTitle("Elije la ruta de 'Horario Alumno.xlsx'"); jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); FileFilter filter = new FileNameExtensionFilter(".xlsx","xlsx"); jfc.addChoosableFileFilter(filter); jfc.setFileFilter(filter); int returnValue = jfc.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); GestorArchivo gestor = new GestorArchivo(); gestor.setAlumno(selectedFile.getAbsolutePath()); } } private HorarioAlumno initHorario(GestorArchivo gestor){ HorarioAlumno horario = null; try{ horario = new HorarioAlumno(); }catch(NullPointerException e){ JOptionPane.showMessageDialog(null, "Formato de archivo incorrecto \n Elija nuevo archivo"); gestor.deleteFile(); FileChooser(); initHorario(gestor); } return horario; } }
src/Ventanas/Inicio.java
package Ventanas; import Procesos.HorarioAlumno; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class Inicio extends JFrame implements ActionListener { private String [][] tablaNombre; private String [][] tablaCodigo; private JLabel labelClase; private JTextField textFieldRut, textFieldBuscar, textFieldNombre, textFieldRuta; private JButton botonBuscar, bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8, bt9, bt10, bt11, bt12, bt13, bt14, bt15, bt16, bt17, bt18, bt19,bt20, bt21, bt22, bt23, bt24, bt25, bt26,bt27, bt28, bt29, bt30, bt31, bt32, bt33, bt34, bt35, bt36, bt37, bt38, bt39, bt40, bt41,bt42,bt43,bt44,bt45,bt46,bt47,bt48,bt49,bt50, botonCargar; public Inicio() { super("UfroTrack"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//finaliza el programa cuando se da click en la X this.setSize(900, 500);//configurando tamaño de la ventana this.setResizable(false); //Labels labelClase = new JLabel("Rut"); labelClase.setText("Rut"); labelClase.setBounds(580, 10, 100, 25); this.add(labelClase); labelClase = new JLabel("Nombre"); labelClase.setText("Nombre"); labelClase.setBounds(10+60, 10, 100, 25); this.add(labelClase); labelClase = new JLabel("Lunes"); labelClase.setText("Lunes"); labelClase.setBounds(10+60, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Martes"); labelClase.setText("Martes"); labelClase.setBounds(110+60, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Miercoles"); labelClase.setText("Miercoles"); labelClase.setBounds(210+60, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Jueves"); labelClase.setText("Jueves"); labelClase.setBounds(310+60, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Viernes"); labelClase.setText("Viernes"); labelClase.setBounds(410+60, 60, 100, 25); this.add(labelClase); //TextFields textFieldRut = new JTextField(); textFieldRut.setEditable(false); textFieldRut.setBounds(650, 10, 100, 25); textFieldRut.setText(""); this.add(textFieldRut); textFieldBuscar = new JTextField(); textFieldBuscar.setBounds(600+60, 110, 100, 25); textFieldBuscar.setText("Buscar"); this.add(textFieldBuscar); textFieldNombre = new JTextField(); textFieldNombre.setEditable(false); textFieldNombre.setBounds(110+60, 10, 100, 25); textFieldNombre.setText(""); this.add(textFieldNombre); labelClase = new JLabel("Hora"); labelClase.setText("Hora"); labelClase.setBounds(10, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("8:30"); labelClase.setText("8:30"); labelClase.setBounds(10, 100, 100, 25); this.add(labelClase); labelClase = new JLabel("9:40"); labelClase.setText("9:40"); labelClase.setBounds(10, 125, 100, 25); this.add(labelClase); labelClase = new JLabel("10:50"); labelClase.setText("10:50"); labelClase.setBounds(10, 175, 100, 25); this.add(labelClase); labelClase = new JLabel("12:00"); labelClase.setText("12:00"); labelClase.setBounds(10, 200, 100, 25); this.add(labelClase); labelClase = new JLabel("14:30"); labelClase.setText("14:30"); labelClase.setBounds(10, 250, 100, 25); this.add(labelClase); labelClase = new JLabel("15:40"); labelClase.setText("15:40"); labelClase.setBounds(10, 275, 100, 25); this.add(labelClase); labelClase = new JLabel("16:50"); labelClase.setText("16:50"); labelClase.setBounds(10, 325, 100, 25); this.add(labelClase); labelClase = new JLabel("18:00"); labelClase.setText("18:00"); labelClase.setBounds(10, 350, 100, 25); this.add(labelClase); labelClase = new JLabel("19:10"); labelClase.setText("19:10"); labelClase.setBounds(10, 400, 100, 25); this.add(labelClase); labelClase = new JLabel("20:20"); labelClase.setText("20:20"); labelClase.setBounds(10, 425, 100, 25); this.add(labelClase); //JButtons //lunes bt1 = new JButton("Terminar"); bt1.setBounds(0+60, 100, 100, 25); this.add(bt1); setLayout(null); bt1.addActionListener(this); bt2 = new JButton("Terminar"); bt2.setBounds(0+60, 125, 100, 25); this.add(bt2); setLayout(null); bt2.addActionListener(this); bt3 = new JButton("Terminar"); bt3.setBounds(0+60, 175, 100, 25); this.add(bt3); setLayout(null); bt3.addActionListener(this); bt4 = new JButton("Terminar"); bt4.setBounds(0+60, 200, 100, 25); this.add(bt4); setLayout(null); bt4.addActionListener(this); bt5 = new JButton("Terminar"); bt5.setBounds(0+60, 250, 100, 25); this.add(bt5); setLayout(null); bt5.addActionListener(this); bt6 = new JButton("Terminar"); bt6.setBounds(0+60, 275, 100, 25); this.add(bt6); setLayout(null); bt6.addActionListener(this); bt7 = new JButton("Terminar"); bt7.setBounds(0+60, 325, 100, 25); this.add(bt7); setLayout(null); bt7.addActionListener(this); bt8 = new JButton("Terminar"); bt8.setBounds(0+60, 350, 100, 25); this.add(bt8); setLayout(null); bt8.addActionListener(this); bt9 = new JButton("Terminar"); bt9.setBounds(0+60, 400, 100, 25); this.add(bt9); setLayout(null); bt9.addActionListener(this); bt10 = new JButton("Terminar"); bt10.setBounds(0+60, 425, 100, 25); this.add(bt10); setLayout(null); bt10.addActionListener(this); // martes bt11 = new JButton("Terminar"); bt11.setBounds(100+60, 100, 100, 25); this.add(bt11); setLayout(null); bt11.addActionListener(this); bt12 = new JButton("Terminar"); bt12.setBounds(100+60, 125, 100, 25); this.add(bt12); setLayout(null); bt12.addActionListener(this); bt13 = new JButton("Terminar"); bt13.setBounds(100+60, 175, 100, 25); this.add(bt13); setLayout(null); bt13.addActionListener(this); bt14 = new JButton("Terminar"); bt14.setBounds(100+60, 200, 100, 25); this.add(bt14); setLayout(null); bt14.addActionListener(this); bt15 = new JButton("Terminar"); bt15.setBounds(100+60, 250, 100, 25); this.add(bt15); setLayout(null); bt15.addActionListener(this); bt16 = new JButton("Terminar"); bt16.setBounds(100+60, 275, 100, 25); this.add(bt16); setLayout(null); bt16.addActionListener(this); bt17 = new JButton("Terminar"); bt17.setBounds(100+60, 325, 100, 25); this.add(bt17); setLayout(null); bt17.addActionListener(this); bt18 = new JButton("Terminar"); bt18.setBounds(100+60, 350, 100, 25); this.add(bt18); setLayout(null); bt18.addActionListener(this); bt19 = new JButton("Terminar"); bt19.setBounds(100+60, 400, 100, 25); this.add(bt19); setLayout(null); bt19.addActionListener(this); bt20 = new JButton("Terminar"); bt20.setBounds(100+60, 425, 100, 25); this.add(bt20); setLayout(null); bt20.addActionListener(this); bt21 = new JButton("Terminar"); bt21.setBounds(200+60, 100, 100, 25); this.add(bt21); setLayout(null); bt21.addActionListener(this); //Miercoles bt22 = new JButton("Terminar"); bt22.setBounds(200+60, 125, 100, 25); this.add(bt22); setLayout(null); bt22.addActionListener(this); bt23 = new JButton("Terminar"); bt23.setBounds(200+60, 175, 100, 25); this.add(bt23); setLayout(null); bt23.addActionListener(this); bt24 = new JButton("Terminar"); bt24.setBounds(200+60, 200, 100, 25); this.add(bt24); setLayout(null); bt24.addActionListener(this); bt25 = new JButton("Terminar"); bt25.setBounds(200+60, 250, 100, 25); this.add(bt25); setLayout(null); bt25.addActionListener(this); bt26 = new JButton("Terminar"); bt26.setBounds(200+60, 275, 100, 25); this.add(bt26); setLayout(null); bt26.addActionListener(this); bt27 = new JButton("Terminar"); bt27.setBounds(200+60, 325, 100, 25); this.add(bt27); setLayout(null); bt27.addActionListener(this); bt28 = new JButton("Terminar"); bt28.setBounds(200+60, 350, 100, 25); this.add(bt28); setLayout(null); bt28.addActionListener(this); bt29 = new JButton("Terminar"); bt29.setBounds(200+60, 400, 100, 25); this.add(bt29); setLayout(null); bt29.addActionListener(this); bt30 = new JButton("Terminar"); bt30.setBounds(200+60, 425, 100, 25); this.add(bt30); setLayout(null); bt30.addActionListener(this); //Jueves bt31 = new JButton("Terminar"); bt31.setBounds(300+60, 100, 100, 25); this.add(bt31); setLayout(null); bt31.addActionListener(this); bt32 = new JButton("Terminar"); bt32.setBounds(300+60, 125, 100, 25); this.add(bt32); setLayout(null); bt32.addActionListener(this); bt33 = new JButton("Terminar"); bt33.setBounds(300+60, 175, 100, 25); this.add(bt33); setLayout(null); bt33.addActionListener(this); bt34 = new JButton("Terminar"); bt34.setBounds(300+60, 200, 100, 25); this.add(bt34); setLayout(null); bt34.addActionListener(this); bt35 = new JButton("Terminar"); bt35.setBounds(300+60, 250, 100, 25); this.add(bt35); setLayout(null); bt35.addActionListener(this); bt36 = new JButton("Terminar"); bt36.setBounds(300+60, 275, 100, 25); this.add(bt36); setLayout(null); bt36.addActionListener(this); bt37 = new JButton("Terminar"); bt37.setBounds(300+60, 325, 100, 25); this.add(bt37); setLayout(null); bt37.addActionListener(this); bt38 = new JButton("Terminar"); bt38.setBounds(300+60, 350, 100, 25); this.add(bt38); setLayout(null); bt38.addActionListener(this); bt39 = new JButton("Terminar"); bt39.setBounds(300+60, 400, 100, 25); this.add(bt39); setLayout(null); bt39.addActionListener(this); bt40 = new JButton("Terminar"); bt40.setBounds(300+60, 425, 100, 25); this.add(bt40); setLayout(null); bt40.addActionListener(this); //Viernes bt41 = new JButton("Terminar"); bt41.setBounds(400+60, 100, 100, 25); this.add(bt41); setLayout(null); bt41.addActionListener(this); bt42 = new JButton("Terminar"); bt42.setBounds(400+60, 125, 100, 25); this.add(bt42); setLayout(null); bt42.addActionListener(this); bt43 = new JButton("Terminar"); bt43.setBounds(400+60, 175, 100, 25); this.add(bt43); setLayout(null); bt43.addActionListener(this); bt44 = new JButton("Terminar"); bt44.setBounds(400+60, 200, 100, 25); this.add(bt44); setLayout(null); bt44.addActionListener(this); bt45 = new JButton("Terminar"); bt45.setBounds(400+60, 250, 100, 25); this.add(bt45); setLayout(null); bt45.addActionListener(this); bt46 = new JButton("Terminar"); bt46.setBounds(400+60, 275, 100, 25); this.add(bt46); setLayout(null); bt46.addActionListener(this); bt47 = new JButton("Terminar"); bt47.setBounds(400+60, 325, 100, 25); this.add(bt47); setLayout(null); bt47.addActionListener(this); bt48 = new JButton("Terminar"); bt48.setBounds(400+60, 350, 100, 25); this.add(bt48); setLayout(null); bt48.addActionListener(this); bt49 = new JButton("Terminar"); bt49.setBounds(400+60, 400, 100, 25); this.add(bt49); setLayout(null); bt49.addActionListener(this); bt50 = new JButton("Terminar"); bt50.setBounds(400+60, 425, 100, 25); this.add(bt50); setLayout(null); bt50.addActionListener(this); botonBuscar = new JButton("Buscar"); botonBuscar.setBounds(600+60, 135, 100, 25); this.add(botonBuscar); setLayout(null); botonBuscar.addActionListener(this); //Cargar horario labelClase = new JLabel("Ruta"); labelClase.setText("Ruta"); labelClase.setBounds(630, 225, 100, 25); this.add(labelClase); textFieldRuta = new JTextField(); textFieldRuta.setBounds(630, 250, 200, 25); textFieldRuta.setText(""); this.add(textFieldRuta); botonCargar = new JButton("Cargar"); botonCargar.setBounds(630, 275, 200, 25); this.add(botonCargar); setLayout(null); botonCargar.addActionListener(this); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Inicio().setVisible(true); } }); } @Override public void actionPerformed(ActionEvent ae) { if(ae.getSource() == botonBuscar ){ ResultadoBusqueda ventana = new ResultadoBusqueda(textFieldBuscar.getText()); ventana.setVisible(true); setVisible(false); } if (ae.getSource() == bt1) { } if (ae.getSource() == bt2) { } if (ae.getSource() == bt3) { } if (ae.getSource() == bt4) { } if (ae.getSource() == bt5) { } if (ae.getSource() == bt6) { } if (ae.getSource() == bt7) { } if (ae.getSource() == bt8) { } if (ae.getSource() == bt9) { } if (ae.getSource() == bt10) { } if (ae.getSource() == bt11) { } if (ae.getSource() == bt12) { } if (ae.getSource() == bt13) { } if (ae.getSource() == bt14) { } if (ae.getSource() == bt15) { } if (ae.getSource() == bt16) { } if (ae.getSource() == bt17) { } if (ae.getSource() == bt18) { } if (ae.getSource() == bt19) { } if (ae.getSource() == bt20) { } if (ae.getSource() == bt21) { } if (ae.getSource() == bt22) { } if (ae.getSource() == bt23) { } if (ae.getSource() == bt24) { } if (ae.getSource() == bt25) { } if (ae.getSource() == bt26) { } if (ae.getSource() == bt27) { } if (ae.getSource() == bt28) { } if (ae.getSource() == bt29) { } if (ae.getSource() == bt30) { } if (ae.getSource() == bt31) { } if (ae.getSource() == bt32) { } if (ae.getSource() == bt33) { } if (ae.getSource() == bt34) { } if (ae.getSource() == bt35) { } if (ae.getSource() == bt36) { } if (ae.getSource() == bt37) { } if (ae.getSource() == bt38) { } if (ae.getSource() == bt39) { } if (ae.getSource() == bt40) { } if (ae.getSource() == bt41) { } if (ae.getSource() == bt42) { } if (ae.getSource() == bt43) { } if (ae.getSource() == bt44) { } if (ae.getSource() == bt45) { } if (ae.getSource() == bt46) { } if (ae.getSource() == bt47) { } if (ae.getSource() == bt48) { } if (ae.getSource() == bt49) { } if (ae.getSource() == bt50) { } } }
Update Inicio.java
src/Ventanas/Inicio.java
Update Inicio.java
Java
apache-2.0
50738ae16e9e873912b5a85d4c928734cdd685f2
0
wenmangbo/BroadleafCommerce,rawbenny/BroadleafCommerce,sitexa/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,caosg/BroadleafCommerce,sitexa/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,gengzhengtao/BroadleafCommerce,wenmangbo/BroadleafCommerce,macielbombonato/BroadleafCommerce,passion1014/metaworks_framework,liqianggao/BroadleafCommerce,TouK/BroadleafCommerce,alextiannus/BroadleafCommerce,caosg/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,alextiannus/BroadleafCommerce,cogitoboy/BroadleafCommerce,wenmangbo/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,shopizer/BroadleafCommerce,udayinfy/BroadleafCommerce,bijukunjummen/BroadleafCommerce,zhaorui1/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,trombka/blc-tmp,sitexa/BroadleafCommerce,liqianggao/BroadleafCommerce,sanlingdd/broadleaf,arshadalisoomro/BroadleafCommerce,liqianggao/BroadleafCommerce,rawbenny/BroadleafCommerce,daniellavoie/BroadleafCommerce,macielbombonato/BroadleafCommerce,trombka/blc-tmp,gengzhengtao/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,cloudbearings/BroadleafCommerce,bijukunjummen/BroadleafCommerce,rawbenny/BroadleafCommerce,cloudbearings/BroadleafCommerce,passion1014/metaworks_framework,gengzhengtao/BroadleafCommerce,passion1014/metaworks_framework,sanlingdd/broadleaf,daniellavoie/BroadleafCommerce,lgscofield/BroadleafCommerce,daniellavoie/BroadleafCommerce,ljshj/BroadleafCommerce,cogitoboy/BroadleafCommerce,shopizer/BroadleafCommerce,zhaorui1/BroadleafCommerce,zhaorui1/BroadleafCommerce,bijukunjummen/BroadleafCommerce,lgscofield/BroadleafCommerce,TouK/BroadleafCommerce,cogitoboy/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,lgscofield/BroadleafCommerce,alextiannus/BroadleafCommerce,udayinfy/BroadleafCommerce,ljshj/BroadleafCommerce,cloudbearings/BroadleafCommerce,shopizer/BroadleafCommerce,TouK/BroadleafCommerce,caosg/BroadleafCommerce,udayinfy/BroadleafCommerce,trombka/blc-tmp,ljshj/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,macielbombonato/BroadleafCommerce
/* * #%L * BroadleafCommerce Framework * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.broadleafcommerce.core.search.service.solr; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.common.SolrInputDocument; import org.broadleafcommerce.common.exception.ExceptionHelper; import org.broadleafcommerce.common.exception.ServiceException; import org.broadleafcommerce.common.extension.ExtensionResultStatusType; import org.broadleafcommerce.common.locale.domain.Locale; import org.broadleafcommerce.common.locale.service.LocaleService; import org.broadleafcommerce.common.util.BLCCollectionUtils; import org.broadleafcommerce.common.util.StopWatch; import org.broadleafcommerce.common.util.TransactionUtils; import org.broadleafcommerce.common.util.TypedTransformer; import org.broadleafcommerce.common.web.BroadleafRequestContext; import org.broadleafcommerce.core.catalog.dao.ProductDao; import org.broadleafcommerce.core.catalog.domain.Product; import org.broadleafcommerce.core.catalog.service.dynamic.DynamicSkuActiveDatesService; import org.broadleafcommerce.core.catalog.service.dynamic.DynamicSkuPricingService; import org.broadleafcommerce.core.catalog.service.dynamic.SkuActiveDateConsiderationContext; import org.broadleafcommerce.core.catalog.service.dynamic.SkuPricingConsiderationContext; import org.broadleafcommerce.core.search.dao.CatalogStructure; import org.broadleafcommerce.core.search.dao.FieldDao; import org.broadleafcommerce.core.search.dao.SolrIndexDao; import org.broadleafcommerce.core.search.domain.Field; import org.broadleafcommerce.core.search.domain.solr.FieldType; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Resource; /** * Responsible for building and rebuilding the Solr index * * @author Andre Azzolini (apazzolini) * @author Jeff Fischer */ @Service("blSolrIndexService") public class SolrIndexServiceImpl implements SolrIndexService { private static final Log LOG = LogFactory.getLog(SolrIndexServiceImpl.class); protected final Object LOCK_OBJECT = new Object(); protected boolean IS_LOCKED = false; @Value("${solr.index.errorOnConcurrentReIndex}") protected boolean errorOnConcurrentReIndex = false; @Value("${solr.index.product.pageSize}") protected int pageSize; @Resource(name = "blProductDao") protected ProductDao productDao; @Resource(name = "blFieldDao") protected FieldDao fieldDao; @Resource(name = "blLocaleService") protected LocaleService localeService; @Resource(name = "blSolrHelperService") protected SolrHelperService shs; @Resource(name = "blSolrSearchServiceExtensionManager") protected SolrSearchServiceExtensionManager extensionManager; @Resource(name = "blTransactionManager") protected PlatformTransactionManager transactionManager; @Resource(name = "blSolrIndexDao") protected SolrIndexDao solrIndexDao; public static String ATTR_MAP = "productAttributes"; @Override public void performCachedOperation(SolrIndexCachedOperation.CacheOperation cacheOperation) throws ServiceException { try { CatalogStructure cache = new CatalogStructure(); SolrIndexCachedOperation.setCache(cache); cacheOperation.execute(); } finally { if (LOG.isInfoEnabled()) { LOG.info("Cleaning up Solr index cache from memory - size approx: " + getCacheSizeInMemoryApproximation(SolrIndexCachedOperation.getCache()) + " bytes"); } SolrIndexCachedOperation.clearCache(); } } protected int getCacheSizeInMemoryApproximation(CatalogStructure structure) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(structure); oos.close(); return baos.size(); } catch (IOException e) { throw ExceptionHelper.refineException(e); } } @Override public boolean isReindexInProcess() { synchronized (LOCK_OBJECT) { return IS_LOCKED; } } @Override public void rebuildIndex() throws ServiceException, IOException { synchronized (LOCK_OBJECT) { if (IS_LOCKED) { if (errorOnConcurrentReIndex) { throw new IllegalStateException("More than one thread attempting to concurrently reindex Solr."); } else { LOG.warn("There is more than one thread attempting to concurrently " + "reindex Solr. Failing additional threads gracefully. Check your configuration."); return; } } else { IS_LOCKED = true; } } try { LOG.info("Rebuilding the solr index..."); StopWatch s = new StopWatch(); LOG.info("Deleting the reindex core prior to rebuilding the index"); deleteAllDocuments(); Object[] pack = saveState(); try { final Long numProducts = productDao.readCountAllActiveProducts(); if (LOG.isDebugEnabled()) { LOG.debug("There are " + numProducts + " total products"); } performCachedOperation(new SolrIndexCachedOperation.CacheOperation() { @Override public void execute() throws ServiceException { int page = 0; while ((page * pageSize) < numProducts) { buildIncrementalIndex(page, pageSize); page++; } } }); optimizeIndex(SolrContext.getReindexServer()); } finally { restoreState(pack); } // Swap the active and the reindex cores shs.swapActiveCores(); LOG.info(String.format("Finished building index in %s", s.toLapString())); } finally { synchronized (LOCK_OBJECT) { IS_LOCKED = false; } } } /** * <p> * This method deletes all of the documents from {@link SolrContext#getReindexServer()} * * @throws ServiceException if there was a problem removing the documents * @deprecated use {@link #deleteAllReindexCoreDocuments()} instead */ @Deprecated protected void deleteAllDocuments() throws ServiceException { deleteAllReindexCoreDocuments(); } /** * <p> * This method deletes all of the documents from {@link SolrContext#getReindexServer()} * * @throws ServiceException if there was a problem removing the documents */ protected void deleteAllReindexCoreDocuments() throws ServiceException { try { String deleteQuery = shs.getNamespaceFieldName() + ":(\"" + shs.getCurrentNamespace() + "\")"; LOG.debug("Deleting by query: " + deleteQuery); SolrContext.getReindexServer().deleteByQuery(deleteQuery); SolrContext.getReindexServer().commit(); } catch (Exception e) { throw new ServiceException("Could not delete documents", e); } } protected void buildIncrementalIndex(int page, int pageSize) throws ServiceException { buildIncrementalIndex(page, pageSize, true); } @Override public void buildIncrementalIndex(int page, int pageSize, boolean useReindexServer) throws ServiceException { if (SolrIndexCachedOperation.getCache() == null) { LOG.warn("Consider using SolrIndexService.performCachedOperation() in combination with " + "SolrIndexService.buildIncrementalIndex() for better caching performance during solr indexing"); } TransactionStatus status = TransactionUtils.createTransaction("readProducts", TransactionDefinition.PROPAGATION_REQUIRED, transactionManager, true); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Building index - page: [%s], pageSize: [%s]", page, pageSize)); } StopWatch s = new StopWatch(); boolean cacheOperationManaged = false; try { CatalogStructure cache = SolrIndexCachedOperation.getCache(); if (cache != null) { cacheOperationManaged = true; } else { cache = new CatalogStructure(); SolrIndexCachedOperation.setCache(cache); } List<Product> products = readAllActiveProducts(page, pageSize); List<Long> productIds = BLCCollectionUtils.collectList(products, new TypedTransformer<Long>() { @Override public Long transform(Object input) { return ((Product) input).getId(); } }); solrIndexDao.populateCatalogStructure(productIds, SolrIndexCachedOperation.getCache()); List<Field> fields = fieldDao.readAllProductFields(); List<Locale> locales = getAllLocales(); Collection<SolrInputDocument> documents = new ArrayList<SolrInputDocument>(); for (Product product : products) { SolrInputDocument doc = buildDocument(product, fields, locales); //If someone overrides the buildDocument method and determines that they don't want a product //indexed, then they can return null. If the document is null it does not get added to //to the index. if (doc != null) { documents.add(doc); } } logDocuments(documents); if (!CollectionUtils.isEmpty(documents)) { SolrServer server = useReindexServer ? SolrContext.getReindexServer() : SolrContext.getServer(); server.add(documents); server.commit(); } TransactionUtils.finalizeTransaction(status, transactionManager, false); } catch (SolrServerException e) { TransactionUtils.finalizeTransaction(status, transactionManager, true); throw new ServiceException("Could not rebuild index", e); } catch (IOException e) { TransactionUtils.finalizeTransaction(status, transactionManager, true); throw new ServiceException("Could not rebuild index", e); } catch (RuntimeException e) { TransactionUtils.finalizeTransaction(status, transactionManager, true); throw e; } finally { if (!cacheOperationManaged) { SolrIndexCachedOperation.clearCache(); } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Built index - page: [%s], pageSize: [%s] in [%s]", page, pageSize, s.toLapString())); } } /** * This method to read all active products will be slow if you have a large catalog. In this case, you will want to * read the products in a different manner. For example, if you know the fields that will be indexed, you can configure * a DAO object to only load those fields. You could also use a JDBC based DAO for even faster access. This default * implementation is only suitable for small catalogs. * * @return the list of all active products to be used by the index building task */ protected List<Product> readAllActiveProducts() { return productDao.readAllActiveProducts(); } /** * This method to read active products utilizes paging to improve performance over {@link #readAllActiveProducts()}. * While not optimal, this will reduce the memory required to load large catalogs. * * It could still be improved for specific implementations by only loading fields that will be indexed or by accessing * the database via direct JDBC (instead of Hibernate). * * @return the list of all active products to be used by the index building task * @since 2.2.0 */ protected List<Product> readAllActiveProducts(int page, int pageSize) { return productDao.readAllActiveProducts(page, pageSize); } @Override public List<Locale> getAllLocales() { return localeService.findAllLocales(); } @Override public SolrInputDocument buildDocument(final Product product, List<Field> fields, List<Locale> locales) { final SolrInputDocument document = new SolrInputDocument(); attachBasicDocumentFields(product, document); // Keep track of searchable fields added to the index. We need to also add the search facets if // they weren't already added as a searchable field. List<String> addedProperties = new ArrayList<String>(); for (Field field : fields) { try { // Index the searchable fields if (field.getSearchable()) { List<FieldType> searchableFieldTypes = shs.getSearchableFieldTypes(field); for (FieldType sft : searchableFieldTypes) { Map<String, Object> propertyValues = getPropertyValues(product, field, sft, locales); // Build out the field for every prefix for (Entry<String, Object> entry : propertyValues.entrySet()) { String prefix = entry.getKey(); prefix = StringUtils.isBlank(prefix) ? prefix : prefix + "_"; String solrPropertyName = shs.getPropertyNameForFieldSearchable(field, sft, prefix); Object value = entry.getValue(); document.addField(solrPropertyName, value); addedProperties.add(solrPropertyName); } } } // Index the faceted field type as well FieldType facetType = field.getFacetFieldType(); if (facetType != null) { Map<String, Object> propertyValues = getPropertyValues(product, field, facetType, locales); // Build out the field for every prefix for (Entry<String, Object> entry : propertyValues.entrySet()) { String prefix = entry.getKey(); prefix = StringUtils.isBlank(prefix) ? prefix : prefix + "_"; String solrFacetPropertyName = shs.getPropertyNameForFieldFacet(field, prefix); Object value = entry.getValue(); if (!addedProperties.contains(solrFacetPropertyName)) { document.addField(solrFacetPropertyName, value); } } } } catch (Exception e) { LOG.error("Could not get value for property[" + field.getQualifiedFieldName() + "] for product id[" + product.getId() + "]", e); } } return document; } /** * Adds the ID, category, and explicitCategory fields for the product to the document * * @param product * @param document */ protected void attachBasicDocumentFields(Product product, SolrInputDocument document) { boolean cacheOperationManaged = false; try { CatalogStructure cache = SolrIndexCachedOperation.getCache(); if (cache != null) { cacheOperationManaged = true; } else { cache = new CatalogStructure(); SolrIndexCachedOperation.setCache(cache); solrIndexDao.populateCatalogStructure(Arrays.asList(product.getId()), SolrIndexCachedOperation.getCache()); } // Add the namespace and ID fields for this product document.addField(shs.getNamespaceFieldName(), shs.getCurrentNamespace()); document.addField(shs.getIdFieldName(), shs.getSolrDocumentId(document, product)); document.addField(shs.getProductIdFieldName(), product.getId()); extensionManager.getProxy().attachAdditionalBasicFields(product, document, shs); // The explicit categories are the ones defined by the product itself if (cache.getParentCategoriesByProduct().containsKey(product.getId())) { for (Long categoryId : cache.getParentCategoriesByProduct().get(product.getId())) { document.addField(shs.getExplicitCategoryFieldName(), shs.getCategoryId(categoryId)); String categorySortFieldName = shs.getCategorySortFieldName(shs.getCategoryId(categoryId)); String displayOrderKey = categoryId + "-" + shs.getProductId(product.getId()); BigDecimal displayOrder = cache.getDisplayOrdersByCategoryProduct().get(displayOrderKey); if (displayOrder == null) { displayOrderKey = categoryId + "-" + product.getId(); displayOrder = cache.getDisplayOrdersByCategoryProduct().get(displayOrderKey); } if (document.getField(categorySortFieldName) == null) { document.addField(categorySortFieldName, displayOrder); } // This is the entire tree of every category defined on the product buildFullCategoryHierarchy(document, cache, categoryId, new HashSet<Long>()); } } } finally { if (!cacheOperationManaged) { SolrIndexCachedOperation.clearCache(); } } } /** * Walk the category hierarchy upwards, adding a field for each level to the solr document * * @param document the solr document for the product * @param cache the catalog structure cache * @param categoryId the current category id */ protected void buildFullCategoryHierarchy(SolrInputDocument document, CatalogStructure cache, Long categoryId, Set<Long> indexedParents) { Long catIdToAdd = shs.getCategoryId(categoryId); Collection<Object> existingValues = document.getFieldValues(shs.getCategoryFieldName()); if (existingValues == null || !existingValues.contains(catIdToAdd)) { document.addField(shs.getCategoryFieldName(), catIdToAdd); } Set<Long> parents = cache.getParentCategoriesByCategory().get(categoryId); for (Long parent : parents) { if (!indexedParents.contains(parent)) { indexedParents.add(parent); buildFullCategoryHierarchy(document, cache, parent, indexedParents); } } } /** * Returns a map of prefix to value for the requested attributes. For example, if the requested field corresponds to * a Sku's description and the locales list has the en_US locale and the es_ES locale, the resulting map could be * * { "en_US" : "A description", * "es_ES" : "Una descripcion" } * * @param product * @param field * @param fieldType * @param locales * @return the value of the property * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ protected Map<String, Object> getPropertyValues(Product product, Field field, FieldType fieldType, List<Locale> locales) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { String propertyName = field.getPropertyName(); Map<String, Object> values = new HashMap<String, Object>(); if (extensionManager != null) { ExtensionResultStatusType result = extensionManager.getProxy().addPropertyValues(product, field, fieldType, values, propertyName, locales); if (ExtensionResultStatusType.NOT_HANDLED.equals(result)) { Object propertyValue; if (propertyName.contains(ATTR_MAP)) { propertyValue = PropertyUtils.getMappedProperty(product, ATTR_MAP, propertyName.substring(ATTR_MAP.length() + 1)); // It's possible that the value is an actual object, like ProductAttribute. We'll attempt to pull the // value field out of it if it exists. if (propertyValue != null) { try { propertyValue = PropertyUtils.getProperty(propertyValue, "value"); } catch (NoSuchMethodException e) { // Do nothing, we'll keep the existing value } } } else { propertyValue = PropertyUtils.getProperty(product, propertyName); } values.put("", propertyValue); } } return values; } /** * Converts a propertyName to one that is able to reference inside a map. For example, consider the property * in Product that references a List<ProductAttribute>, "productAttributes". Also consider the utility method * in Product called "mappedProductAttributes", which returns a map of the ProductAttributes keyed by the name * property in the ProductAttribute. Given the parameters "productAttributes.heatRange", "productAttributes", * "mappedProductAttributes" (which would represent a property called "productAttributes.heatRange" that * references a specific ProductAttribute inside of a product whose "name" property is equal to "heatRange", * this method will convert this property to mappedProductAttributes(heatRange).value, which is then usable * by the standard beanutils PropertyUtils class to get the value. * * @param propertyName * @param listPropertyName * @param mapPropertyName * @return the converted property name */ protected String convertToMappedProperty(String propertyName, String listPropertyName, String mapPropertyName) { String[] splitName = StringUtils.split(propertyName, "."); StringBuilder convertedProperty = new StringBuilder(); for (int i = 0; i < splitName.length; i++) { if (convertedProperty.length() > 0) { convertedProperty.append("."); } if (splitName[i].equals(listPropertyName)) { convertedProperty.append(mapPropertyName).append("("); convertedProperty.append(splitName[i + 1]).append(").value"); i++; } else { convertedProperty.append(splitName[i]); } } return convertedProperty.toString(); } @Override public Object[] saveState() { return new Object[] { BroadleafRequestContext.getBroadleafRequestContext(), SkuPricingConsiderationContext.getSkuPricingConsiderationContext(), SkuPricingConsiderationContext.getSkuPricingService(), SkuActiveDateConsiderationContext.getSkuActiveDatesService() }; } @Override @SuppressWarnings("rawtypes") public void restoreState(Object[] pack) { BroadleafRequestContext.setBroadleafRequestContext((BroadleafRequestContext) pack[0]); SkuPricingConsiderationContext.setSkuPricingConsiderationContext((HashMap) pack[1]); SkuPricingConsiderationContext.setSkuPricingService((DynamicSkuPricingService) pack[2]); SkuActiveDateConsiderationContext.setSkuActiveDatesService((DynamicSkuActiveDatesService) pack[3]); } @Override public void optimizeIndex(SolrServer server) throws ServiceException, IOException { try { if (LOG.isDebugEnabled()) { LOG.debug("Optimizing the index..."); } server.optimize(); } catch (SolrServerException e) { throw new ServiceException("Could not optimize index", e); } } @Override public void logDocuments(Collection<SolrInputDocument> documents) { if (LOG.isTraceEnabled()) { for (SolrInputDocument document : documents) { LOG.trace(document); } } } }
core/broadleaf-framework/src/main/java/org/broadleafcommerce/core/search/service/solr/SolrIndexServiceImpl.java
/* * #%L * BroadleafCommerce Framework * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.broadleafcommerce.core.search.service.solr; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.common.SolrInputDocument; import org.broadleafcommerce.common.exception.ExceptionHelper; import org.broadleafcommerce.common.exception.ServiceException; import org.broadleafcommerce.common.extension.ExtensionResultStatusType; import org.broadleafcommerce.common.locale.domain.Locale; import org.broadleafcommerce.common.locale.service.LocaleService; import org.broadleafcommerce.common.util.BLCCollectionUtils; import org.broadleafcommerce.common.util.StopWatch; import org.broadleafcommerce.common.util.TransactionUtils; import org.broadleafcommerce.common.util.TypedTransformer; import org.broadleafcommerce.common.web.BroadleafRequestContext; import org.broadleafcommerce.core.catalog.dao.ProductDao; import org.broadleafcommerce.core.catalog.domain.Product; import org.broadleafcommerce.core.catalog.service.dynamic.DynamicSkuActiveDatesService; import org.broadleafcommerce.core.catalog.service.dynamic.DynamicSkuPricingService; import org.broadleafcommerce.core.catalog.service.dynamic.SkuActiveDateConsiderationContext; import org.broadleafcommerce.core.catalog.service.dynamic.SkuPricingConsiderationContext; import org.broadleafcommerce.core.search.dao.CatalogStructure; import org.broadleafcommerce.core.search.dao.FieldDao; import org.broadleafcommerce.core.search.dao.SolrIndexDao; import org.broadleafcommerce.core.search.domain.Field; import org.broadleafcommerce.core.search.domain.solr.FieldType; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Resource; /** * Responsible for building and rebuilding the Solr index * * @author Andre Azzolini (apazzolini) * @author Jeff Fischer */ @Service("blSolrIndexService") public class SolrIndexServiceImpl implements SolrIndexService { private static final Log LOG = LogFactory.getLog(SolrIndexServiceImpl.class); protected final Object LOCK_OBJECT = new Object(); protected boolean IS_LOCKED = false; @Value("${solr.index.errorOnConcurrentReIndex}") protected boolean errorOnConcurrentReIndex = false; @Value("${solr.index.product.pageSize}") protected int pageSize; @Resource(name = "blProductDao") protected ProductDao productDao; @Resource(name = "blFieldDao") protected FieldDao fieldDao; @Resource(name = "blLocaleService") protected LocaleService localeService; @Resource(name = "blSolrHelperService") protected SolrHelperService shs; @Resource(name = "blSolrSearchServiceExtensionManager") protected SolrSearchServiceExtensionManager extensionManager; @Resource(name = "blTransactionManager") protected PlatformTransactionManager transactionManager; @Resource(name = "blSolrIndexDao") protected SolrIndexDao solrIndexDao; public static String ATTR_MAP = "productAttributes"; @Override public void performCachedOperation(SolrIndexCachedOperation.CacheOperation cacheOperation) throws ServiceException { try { CatalogStructure cache = new CatalogStructure(); SolrIndexCachedOperation.setCache(cache); cacheOperation.execute(); } finally { if (LOG.isInfoEnabled()) { LOG.info("Cleaning up Solr index cache from memory - size approx: " + getCacheSizeInMemoryApproximation(SolrIndexCachedOperation.getCache()) + " bytes"); } SolrIndexCachedOperation.clearCache(); } } protected int getCacheSizeInMemoryApproximation(CatalogStructure structure) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(structure); oos.close(); return baos.size(); } catch (IOException e) { throw ExceptionHelper.refineException(e); } } @Override public boolean isReindexInProcess() { synchronized (LOCK_OBJECT) { return IS_LOCKED; } } @Override public void rebuildIndex() throws ServiceException, IOException { synchronized (LOCK_OBJECT) { if (IS_LOCKED) { if (errorOnConcurrentReIndex) { throw new IllegalStateException("More than one thread attempting to concurrently reindex Solr."); } else { LOG.warn("There is more than one thread attempting to concurrently " + "reindex Solr. Failing additional threads gracefully. Check your configuration."); return; } } else { IS_LOCKED = true; } } try { LOG.info("Rebuilding the solr index..."); StopWatch s = new StopWatch(); LOG.info("Deleting the reindex core prior to rebuilding the index"); deleteAllReindexCoreDocuments(); Object[] pack = saveState(); try { final Long numProducts = productDao.readCountAllActiveProducts(); if (LOG.isDebugEnabled()) { LOG.debug("There are " + numProducts + " total products"); } performCachedOperation(new SolrIndexCachedOperation.CacheOperation() { @Override public void execute() throws ServiceException { int page = 0; while ((page * pageSize) < numProducts) { buildIncrementalIndex(page, pageSize); page++; } } }); optimizeIndex(SolrContext.getReindexServer()); } finally { restoreState(pack); } // Swap the active and the reindex cores shs.swapActiveCores(); LOG.info(String.format("Finished building index in %s", s.toLapString())); } finally { synchronized (LOCK_OBJECT) { IS_LOCKED = false; } } } /** * <p> * This method deletes all of the documents from {@link SolrContext#getReindexServer()} * * @throws ServiceException if there was a problem removing the documents * @deprecated use {@link #deleteAllReindexCoreDocuments()} instead */ @Deprecated protected void deleteAllDocuments() throws ServiceException { deleteAllReindexCoreDocuments(); } /** * <p> * This method deletes all of the documents from {@link SolrContext#getReindexServer()} * * @throws ServiceException if there was a problem removing the documents */ protected void deleteAllReindexCoreDocuments() throws ServiceException { try { String deleteQuery = shs.getNamespaceFieldName() + ":(\"" + shs.getCurrentNamespace() + "\")"; LOG.debug("Deleting by query: " + deleteQuery); SolrContext.getReindexServer().deleteByQuery(deleteQuery); SolrContext.getReindexServer().commit(); } catch (Exception e) { throw new ServiceException("Could not delete documents", e); } } protected void buildIncrementalIndex(int page, int pageSize) throws ServiceException { buildIncrementalIndex(page, pageSize, true); } @Override public void buildIncrementalIndex(int page, int pageSize, boolean useReindexServer) throws ServiceException { if (SolrIndexCachedOperation.getCache() == null) { LOG.warn("Consider using SolrIndexService.performCachedOperation() in combination with " + "SolrIndexService.buildIncrementalIndex() for better caching performance during solr indexing"); } TransactionStatus status = TransactionUtils.createTransaction("readProducts", TransactionDefinition.PROPAGATION_REQUIRED, transactionManager, true); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Building index - page: [%s], pageSize: [%s]", page, pageSize)); } StopWatch s = new StopWatch(); boolean cacheOperationManaged = false; try { CatalogStructure cache = SolrIndexCachedOperation.getCache(); if (cache != null) { cacheOperationManaged = true; } else { cache = new CatalogStructure(); SolrIndexCachedOperation.setCache(cache); } List<Product> products = readAllActiveProducts(page, pageSize); List<Long> productIds = BLCCollectionUtils.collectList(products, new TypedTransformer<Long>() { @Override public Long transform(Object input) { return ((Product) input).getId(); } }); solrIndexDao.populateCatalogStructure(productIds, SolrIndexCachedOperation.getCache()); List<Field> fields = fieldDao.readAllProductFields(); List<Locale> locales = getAllLocales(); Collection<SolrInputDocument> documents = new ArrayList<SolrInputDocument>(); for (Product product : products) { SolrInputDocument doc = buildDocument(product, fields, locales); //If someone overrides the buildDocument method and determines that they don't want a product //indexed, then they can return null. If the document is null it does not get added to //to the index. if (doc != null) { documents.add(doc); } } logDocuments(documents); if (!CollectionUtils.isEmpty(documents)) { SolrServer server = useReindexServer ? SolrContext.getReindexServer() : SolrContext.getServer(); server.add(documents); server.commit(); } TransactionUtils.finalizeTransaction(status, transactionManager, false); } catch (SolrServerException e) { TransactionUtils.finalizeTransaction(status, transactionManager, true); throw new ServiceException("Could not rebuild index", e); } catch (IOException e) { TransactionUtils.finalizeTransaction(status, transactionManager, true); throw new ServiceException("Could not rebuild index", e); } catch (RuntimeException e) { TransactionUtils.finalizeTransaction(status, transactionManager, true); throw e; } finally { if (!cacheOperationManaged) { SolrIndexCachedOperation.clearCache(); } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Built index - page: [%s], pageSize: [%s] in [%s]", page, pageSize, s.toLapString())); } } /** * This method to read all active products will be slow if you have a large catalog. In this case, you will want to * read the products in a different manner. For example, if you know the fields that will be indexed, you can configure * a DAO object to only load those fields. You could also use a JDBC based DAO for even faster access. This default * implementation is only suitable for small catalogs. * * @return the list of all active products to be used by the index building task */ protected List<Product> readAllActiveProducts() { return productDao.readAllActiveProducts(); } /** * This method to read active products utilizes paging to improve performance over {@link #readAllActiveProducts()}. * While not optimal, this will reduce the memory required to load large catalogs. * * It could still be improved for specific implementations by only loading fields that will be indexed or by accessing * the database via direct JDBC (instead of Hibernate). * * @return the list of all active products to be used by the index building task * @since 2.2.0 */ protected List<Product> readAllActiveProducts(int page, int pageSize) { return productDao.readAllActiveProducts(page, pageSize); } @Override public List<Locale> getAllLocales() { return localeService.findAllLocales(); } @Override public SolrInputDocument buildDocument(final Product product, List<Field> fields, List<Locale> locales) { final SolrInputDocument document = new SolrInputDocument(); attachBasicDocumentFields(product, document); // Keep track of searchable fields added to the index. We need to also add the search facets if // they weren't already added as a searchable field. List<String> addedProperties = new ArrayList<String>(); for (Field field : fields) { try { // Index the searchable fields if (field.getSearchable()) { List<FieldType> searchableFieldTypes = shs.getSearchableFieldTypes(field); for (FieldType sft : searchableFieldTypes) { Map<String, Object> propertyValues = getPropertyValues(product, field, sft, locales); // Build out the field for every prefix for (Entry<String, Object> entry : propertyValues.entrySet()) { String prefix = entry.getKey(); prefix = StringUtils.isBlank(prefix) ? prefix : prefix + "_"; String solrPropertyName = shs.getPropertyNameForFieldSearchable(field, sft, prefix); Object value = entry.getValue(); document.addField(solrPropertyName, value); addedProperties.add(solrPropertyName); } } } // Index the faceted field type as well FieldType facetType = field.getFacetFieldType(); if (facetType != null) { Map<String, Object> propertyValues = getPropertyValues(product, field, facetType, locales); // Build out the field for every prefix for (Entry<String, Object> entry : propertyValues.entrySet()) { String prefix = entry.getKey(); prefix = StringUtils.isBlank(prefix) ? prefix : prefix + "_"; String solrFacetPropertyName = shs.getPropertyNameForFieldFacet(field, prefix); Object value = entry.getValue(); if (!addedProperties.contains(solrFacetPropertyName)) { document.addField(solrFacetPropertyName, value); } } } } catch (Exception e) { LOG.error("Could not get value for property[" + field.getQualifiedFieldName() + "] for product id[" + product.getId() + "]", e); } } return document; } /** * Adds the ID, category, and explicitCategory fields for the product to the document * * @param product * @param document */ protected void attachBasicDocumentFields(Product product, SolrInputDocument document) { boolean cacheOperationManaged = false; try { CatalogStructure cache = SolrIndexCachedOperation.getCache(); if (cache != null) { cacheOperationManaged = true; } else { cache = new CatalogStructure(); SolrIndexCachedOperation.setCache(cache); solrIndexDao.populateCatalogStructure(Arrays.asList(product.getId()), SolrIndexCachedOperation.getCache()); } // Add the namespace and ID fields for this product document.addField(shs.getNamespaceFieldName(), shs.getCurrentNamespace()); document.addField(shs.getIdFieldName(), shs.getSolrDocumentId(document, product)); document.addField(shs.getProductIdFieldName(), product.getId()); extensionManager.getProxy().attachAdditionalBasicFields(product, document, shs); // The explicit categories are the ones defined by the product itself if (cache.getParentCategoriesByProduct().containsKey(product.getId())) { for (Long categoryId : cache.getParentCategoriesByProduct().get(product.getId())) { document.addField(shs.getExplicitCategoryFieldName(), shs.getCategoryId(categoryId)); String categorySortFieldName = shs.getCategorySortFieldName(shs.getCategoryId(categoryId)); String displayOrderKey = categoryId + "-" + shs.getProductId(product.getId()); BigDecimal displayOrder = cache.getDisplayOrdersByCategoryProduct().get(displayOrderKey); if (displayOrder == null) { displayOrderKey = categoryId + "-" + product.getId(); displayOrder = cache.getDisplayOrdersByCategoryProduct().get(displayOrderKey); } if (document.getField(categorySortFieldName) == null) { document.addField(categorySortFieldName, displayOrder); } // This is the entire tree of every category defined on the product buildFullCategoryHierarchy(document, cache, categoryId, new HashSet<Long>()); } } } finally { if (!cacheOperationManaged) { SolrIndexCachedOperation.clearCache(); } } } /** * Walk the category hierarchy upwards, adding a field for each level to the solr document * * @param document the solr document for the product * @param cache the catalog structure cache * @param categoryId the current category id */ protected void buildFullCategoryHierarchy(SolrInputDocument document, CatalogStructure cache, Long categoryId, Set<Long> indexedParents) { Long catIdToAdd = shs.getCategoryId(categoryId); Collection<Object> existingValues = document.getFieldValues(shs.getCategoryFieldName()); if (existingValues == null || !existingValues.contains(catIdToAdd)) { document.addField(shs.getCategoryFieldName(), catIdToAdd); } Set<Long> parents = cache.getParentCategoriesByCategory().get(categoryId); for (Long parent : parents) { if (!indexedParents.contains(parent)) { indexedParents.add(parent); buildFullCategoryHierarchy(document, cache, parent, indexedParents); } } } /** * Returns a map of prefix to value for the requested attributes. For example, if the requested field corresponds to * a Sku's description and the locales list has the en_US locale and the es_ES locale, the resulting map could be * * { "en_US" : "A description", * "es_ES" : "Una descripcion" } * * @param product * @param field * @param fieldType * @param locales * @return the value of the property * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ protected Map<String, Object> getPropertyValues(Product product, Field field, FieldType fieldType, List<Locale> locales) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { String propertyName = field.getPropertyName(); Map<String, Object> values = new HashMap<String, Object>(); if (extensionManager != null) { ExtensionResultStatusType result = extensionManager.getProxy().addPropertyValues(product, field, fieldType, values, propertyName, locales); if (ExtensionResultStatusType.NOT_HANDLED.equals(result)) { Object propertyValue; if (propertyName.contains(ATTR_MAP)) { propertyValue = PropertyUtils.getMappedProperty(product, ATTR_MAP, propertyName.substring(ATTR_MAP.length() + 1)); // It's possible that the value is an actual object, like ProductAttribute. We'll attempt to pull the // value field out of it if it exists. if (propertyValue != null) { try { propertyValue = PropertyUtils.getProperty(propertyValue, "value"); } catch (NoSuchMethodException e) { // Do nothing, we'll keep the existing value } } } else { propertyValue = PropertyUtils.getProperty(product, propertyName); } values.put("", propertyValue); } } return values; } /** * Converts a propertyName to one that is able to reference inside a map. For example, consider the property * in Product that references a List<ProductAttribute>, "productAttributes". Also consider the utility method * in Product called "mappedProductAttributes", which returns a map of the ProductAttributes keyed by the name * property in the ProductAttribute. Given the parameters "productAttributes.heatRange", "productAttributes", * "mappedProductAttributes" (which would represent a property called "productAttributes.heatRange" that * references a specific ProductAttribute inside of a product whose "name" property is equal to "heatRange", * this method will convert this property to mappedProductAttributes(heatRange).value, which is then usable * by the standard beanutils PropertyUtils class to get the value. * * @param propertyName * @param listPropertyName * @param mapPropertyName * @return the converted property name */ protected String convertToMappedProperty(String propertyName, String listPropertyName, String mapPropertyName) { String[] splitName = StringUtils.split(propertyName, "."); StringBuilder convertedProperty = new StringBuilder(); for (int i = 0; i < splitName.length; i++) { if (convertedProperty.length() > 0) { convertedProperty.append("."); } if (splitName[i].equals(listPropertyName)) { convertedProperty.append(mapPropertyName).append("("); convertedProperty.append(splitName[i + 1]).append(").value"); i++; } else { convertedProperty.append(splitName[i]); } } return convertedProperty.toString(); } @Override public Object[] saveState() { return new Object[] { BroadleafRequestContext.getBroadleafRequestContext(), SkuPricingConsiderationContext.getSkuPricingConsiderationContext(), SkuPricingConsiderationContext.getSkuPricingService(), SkuActiveDateConsiderationContext.getSkuActiveDatesService() }; } @Override @SuppressWarnings("rawtypes") public void restoreState(Object[] pack) { BroadleafRequestContext.setBroadleafRequestContext((BroadleafRequestContext) pack[0]); SkuPricingConsiderationContext.setSkuPricingConsiderationContext((HashMap) pack[1]); SkuPricingConsiderationContext.setSkuPricingService((DynamicSkuPricingService) pack[2]); SkuActiveDateConsiderationContext.setSkuActiveDatesService((DynamicSkuActiveDatesService) pack[3]); } @Override public void optimizeIndex(SolrServer server) throws ServiceException, IOException { try { if (LOG.isDebugEnabled()) { LOG.debug("Optimizing the index..."); } server.optimize(); } catch (SolrServerException e) { throw new ServiceException("Could not optimize index", e); } } @Override public void logDocuments(Collection<SolrInputDocument> documents) { if (LOG.isTraceEnabled()) { for (SolrInputDocument document : documents) { LOG.trace(document); } } } }
#1229 - Continue to invoke the old Solr document deletion method in case someone has overridden it
core/broadleaf-framework/src/main/java/org/broadleafcommerce/core/search/service/solr/SolrIndexServiceImpl.java
#1229 - Continue to invoke the old Solr document deletion method in case someone has overridden it
Java
apache-2.0
31c64437037fb0f7c790fe1adafba509db85ce7c
0
irfanah/jmeter,liwangbest/jmeter,ubikfsabbe/jmeter,kyroskoh/jmeter,ThiagoGarciaAlves/jmeter,DoctorQ/jmeter,liwangbest/jmeter,hemikak/jmeter,DoctorQ/jmeter,ra0077/jmeter,thomsonreuters/jmeter,etnetera/jmeter,fj11/jmeter,max3163/jmeter,ubikfsabbe/jmeter,ubikloadpack/jmeter,etnetera/jmeter,tuanhq/jmeter,hemikak/jmeter,tuanhq/jmeter,kschroeder/jmeter,liwangbest/jmeter,vherilier/jmeter,hemikak/jmeter,hizhangqi/jmeter-1,max3163/jmeter,kyroskoh/jmeter,ra0077/jmeter,thomsonreuters/jmeter,d0k1/jmeter,kschroeder/jmeter,thomsonreuters/jmeter,vherilier/jmeter,ThiagoGarciaAlves/jmeter,max3163/jmeter,ubikloadpack/jmeter,etnetera/jmeter,DoctorQ/jmeter,vherilier/jmeter,hizhangqi/jmeter-1,d0k1/jmeter,hemikak/jmeter,fj11/jmeter,d0k1/jmeter,fj11/jmeter,irfanah/jmeter,ra0077/jmeter,ubikloadpack/jmeter,kyroskoh/jmeter,vherilier/jmeter,d0k1/jmeter,ubikfsabbe/jmeter,max3163/jmeter,kschroeder/jmeter,tuanhq/jmeter,ra0077/jmeter,etnetera/jmeter,ThiagoGarciaAlves/jmeter,irfanah/jmeter,hizhangqi/jmeter-1,ubikfsabbe/jmeter,ubikloadpack/jmeter,etnetera/jmeter
/* * 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.jmeter.save; import java.io.BufferedReader; import java.io.CharArrayWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.table.DefaultTableModel; import org.apache.commons.collections.map.LinkedMap; import org.apache.commons.lang3.CharUtils; import org.apache.commons.lang3.StringUtils; import org.apache.jmeter.assertions.AssertionResult; import org.apache.jmeter.reporters.ResultCollector; import org.apache.jmeter.samplers.SampleEvent; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.samplers.SampleSaveConfiguration; import org.apache.jmeter.samplers.StatisticalSampleResult; import org.apache.jmeter.util.JMeterUtils; import org.apache.jmeter.visualizers.Visualizer; import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.reflect.Functor; import org.apache.jorphan.util.JMeterError; import org.apache.jorphan.util.JOrphanUtils; import org.apache.log.Logger; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.PatternMatcherInput; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; /** * This class provides a means for saving/reading test results as CSV files. */ // For unit tests, @see TestCSVSaveService public final class CSVSaveService { private static final Logger log = LoggingManager.getLoggerForClass(); // --------------------------------------------------------------------- // XML RESULT FILE CONSTANTS AND FIELD NAME CONSTANTS // --------------------------------------------------------------------- private static final String DATA_TYPE = "dataType"; // $NON-NLS-1$ private static final String FAILURE_MESSAGE = "failureMessage"; // $NON-NLS-1$ private static final String LABEL = "label"; // $NON-NLS-1$ private static final String RESPONSE_CODE = "responseCode"; // $NON-NLS-1$ private static final String RESPONSE_MESSAGE = "responseMessage"; // $NON-NLS-1$ private static final String SUCCESSFUL = "success"; // $NON-NLS-1$ private static final String THREAD_NAME = "threadName"; // $NON-NLS-1$ private static final String TIME_STAMP = "timeStamp"; // $NON-NLS-1$ // --------------------------------------------------------------------- // ADDITIONAL CSV RESULT FILE CONSTANTS AND FIELD NAME CONSTANTS // --------------------------------------------------------------------- private static final String CSV_ELAPSED = "elapsed"; // $NON-NLS-1$ private static final String CSV_BYTES = "bytes"; // $NON-NLS-1$ private static final String CSV_THREAD_COUNT1 = "grpThreads"; // $NON-NLS-1$ private static final String CSV_THREAD_COUNT2 = "allThreads"; // $NON-NLS-1$ private static final String CSV_SAMPLE_COUNT = "SampleCount"; // $NON-NLS-1$ private static final String CSV_ERROR_COUNT = "ErrorCount"; // $NON-NLS-1$ private static final String CSV_URL = "URL"; // $NON-NLS-1$ private static final String CSV_FILENAME = "Filename"; // $NON-NLS-1$ private static final String CSV_LATENCY = "Latency"; // $NON-NLS-1$ private static final String CSV_ENCODING = "Encoding"; // $NON-NLS-1$ private static final String CSV_HOSTNAME = "Hostname"; // $NON-NLS-1$ private static final String CSV_IDLETIME = "IdleTime"; // $NON-NLS-1$ // Used to enclose variable name labels, to distinguish from any of the // above labels private static final String VARIABLE_NAME_QUOTE_CHAR = "\""; // $NON-NLS-1$ // Initial config from properties static private final SampleSaveConfiguration _saveConfig = SampleSaveConfiguration .staticConfig(); // Date format to try if the time format does not parse as milliseconds // (this is the suggested value in jmeter.properties) private static final String DEFAULT_DATE_FORMAT_STRING = "MM/dd/yy HH:mm:ss"; // $NON-NLS-1$ private static final String LINE_SEP = System.getProperty("line.separator"); // $NON-NLS-1$ /** * Private constructor to prevent instantiation. */ private CSVSaveService() { } /** * Read Samples from a file; handles quoted strings. * * @param filename * input file * @param visualizer * where to send the results * @param resultCollector * the parent collector * @throws IOException */ public static void processSamples(String filename, Visualizer visualizer, ResultCollector resultCollector) throws IOException { BufferedReader dataReader = null; final boolean errorsOnly = resultCollector.isErrorLogging(); final boolean successOnly = resultCollector.isSuccessOnlyLogging(); try { dataReader = new BufferedReader(new InputStreamReader( new FileInputStream(filename), SaveService.getFileEncoding("UTF-8"))); dataReader.mark(400);// Enough to read the header column names // Get the first line, and see if it is the header String line = dataReader.readLine(); if (line == null) { throw new IOException(filename + ": unable to read header line"); } long lineNumber = 1; SampleSaveConfiguration saveConfig = CSVSaveService .getSampleSaveConfiguration(line, filename); if (saveConfig == null) {// not a valid header log.info(filename + " does not appear to have a valid header. Using default configuration."); saveConfig = (SampleSaveConfiguration) resultCollector .getSaveConfig().clone(); // may change the format later dataReader.reset(); // restart from beginning lineNumber = 0; } String[] parts; final char delim = saveConfig.getDelimiter().charAt(0); // TODO: does it matter that an empty line will terminate the loop? // CSV output files should never contain empty lines, so probably // not // If so, then need to check whether the reader is at EOF SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT_STRING); while ((parts = csvReadFile(dataReader, delim)).length != 0) { lineNumber++; SampleEvent event = CSVSaveService .makeResultFromDelimitedString(parts, saveConfig, lineNumber, dateFormat); if (event != null) { final SampleResult result = event.getResult(); if (ResultCollector.isSampleWanted(result.isSuccessful(), errorsOnly, successOnly)) { visualizer.add(result); } } } } finally { JOrphanUtils.closeQuietly(dataReader); } } /** * Make a SampleResult given a set of tokens * * @param parts * tokens parsed from the input * @param saveConfig * the save configuration (may be updated) * @param lineNumber * @param dateFormat * @return the sample result * * @throws JMeterError */ private static SampleEvent makeResultFromDelimitedString( final String[] parts, final SampleSaveConfiguration saveConfig, // may be updated final long lineNumber, DateFormat dateFormat) { SampleResult result = null; String hostname = "";// $NON-NLS-1$ long timeStamp = 0; long elapsed = 0; String text = null; String field = null; // Save the name for error reporting int i = 0; try { if (saveConfig.saveTimestamp()) { field = TIME_STAMP; text = parts[i++]; if (saveConfig.printMilliseconds()) { try { timeStamp = Long.parseLong(text); } catch (NumberFormatException e) {// see if this works log.warn(e.toString()); // method is only ever called from one thread at a time // so it's OK to use a static DateFormat Date stamp = dateFormat.parse(text); timeStamp = stamp.getTime(); log.warn("Setting date format to: " + DEFAULT_DATE_FORMAT_STRING); saveConfig.setFormatter(dateFormat); } } else if (saveConfig.formatter() != null) { Date stamp = saveConfig.formatter().parse(text); timeStamp = stamp.getTime(); } else { // can this happen? final String msg = "Unknown timestamp format"; log.warn(msg); throw new JMeterError(msg); } } if (saveConfig.saveTime()) { field = CSV_ELAPSED; text = parts[i++]; elapsed = Long.parseLong(text); } if (saveConfig.saveSampleCount()) { result = new StatisticalSampleResult(timeStamp, elapsed); } else { result = new SampleResult(timeStamp, elapsed); } if (saveConfig.saveLabel()) { field = LABEL; text = parts[i++]; result.setSampleLabel(text); } if (saveConfig.saveCode()) { field = RESPONSE_CODE; text = parts[i++]; result.setResponseCode(text); } if (saveConfig.saveMessage()) { field = RESPONSE_MESSAGE; text = parts[i++]; result.setResponseMessage(text); } if (saveConfig.saveThreadName()) { field = THREAD_NAME; text = parts[i++]; result.setThreadName(text); } if (saveConfig.saveDataType()) { field = DATA_TYPE; text = parts[i++]; result.setDataType(text); } if (saveConfig.saveSuccess()) { field = SUCCESSFUL; text = parts[i++]; result.setSuccessful(Boolean.valueOf(text).booleanValue()); } if (saveConfig.saveAssertionResultsFailureMessage()) { i++; // TODO - should this be restored? } if (saveConfig.saveBytes()) { field = CSV_BYTES; text = parts[i++]; result.setBytes(Integer.parseInt(text)); } if (saveConfig.saveThreadCounts()) { field = CSV_THREAD_COUNT1; text = parts[i++]; result.setGroupThreads(Integer.parseInt(text)); field = CSV_THREAD_COUNT2; text = parts[i++]; result.setAllThreads(Integer.parseInt(text)); } if (saveConfig.saveUrl()) { i++; // TODO: should this be restored? } if (saveConfig.saveFileName()) { field = CSV_FILENAME; text = parts[i++]; result.setResultFileName(text); } if (saveConfig.saveLatency()) { field = CSV_LATENCY; text = parts[i++]; result.setLatency(Long.parseLong(text)); } if (saveConfig.saveEncoding()) { field = CSV_ENCODING; text = parts[i++]; result.setEncodingAndType(text); } if (saveConfig.saveSampleCount()) { field = CSV_SAMPLE_COUNT; text = parts[i++]; result.setSampleCount(Integer.parseInt(text)); field = CSV_ERROR_COUNT; text = parts[i++]; result.setErrorCount(Integer.parseInt(text)); } if (saveConfig.saveHostname()) { field = CSV_HOSTNAME; hostname = parts[i++]; } if (saveConfig.saveIdleTime()) { field = CSV_IDLETIME; text = parts[i++]; result.setIdleTime(Long.parseLong(text)); } if (i + saveConfig.getVarCount() < parts.length) { log.warn("Line: " + lineNumber + ". Found " + parts.length + " fields, expected " + i + ". Extra fields have been ignored."); } } catch (NumberFormatException e) { log.warn("Error parsing field '" + field + "' at line " + lineNumber + " " + e); throw new JMeterError(e); } catch (ParseException e) { log.warn("Error parsing field '" + field + "' at line " + lineNumber + " " + e); throw new JMeterError(e); } catch (ArrayIndexOutOfBoundsException e) { log.warn("Insufficient columns to parse field '" + field + "' at line " + lineNumber); throw new JMeterError(e); } return new SampleEvent(result, "", hostname); } /** * Generates the field names for the output file * * @return the field names as a string */ public static String printableFieldNamesToString() { return printableFieldNamesToString(_saveConfig); } /** * Generates the field names for the output file * * @return the field names as a string */ public static String printableFieldNamesToString( SampleSaveConfiguration saveConfig) { StringBuilder text = new StringBuilder(); String delim = saveConfig.getDelimiter(); if (saveConfig.saveTimestamp()) { text.append(TIME_STAMP); text.append(delim); } if (saveConfig.saveTime()) { text.append(CSV_ELAPSED); text.append(delim); } if (saveConfig.saveLabel()) { text.append(LABEL); text.append(delim); } if (saveConfig.saveCode()) { text.append(RESPONSE_CODE); text.append(delim); } if (saveConfig.saveMessage()) { text.append(RESPONSE_MESSAGE); text.append(delim); } if (saveConfig.saveThreadName()) { text.append(THREAD_NAME); text.append(delim); } if (saveConfig.saveDataType()) { text.append(DATA_TYPE); text.append(delim); } if (saveConfig.saveSuccess()) { text.append(SUCCESSFUL); text.append(delim); } if (saveConfig.saveAssertionResultsFailureMessage()) { text.append(FAILURE_MESSAGE); text.append(delim); } if (saveConfig.saveBytes()) { text.append(CSV_BYTES); text.append(delim); } if (saveConfig.saveThreadCounts()) { text.append(CSV_THREAD_COUNT1); text.append(delim); text.append(CSV_THREAD_COUNT2); text.append(delim); } if (saveConfig.saveUrl()) { text.append(CSV_URL); text.append(delim); } if (saveConfig.saveFileName()) { text.append(CSV_FILENAME); text.append(delim); } if (saveConfig.saveLatency()) { text.append(CSV_LATENCY); text.append(delim); } if (saveConfig.saveEncoding()) { text.append(CSV_ENCODING); text.append(delim); } if (saveConfig.saveSampleCount()) { text.append(CSV_SAMPLE_COUNT); text.append(delim); text.append(CSV_ERROR_COUNT); text.append(delim); } if (saveConfig.saveHostname()) { text.append(CSV_HOSTNAME); text.append(delim); } if (saveConfig.saveIdleTime()) { text.append(CSV_IDLETIME); text.append(delim); } for (int i = 0; i < SampleEvent.getVarCount(); i++) { text.append(VARIABLE_NAME_QUOTE_CHAR); text.append(SampleEvent.getVarName(i)); text.append(VARIABLE_NAME_QUOTE_CHAR); text.append(delim); } String resultString = null; int size = text.length(); int delSize = delim.length(); // Strip off the trailing delimiter if (size >= delSize) { resultString = text.substring(0, size - delSize); } else { resultString = text.toString(); } return resultString; } // Map header names to set() methods private static final LinkedMap headerLabelMethods = new LinkedMap(); // These entries must be in the same order as columns are saved/restored. static { headerLabelMethods.put(TIME_STAMP, new Functor("setTimestamp")); headerLabelMethods.put(CSV_ELAPSED, new Functor("setTime")); headerLabelMethods.put(LABEL, new Functor("setLabel")); headerLabelMethods.put(RESPONSE_CODE, new Functor("setCode")); headerLabelMethods.put(RESPONSE_MESSAGE, new Functor("setMessage")); headerLabelMethods.put(THREAD_NAME, new Functor("setThreadName")); headerLabelMethods.put(DATA_TYPE, new Functor("setDataType")); headerLabelMethods.put(SUCCESSFUL, new Functor("setSuccess")); headerLabelMethods.put(FAILURE_MESSAGE, new Functor( "setAssertionResultsFailureMessage")); headerLabelMethods.put(CSV_BYTES, new Functor("setBytes")); // Both these are needed in the list even though they set the same // variable headerLabelMethods.put(CSV_THREAD_COUNT1, new Functor("setThreadCounts")); headerLabelMethods.put(CSV_THREAD_COUNT2, new Functor("setThreadCounts")); headerLabelMethods.put(CSV_URL, new Functor("setUrl")); headerLabelMethods.put(CSV_FILENAME, new Functor("setFileName")); headerLabelMethods.put(CSV_LATENCY, new Functor("setLatency")); headerLabelMethods.put(CSV_ENCODING, new Functor("setEncoding")); // Both these are needed in the list even though they set the same // variable headerLabelMethods.put(CSV_SAMPLE_COUNT, new Functor("setSampleCount")); headerLabelMethods.put(CSV_ERROR_COUNT, new Functor("setSampleCount")); headerLabelMethods.put(CSV_HOSTNAME, new Functor("setHostname")); headerLabelMethods.put(CSV_IDLETIME, new Functor("setIdleTime")); } /** * Parse a CSV header line * * @param headerLine * from CSV file * @param filename * name of file (for log message only) * @return config corresponding to the header items found or null if not a * header line */ public static SampleSaveConfiguration getSampleSaveConfiguration( String headerLine, String filename) { String[] parts = splitHeader(headerLine, _saveConfig.getDelimiter()); // Try // default // delimiter String delim = null; if (parts == null) { Perl5Matcher matcher = JMeterUtils.getMatcher(); PatternMatcherInput input = new PatternMatcherInput(headerLine); Pattern pattern = JMeterUtils.getPatternCache() // This assumes the header names are all single words with no spaces // word followed by 0 or more repeats of (non-word char + word) // where the non-word char (\2) is the same // e.g. abc|def|ghi but not abd|def~ghi .getPattern("\\w+((\\W)\\w+)?(\\2\\w+)*(\\2\"\\w+\")*", // $NON-NLS-1$ // last entries may be quoted strings Perl5Compiler.READ_ONLY_MASK); if (matcher.matches(input, pattern)) { delim = matcher.getMatch().group(2); parts = splitHeader(headerLine, delim);// now validate the // result } } if (parts == null) { return null; // failed to recognise the header } // We know the column names all exist, so create the config SampleSaveConfiguration saveConfig = new SampleSaveConfiguration(false); int varCount = 0; for (int i = 0; i < parts.length; i++) { String label = parts[i]; if (isVariableName(label)) { varCount++; } else { Functor set = (Functor) headerLabelMethods.get(label); set.invoke(saveConfig, new Boolean[] { Boolean.TRUE }); } } if (delim != null) { log.warn("Default delimiter '" + _saveConfig.getDelimiter() + "' did not work; using alternate '" + delim + "' for reading " + filename); saveConfig.setDelimiter(delim); } saveConfig.setVarCount(varCount); return saveConfig; } private static String[] splitHeader(String headerLine, String delim) { String parts[] = headerLine.split("\\Q" + delim);// $NON-NLS-1$ int previous = -1; // Check if the line is a header for (int i = 0; i < parts.length; i++) { final String label = parts[i]; // Check for Quoted variable names if (isVariableName(label)) { previous = Integer.MAX_VALUE; // they are always last continue; } int current = headerLabelMethods.indexOf(label); if (current == -1) { return null; // unknown column name } if (current <= previous) { log.warn("Column header number " + (i + 1) + " name " + label + " is out of order."); return null; // out of order } previous = current; } return parts; } /** * Check if the label is a variable name, i.e. is it enclosed in * double-quotes? * * @param label * column name from CSV file * @return if the label is enclosed in double-quotes */ private static boolean isVariableName(final String label) { return label.length() > 2 && label.startsWith(VARIABLE_NAME_QUOTE_CHAR) && label.endsWith(VARIABLE_NAME_QUOTE_CHAR); } /** * Method will save aggregate statistics as CSV. For now I put it here. Not * sure if it should go in the newer SaveService instead of here. if we ever * decide to get rid of this class, we'll need to move this method to the * new save service. * * @param data * List of data rows * @param writer * output file * @throws IOException */ public static void saveCSVStats(List<?> data, FileWriter writer) throws IOException { saveCSVStats(data, writer, null); } /** * Method will save aggregate statistics as CSV. For now I put it here. Not * sure if it should go in the newer SaveService instead of here. if we ever * decide to get rid of this class, we'll need to move this method to the * new save service. * * @param data * List of data rows * @param writer * output file * @param headers * header names (if non-null) * @throws IOException */ public static void saveCSVStats(List<?> data, FileWriter writer, String headers[]) throws IOException { final char DELIM = ','; final char SPECIALS[] = new char[] { DELIM, QUOTING_CHAR }; if (headers != null) { for (int i = 0; i < headers.length; i++) { if (i > 0) { writer.write(DELIM); } writer.write(quoteDelimiters(headers[i], SPECIALS)); } writer.write(LINE_SEP); } for (int idx = 0; idx < data.size(); idx++) { List<?> row = (List<?>) data.get(idx); for (int idy = 0; idy < row.size(); idy++) { if (idy > 0) { writer.write(DELIM); } Object item = row.get(idy); writer.write(quoteDelimiters(String.valueOf(item), SPECIALS)); } writer.write(LINE_SEP); } } /** * Method saves aggregate statistics (with header names) as CSV from a table * model. Same as {@link #saveCSVStats(List, FileWriter, String[])} except * that there is no need to create a List containing the data. * * @param model * table model containing the data * @param writer * output file * @throws IOException */ public static void saveCSVStats(DefaultTableModel model, FileWriter writer) throws IOException { saveCSVStats(model, writer, true); } /** * Method saves aggregate statistics as CSV from a table model. Same as * {@link #saveCSVStats(List, FileWriter, String[])} except that there is * no need to create a List containing the data. * * @param model * table model containing the data * @param writer * output file * @param saveHeaders * whether or not to save headers * @throws IOException */ public static void saveCSVStats(DefaultTableModel model, FileWriter writer, boolean saveHeaders) throws IOException { final char DELIM = ','; final char SPECIALS[] = new char[] { DELIM, QUOTING_CHAR }; final int columns = model.getColumnCount(); final int rows = model.getRowCount(); if (saveHeaders) { for (int i = 0; i < columns; i++) { if (i > 0) { writer.write(DELIM); } writer.write(quoteDelimiters(model.getColumnName(i), SPECIALS)); } writer.write(LINE_SEP); } for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { if (column > 0) { writer.write(DELIM); } Object item = model.getValueAt(row, column); writer.write(quoteDelimiters(String.valueOf(item), SPECIALS)); } writer.write(LINE_SEP); } } /** * Convert a result into a string, where the fields of the result are * separated by the default delimiter. * * @param event * the sample event to be converted * @return the separated value representation of the result */ public static String resultToDelimitedString(SampleEvent event) { return resultToDelimitedString(event, event.getResult().getSaveConfig() .getDelimiter()); } /** * Convert a result into a string, where the fields of the result are * separated by a specified String. * * @param event * the sample event to be converted * @param delimiter * the separation string * @return the separated value representation of the result */ public static String resultToDelimitedString(SampleEvent event, final String delimiter) { /* * Class to handle generating the delimited string. - adds the delimiter * if not the first call - quotes any strings that require it */ final class StringQuoter { final StringBuilder sb = new StringBuilder(); private final char[] specials; private boolean addDelim; public StringQuoter(char delim) { specials = new char[] { delim, QUOTING_CHAR, CharUtils.CR, CharUtils.LF }; addDelim = false; // Don't add delimiter first time round } private void addDelim() { if (addDelim) { sb.append(specials[0]); } else { addDelim = true; } } // These methods handle parameters that could contain delimiters or // quotes: public void append(String s) { addDelim(); // if (s == null) return; sb.append(quoteDelimiters(s, specials)); } public void append(Object obj) { append(String.valueOf(obj)); } // These methods handle parameters that cannot contain delimiters or // quotes public void append(int i) { addDelim(); sb.append(i); } public void append(long l) { addDelim(); sb.append(l); } public void append(boolean b) { addDelim(); sb.append(b); } @Override public String toString() { return sb.toString(); } } StringQuoter text = new StringQuoter(delimiter.charAt(0)); SampleResult sample = event.getResult(); SampleSaveConfiguration saveConfig = sample.getSaveConfig(); if (saveConfig.saveTimestamp()) { if (saveConfig.printMilliseconds()) { text.append(sample.getTimeStamp()); } else if (saveConfig.formatter() != null) { String stamp = saveConfig.formatter().format( new Date(sample.getTimeStamp())); text.append(stamp); } } if (saveConfig.saveTime()) { text.append(sample.getTime()); } if (saveConfig.saveLabel()) { text.append(sample.getSampleLabel()); } if (saveConfig.saveCode()) { text.append(sample.getResponseCode()); } if (saveConfig.saveMessage()) { text.append(sample.getResponseMessage()); } if (saveConfig.saveThreadName()) { text.append(sample.getThreadName()); } if (saveConfig.saveDataType()) { text.append(sample.getDataType()); } if (saveConfig.saveSuccess()) { text.append(sample.isSuccessful()); } if (saveConfig.saveAssertionResultsFailureMessage()) { String message = null; AssertionResult[] results = sample.getAssertionResults(); if (results != null) { // Find the first non-null message for (int i = 0; i < results.length; i++) { message = results[i].getFailureMessage(); if (message != null) { break; } } } if (message != null) { text.append(message); } else { text.append(""); // Need to append something so delimiter is // added } } if (saveConfig.saveBytes()) { text.append(sample.getBytes()); } if (saveConfig.saveThreadCounts()) { text.append(sample.getGroupThreads()); text.append(sample.getAllThreads()); } if (saveConfig.saveUrl()) { text.append(sample.getURL()); } if (saveConfig.saveFileName()) { text.append(sample.getResultFileName()); } if (saveConfig.saveLatency()) { text.append(sample.getLatency()); } if (saveConfig.saveEncoding()) { text.append(sample.getDataEncodingWithDefault()); } if (saveConfig.saveSampleCount()) { // Need both sample and error count to be any use text.append(sample.getSampleCount()); text.append(sample.getErrorCount()); } if (saveConfig.saveHostname()) { text.append(event.getHostname()); } if (saveConfig.saveIdleTime()) { text.append(event.getResult().getIdleTime()); } for (int i = 0; i < SampleEvent.getVarCount(); i++) { text.append(event.getVarValue(i)); } return text.toString(); } // =================================== CSV quote/unquote handling // ============================== /* * Private versions of what might eventually be part of Commons-CSV or * Commons-Lang/Io... */ /* * <p> Returns a <code>String</code> value for a character-delimited column * value enclosed in the quote character, if required. </p> * * <p> If the value contains a special character, then the String value is * returned enclosed in the quote character. </p> * * <p> Any quote characters in the value are doubled up. </p> * * <p> If the value does not contain any special characters, then the String * value is returned unchanged. </p> * * <p> N.B. The list of special characters includes the quote character. * </p> * * @param input the input column String, may be null (without enclosing * delimiters) * * @param specialChars special characters; second one must be the quote * character * * @return the input String, enclosed in quote characters if the value * contains a special character, <code>null</code> for null string input */ private static String quoteDelimiters(String input, char[] specialChars) { if (StringUtils.containsNone(input, specialChars)) { return input; } StringBuilder buffer = new StringBuilder(input.length() + 10); final char quote = specialChars[1]; buffer.append(quote); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c == quote) { buffer.append(quote); // double the quote char } buffer.append(c); } buffer.append(quote); return buffer.toString(); } // State of the parser private static final int INITIAL = 0, PLAIN = 1, QUOTED = 2, EMBEDDEDQUOTE = 3; public static final char QUOTING_CHAR = '"'; /** * Reads from file and splits input into strings according to the delimiter, * taking note of quoted strings. * <p> * Handles DOS (CRLF), Unix (LF), and Mac (CR) line-endings equally. * <p> * A blank line - or a quoted blank line - both return an array containing * a single empty String. * @param infile * input file - must support mark(1) * @param delim * delimiter (e.g. comma) * @return array of strings, will be empty if there is no data, i.e. if the input is at EOF. * @throws IOException * also for unexpected quote characters */ public static String[] csvReadFile(BufferedReader infile, char delim) throws IOException { int ch; int state = INITIAL; List<String> list = new ArrayList<String>(); CharArrayWriter baos = new CharArrayWriter(200); boolean push = false; while (-1 != (ch = infile.read())) { push = false; switch (state) { case INITIAL: if (ch == QUOTING_CHAR) { state = QUOTED; } else if (isDelimOrEOL(delim, ch)) { push = true; } else { baos.write(ch); state = PLAIN; } break; case PLAIN: if (ch == QUOTING_CHAR) { baos.write(ch); throw new IOException( "Cannot have quote-char in plain field:[" + baos.toString() + "]"); } else if (isDelimOrEOL(delim, ch)) { push = true; state = INITIAL; } else { baos.write(ch); } break; case QUOTED: if (ch == QUOTING_CHAR) { state = EMBEDDEDQUOTE; } else { baos.write(ch); } break; case EMBEDDEDQUOTE: if (ch == QUOTING_CHAR) { baos.write(QUOTING_CHAR); // doubled quote => quote state = QUOTED; } else if (isDelimOrEOL(delim, ch)) { push = true; state = INITIAL; } else { baos.write(QUOTING_CHAR); throw new IOException( "Cannot have single quote-char in quoted field:[" + baos.toString() + "]"); } break; } // switch(state) if (push) { if (ch == '\r') {// Remove following \n if present infile.mark(1); if (infile.read() != '\n') { infile.reset(); // did not find \n, put the character // back } } String s = baos.toString(); list.add(s); baos.reset(); } if ((ch == '\n' || ch == '\r') && state != QUOTED) { break; } } // while not EOF if (ch == -1) {// EOF (or end of string) so collect any remaining data if (state == QUOTED) { throw new IOException(state + " Missing trailing quote-char in quoted field:[\"" + baos.toString() + "]"); } // Do we have some data, or a trailing empty field? if (baos.size() > 0 // we have some data || push // we've started a field || state == EMBEDDEDQUOTE // Just seen "" ) { list.add(baos.toString()); } } return list.toArray(new String[list.size()]); } private static boolean isDelimOrEOL(char delim, int ch) { return ch == delim || ch == '\n' || ch == '\r'; } /** * Reads from String and splits into strings according to the delimiter, * taking note of quoted strings. * * Handles DOS (CRLF), Unix (LF), and Mac (CR) line-endings equally. * * @param line * input line * @param delim * delimiter (e.g. comma) * @return array of strings * @throws IOException * also for unexpected quote characters */ public static String[] csvSplitString(String line, char delim) throws IOException { return csvReadFile(new BufferedReader(new StringReader(line)), delim); } }
src/core/org/apache/jmeter/save/CSVSaveService.java
/* * 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.jmeter.save; import java.io.BufferedReader; import java.io.CharArrayWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.table.DefaultTableModel; import org.apache.commons.collections.map.LinkedMap; import org.apache.commons.lang3.CharUtils; import org.apache.commons.lang3.StringUtils; import org.apache.jmeter.assertions.AssertionResult; import org.apache.jmeter.reporters.ResultCollector; import org.apache.jmeter.samplers.SampleEvent; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.samplers.SampleSaveConfiguration; import org.apache.jmeter.samplers.StatisticalSampleResult; import org.apache.jmeter.util.JMeterUtils; import org.apache.jmeter.visualizers.Visualizer; import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.reflect.Functor; import org.apache.jorphan.util.JMeterError; import org.apache.jorphan.util.JOrphanUtils; import org.apache.log.Logger; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.PatternMatcherInput; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; /** * This class provides a means for saving/reading test results as CSV files. */ // For unit tests, @see TestCSVSaveService public final class CSVSaveService { private static final Logger log = LoggingManager.getLoggerForClass(); // --------------------------------------------------------------------- // XML RESULT FILE CONSTANTS AND FIELD NAME CONSTANTS // --------------------------------------------------------------------- private static final String DATA_TYPE = "dataType"; // $NON-NLS-1$ private static final String FAILURE_MESSAGE = "failureMessage"; // $NON-NLS-1$ private static final String LABEL = "label"; // $NON-NLS-1$ private static final String RESPONSE_CODE = "responseCode"; // $NON-NLS-1$ private static final String RESPONSE_MESSAGE = "responseMessage"; // $NON-NLS-1$ private static final String SUCCESSFUL = "success"; // $NON-NLS-1$ private static final String THREAD_NAME = "threadName"; // $NON-NLS-1$ private static final String TIME_STAMP = "timeStamp"; // $NON-NLS-1$ // --------------------------------------------------------------------- // ADDITIONAL CSV RESULT FILE CONSTANTS AND FIELD NAME CONSTANTS // --------------------------------------------------------------------- private static final String CSV_ELAPSED = "elapsed"; // $NON-NLS-1$ private static final String CSV_BYTES = "bytes"; // $NON-NLS-1$ private static final String CSV_THREAD_COUNT1 = "grpThreads"; // $NON-NLS-1$ private static final String CSV_THREAD_COUNT2 = "allThreads"; // $NON-NLS-1$ private static final String CSV_SAMPLE_COUNT = "SampleCount"; // $NON-NLS-1$ private static final String CSV_ERROR_COUNT = "ErrorCount"; // $NON-NLS-1$ private static final String CSV_URL = "URL"; // $NON-NLS-1$ private static final String CSV_FILENAME = "Filename"; // $NON-NLS-1$ private static final String CSV_LATENCY = "Latency"; // $NON-NLS-1$ private static final String CSV_ENCODING = "Encoding"; // $NON-NLS-1$ private static final String CSV_HOSTNAME = "Hostname"; // $NON-NLS-1$ private static final String CSV_IDLETIME = "IdleTime"; // $NON-NLS-1$ // Used to enclose variable name labels, to distinguish from any of the // above labels private static final String VARIABLE_NAME_QUOTE_CHAR = "\""; // $NON-NLS-1$ // Initial config from properties static private final SampleSaveConfiguration _saveConfig = SampleSaveConfiguration .staticConfig(); // Date format to try if the time format does not parse as milliseconds // (this is the suggested value in jmeter.properties) private static final String DEFAULT_DATE_FORMAT_STRING = "MM/dd/yy HH:mm:ss"; // $NON-NLS-1$ private static final String LINE_SEP = System.getProperty("line.separator"); // $NON-NLS-1$ /** * Private constructor to prevent instantiation. */ private CSVSaveService() { } /** * Read Samples from a file; handles quoted strings. * * @param filename * input file * @param visualizer * where to send the results * @param resultCollector * the parent collector * @throws IOException */ public static void processSamples(String filename, Visualizer visualizer, ResultCollector resultCollector) throws IOException { BufferedReader dataReader = null; final boolean errorsOnly = resultCollector.isErrorLogging(); final boolean successOnly = resultCollector.isSuccessOnlyLogging(); try { dataReader = new BufferedReader(new InputStreamReader( new FileInputStream(filename), SaveService.getFileEncoding("UTF-8"))); dataReader.mark(400);// Enough to read the header column names // Get the first line, and see if it is the header String line = dataReader.readLine(); if (line == null) { throw new IOException(filename + ": unable to read header line"); } long lineNumber = 1; SampleSaveConfiguration saveConfig = CSVSaveService .getSampleSaveConfiguration(line, filename); if (saveConfig == null) {// not a valid header log.info(filename + " does not appear to have a valid header. Using default configuration."); saveConfig = (SampleSaveConfiguration) resultCollector .getSaveConfig().clone(); // may change the format later dataReader.reset(); // restart from beginning lineNumber = 0; } String[] parts; final char delim = saveConfig.getDelimiter().charAt(0); // TODO: does it matter that an empty line will terminate the loop? // CSV output files should never contain empty lines, so probably // not // If so, then need to check whether the reader is at EOF SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT_STRING); while ((parts = csvReadFile(dataReader, delim)).length != 0) { lineNumber++; SampleEvent event = CSVSaveService .makeResultFromDelimitedString(parts, saveConfig, lineNumber, dateFormat); if (event != null) { final SampleResult result = event.getResult(); if (ResultCollector.isSampleWanted(result.isSuccessful(), errorsOnly, successOnly)) { visualizer.add(result); } } } } finally { JOrphanUtils.closeQuietly(dataReader); } } /** * Make a SampleResult given a set of tokens * * @param parts * tokens parsed from the input * @param saveConfig * the save configuration (may be updated) * @param lineNumber * @param dateFormat * @return the sample result * * @throws JMeterError */ private static SampleEvent makeResultFromDelimitedString( final String[] parts, final SampleSaveConfiguration saveConfig, // may be updated final long lineNumber, DateFormat dateFormat) { SampleResult result = null; String hostname = "";// $NON-NLS-1$ long timeStamp = 0; long elapsed = 0; String text = null; String field = null; // Save the name for error reporting int i = 0; try { if (saveConfig.saveTimestamp()) { field = TIME_STAMP; text = parts[i++]; if (saveConfig.printMilliseconds()) { try { timeStamp = Long.parseLong(text); } catch (NumberFormatException e) {// see if this works log.warn(e.toString()); // method is only ever called from one thread at a time // so it's OK to use a static DateFormat Date stamp = dateFormat.parse(text); timeStamp = stamp.getTime(); log.warn("Setting date format to: " + DEFAULT_DATE_FORMAT_STRING); saveConfig.setFormatter(dateFormat); } } else if (saveConfig.formatter() != null) { Date stamp = saveConfig.formatter().parse(text); timeStamp = stamp.getTime(); } else { // can this happen? final String msg = "Unknown timestamp format"; log.warn(msg); throw new JMeterError(msg); } } if (saveConfig.saveTime()) { field = CSV_ELAPSED; text = parts[i++]; elapsed = Long.parseLong(text); } if (saveConfig.saveSampleCount()) { result = new StatisticalSampleResult(timeStamp, elapsed); } else { result = new SampleResult(timeStamp, elapsed); } if (saveConfig.saveLabel()) { field = LABEL; text = parts[i++]; result.setSampleLabel(text); } if (saveConfig.saveCode()) { field = RESPONSE_CODE; text = parts[i++]; result.setResponseCode(text); } if (saveConfig.saveMessage()) { field = RESPONSE_MESSAGE; text = parts[i++]; result.setResponseMessage(text); } if (saveConfig.saveThreadName()) { field = THREAD_NAME; text = parts[i++]; result.setThreadName(text); } if (saveConfig.saveDataType()) { field = DATA_TYPE; text = parts[i++]; result.setDataType(text); } if (saveConfig.saveSuccess()) { field = SUCCESSFUL; text = parts[i++]; result.setSuccessful(Boolean.valueOf(text).booleanValue()); } if (saveConfig.saveAssertionResultsFailureMessage()) { i++; // TODO - should this be restored? } if (saveConfig.saveBytes()) { field = CSV_BYTES; text = parts[i++]; result.setBytes(Integer.parseInt(text)); } if (saveConfig.saveThreadCounts()) { field = CSV_THREAD_COUNT1; text = parts[i++]; result.setGroupThreads(Integer.parseInt(text)); field = CSV_THREAD_COUNT2; text = parts[i++]; result.setAllThreads(Integer.parseInt(text)); } if (saveConfig.saveUrl()) { i++; // TODO: should this be restored? } if (saveConfig.saveFileName()) { field = CSV_FILENAME; text = parts[i++]; result.setResultFileName(text); } if (saveConfig.saveLatency()) { field = CSV_LATENCY; text = parts[i++]; result.setLatency(Long.parseLong(text)); } if (saveConfig.saveEncoding()) { field = CSV_ENCODING; text = parts[i++]; result.setEncodingAndType(text); } if (saveConfig.saveSampleCount()) { field = CSV_SAMPLE_COUNT; text = parts[i++]; result.setSampleCount(Integer.parseInt(text)); field = CSV_ERROR_COUNT; text = parts[i++]; result.setErrorCount(Integer.parseInt(text)); } if (saveConfig.saveHostname()) { field = CSV_HOSTNAME; hostname = parts[i++]; } if (saveConfig.saveIdleTime()) { field = CSV_IDLETIME; text = parts[i++]; result.setIdleTime(Long.parseLong(text)); } if (i + saveConfig.getVarCount() < parts.length) { log.warn("Line: " + lineNumber + ". Found " + parts.length + " fields, expected " + i + ". Extra fields have been ignored."); } } catch (NumberFormatException e) { log.warn("Error parsing field '" + field + "' at line " + lineNumber + " " + e); throw new JMeterError(e); } catch (ParseException e) { log.warn("Error parsing field '" + field + "' at line " + lineNumber + " " + e); throw new JMeterError(e); } catch (ArrayIndexOutOfBoundsException e) { log.warn("Insufficient columns to parse field '" + field + "' at line " + lineNumber); throw new JMeterError(e); } return new SampleEvent(result, "", hostname); } /** * Generates the field names for the output file * * @return the field names as a string */ public static String printableFieldNamesToString() { return printableFieldNamesToString(_saveConfig); } /** * Generates the field names for the output file * * @return the field names as a string */ public static String printableFieldNamesToString( SampleSaveConfiguration saveConfig) { StringBuilder text = new StringBuilder(); String delim = saveConfig.getDelimiter(); if (saveConfig.saveTimestamp()) { text.append(TIME_STAMP); text.append(delim); } if (saveConfig.saveTime()) { text.append(CSV_ELAPSED); text.append(delim); } if (saveConfig.saveLabel()) { text.append(LABEL); text.append(delim); } if (saveConfig.saveCode()) { text.append(RESPONSE_CODE); text.append(delim); } if (saveConfig.saveMessage()) { text.append(RESPONSE_MESSAGE); text.append(delim); } if (saveConfig.saveThreadName()) { text.append(THREAD_NAME); text.append(delim); } if (saveConfig.saveDataType()) { text.append(DATA_TYPE); text.append(delim); } if (saveConfig.saveSuccess()) { text.append(SUCCESSFUL); text.append(delim); } if (saveConfig.saveAssertionResultsFailureMessage()) { text.append(FAILURE_MESSAGE); text.append(delim); } if (saveConfig.saveBytes()) { text.append(CSV_BYTES); text.append(delim); } if (saveConfig.saveThreadCounts()) { text.append(CSV_THREAD_COUNT1); text.append(delim); text.append(CSV_THREAD_COUNT2); text.append(delim); } if (saveConfig.saveUrl()) { text.append(CSV_URL); text.append(delim); } if (saveConfig.saveFileName()) { text.append(CSV_FILENAME); text.append(delim); } if (saveConfig.saveLatency()) { text.append(CSV_LATENCY); text.append(delim); } if (saveConfig.saveEncoding()) { text.append(CSV_ENCODING); text.append(delim); } if (saveConfig.saveSampleCount()) { text.append(CSV_SAMPLE_COUNT); text.append(delim); text.append(CSV_ERROR_COUNT); text.append(delim); } if (saveConfig.saveHostname()) { text.append(CSV_HOSTNAME); text.append(delim); } if (saveConfig.saveIdleTime()) { text.append(CSV_IDLETIME); text.append(delim); } for (int i = 0; i < SampleEvent.getVarCount(); i++) { text.append(VARIABLE_NAME_QUOTE_CHAR); text.append(SampleEvent.getVarName(i)); text.append(VARIABLE_NAME_QUOTE_CHAR); text.append(delim); } String resultString = null; int size = text.length(); int delSize = delim.length(); // Strip off the trailing delimiter if (size >= delSize) { resultString = text.substring(0, size - delSize); } else { resultString = text.toString(); } return resultString; } // Map header names to set() methods private static final LinkedMap headerLabelMethods = new LinkedMap(); // These entries must be in the same order as columns are saved/restored. static { headerLabelMethods.put(TIME_STAMP, new Functor("setTimestamp")); headerLabelMethods.put(CSV_ELAPSED, new Functor("setTime")); headerLabelMethods.put(LABEL, new Functor("setLabel")); headerLabelMethods.put(RESPONSE_CODE, new Functor("setCode")); headerLabelMethods.put(RESPONSE_MESSAGE, new Functor("setMessage")); headerLabelMethods.put(THREAD_NAME, new Functor("setThreadName")); headerLabelMethods.put(DATA_TYPE, new Functor("setDataType")); headerLabelMethods.put(SUCCESSFUL, new Functor("setSuccess")); headerLabelMethods.put(FAILURE_MESSAGE, new Functor( "setAssertionResultsFailureMessage")); headerLabelMethods.put(CSV_BYTES, new Functor("setBytes")); // Both these are needed in the list even though they set the same // variable headerLabelMethods.put(CSV_THREAD_COUNT1, new Functor("setThreadCounts")); headerLabelMethods.put(CSV_THREAD_COUNT2, new Functor("setThreadCounts")); headerLabelMethods.put(CSV_URL, new Functor("setUrl")); headerLabelMethods.put(CSV_FILENAME, new Functor("setFileName")); headerLabelMethods.put(CSV_LATENCY, new Functor("setLatency")); headerLabelMethods.put(CSV_ENCODING, new Functor("setEncoding")); // Both these are needed in the list even though they set the same // variable headerLabelMethods.put(CSV_SAMPLE_COUNT, new Functor("setSampleCount")); headerLabelMethods.put(CSV_ERROR_COUNT, new Functor("setSampleCount")); headerLabelMethods.put(CSV_HOSTNAME, new Functor("setHostname")); headerLabelMethods.put(CSV_IDLETIME, new Functor("setIdleTime")); } /** * Parse a CSV header line * * @param headerLine * from CSV file * @param filename * name of file (for log message only) * @return config corresponding to the header items found or null if not a * header line */ public static SampleSaveConfiguration getSampleSaveConfiguration( String headerLine, String filename) { String[] parts = splitHeader(headerLine, _saveConfig.getDelimiter()); // Try // default // delimiter String delim = null; if (parts == null) { Perl5Matcher matcher = JMeterUtils.getMatcher(); PatternMatcherInput input = new PatternMatcherInput(headerLine); Pattern pattern = JMeterUtils.getPatternCache() // This assumes the header names are all single words with no spaces // word followed by 0 or more repeats of (non-word char + word) // where the non-word char (\2) is the same // e.g. abc|def|ghi but not abd|def~ghi .getPattern("\\w+((\\W)\\w+)?(\\2\\w+)*(\\2\"\\w+\")*", // $NON-NLS-1$ // last entries may be quoted strings Perl5Compiler.READ_ONLY_MASK); if (matcher.matches(input, pattern)) { delim = matcher.getMatch().group(2); parts = splitHeader(headerLine, delim);// now validate the // result } } if (parts == null) { return null; // failed to recognise the header } // We know the column names all exist, so create the config SampleSaveConfiguration saveConfig = new SampleSaveConfiguration(false); int varCount = 0; for (int i = 0; i < parts.length; i++) { String label = parts[i]; if (isVariableName(label)) { varCount++; } else { Functor set = (Functor) headerLabelMethods.get(label); set.invoke(saveConfig, new Boolean[] { Boolean.TRUE }); } } if (delim != null) { log.warn("Default delimiter '" + _saveConfig.getDelimiter() + "' did not work; using alternate '" + delim + "' for reading " + filename); saveConfig.setDelimiter(delim); } saveConfig.setVarCount(varCount); return saveConfig; } private static String[] splitHeader(String headerLine, String delim) { String parts[] = headerLine.split("\\Q" + delim);// $NON-NLS-1$ int previous = -1; // Check if the line is a header for (int i = 0; i < parts.length; i++) { final String label = parts[i]; // Check for Quoted variable names if (isVariableName(label)) { previous = Integer.MAX_VALUE; // they are always last continue; } int current = headerLabelMethods.indexOf(label); if (current == -1) { return null; // unknown column name } if (current <= previous) { log.warn("Column header number " + (i + 1) + " name " + label + " is out of order."); return null; // out of order } previous = current; } return parts; } /** * Check if the label is a variable name, i.e. is it enclosed in * double-quotes? * * @param label * column name from CSV file * @return if the label is enclosed in double-quotes */ private static boolean isVariableName(final String label) { return label.length() > 2 && label.startsWith(VARIABLE_NAME_QUOTE_CHAR) && label.endsWith(VARIABLE_NAME_QUOTE_CHAR); } /** * Method will save aggregate statistics as CSV. For now I put it here. Not * sure if it should go in the newer SaveService instead of here. if we ever * decide to get rid of this class, we'll need to move this method to the * new save service. * * @param data * List of data rows * @param writer * output file * @throws IOException */ public static void saveCSVStats(List<?> data, FileWriter writer) throws IOException { saveCSVStats(data, writer, null); } /** * Method will save aggregate statistics as CSV. For now I put it here. Not * sure if it should go in the newer SaveService instead of here. if we ever * decide to get rid of this class, we'll need to move this method to the * new save service. * * @param data * List of data rows * @param writer * output file * @param headers * header names (if non-null) * @throws IOException */ public static void saveCSVStats(List<?> data, FileWriter writer, String headers[]) throws IOException { final char DELIM = ','; final char SPECIALS[] = new char[] { DELIM, QUOTING_CHAR }; if (headers != null) { for (int i = 0; i < headers.length; i++) { if (i > 0) { writer.write(DELIM); } writer.write(quoteDelimiters(headers[i], SPECIALS)); } writer.write(LINE_SEP); } for (int idx = 0; idx < data.size(); idx++) { List<?> row = (List<?>) data.get(idx); for (int idy = 0; idy < row.size(); idy++) { if (idy > 0) { writer.write(DELIM); } Object item = row.get(idy); writer.write(quoteDelimiters(String.valueOf(item), SPECIALS)); } writer.write(LINE_SEP); } } /** * Method saves aggregate statistics (with header names) as CSV from a table * model. Same as {@link #saveCSVStats(List, FileWriter, String[])} except * that there is no need to create a List containing the data. * * @param model * table model containing the data * @param writer * output file * @throws IOException */ public static void saveCSVStats(DefaultTableModel model, FileWriter writer) throws IOException { saveCSVStats(model, writer, true); } /** * Method saves aggregate statistics as CSV from a table model. Same as * {@link #saveCSVStats(List, FileWriter, String[])} except that there is * no need to create a List containing the data. * * @param model * table model containing the data * @param writer * output file * @param saveHeaders * whether or not to save headers * @throws IOException */ public static void saveCSVStats(DefaultTableModel model, FileWriter writer, boolean saveHeaders) throws IOException { final char DELIM = ','; final char SPECIALS[] = new char[] { DELIM, QUOTING_CHAR }; final int columns = model.getColumnCount(); final int rows = model.getRowCount(); if (saveHeaders) { for (int i = 0; i < columns; i++) { if (i > 0) { writer.write(DELIM); } writer.write(quoteDelimiters(model.getColumnName(i), SPECIALS)); } writer.write(LINE_SEP); } for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { if (column > 0) { writer.write(DELIM); } Object item = model.getValueAt(row, column); writer.write(quoteDelimiters(String.valueOf(item), SPECIALS)); } writer.write(LINE_SEP); } } /** * Convert a result into a string, where the fields of the result are * separated by the default delimiter. * * @param event * the sample event to be converted * @return the separated value representation of the result */ public static String resultToDelimitedString(SampleEvent event) { return resultToDelimitedString(event, event.getResult().getSaveConfig() .getDelimiter()); } /** * Convert a result into a string, where the fields of the result are * separated by a specified String. * * @param event * the sample event to be converted * @param delimiter * the separation string * @return the separated value representation of the result */ public static String resultToDelimitedString(SampleEvent event, final String delimiter) { /* * Class to handle generating the delimited string. - adds the delimiter * if not the first call - quotes any strings that require it */ final class StringQuoter { final StringBuilder sb = new StringBuilder(); private final char[] specials; private boolean addDelim; public StringQuoter(char delim) { specials = new char[] { delim, QUOTING_CHAR, CharUtils.CR, CharUtils.LF }; addDelim = false; // Don't add delimiter first time round } private void addDelim() { if (addDelim) { sb.append(specials[0]); } else { addDelim = true; } } // These methods handle parameters that could contain delimiters or // quotes: public void append(String s) { addDelim(); // if (s == null) return; sb.append(quoteDelimiters(s, specials)); } public void append(Object obj) { append(String.valueOf(obj)); } // These methods handle parameters that cannot contain delimiters or // quotes public void append(int i) { addDelim(); sb.append(i); } public void append(long l) { addDelim(); sb.append(l); } public void append(boolean b) { addDelim(); sb.append(b); } @Override public String toString() { return sb.toString(); } } StringQuoter text = new StringQuoter(delimiter.charAt(0)); SampleResult sample = event.getResult(); SampleSaveConfiguration saveConfig = sample.getSaveConfig(); if (saveConfig.saveTimestamp()) { if (saveConfig.printMilliseconds()) { text.append(sample.getTimeStamp()); } else if (saveConfig.formatter() != null) { String stamp = saveConfig.formatter().format( new Date(sample.getTimeStamp())); text.append(stamp); } } if (saveConfig.saveTime()) { text.append(sample.getTime()); } if (saveConfig.saveLabel()) { text.append(sample.getSampleLabel()); } if (saveConfig.saveCode()) { text.append(sample.getResponseCode()); } if (saveConfig.saveMessage()) { text.append(sample.getResponseMessage()); } if (saveConfig.saveThreadName()) { text.append(sample.getThreadName()); } if (saveConfig.saveDataType()) { text.append(sample.getDataType()); } if (saveConfig.saveSuccess()) { text.append(sample.isSuccessful()); } if (saveConfig.saveAssertionResultsFailureMessage()) { String message = null; AssertionResult[] results = sample.getAssertionResults(); if (results != null) { // Find the first non-null message for (int i = 0; i < results.length; i++) { message = results[i].getFailureMessage(); if (message != null) { break; } } } if (message != null) { text.append(message); } else { text.append(""); // Need to append something so delimiter is // added } } if (saveConfig.saveBytes()) { text.append(sample.getBytes()); } if (saveConfig.saveThreadCounts()) { text.append(sample.getGroupThreads()); text.append(sample.getAllThreads()); } if (saveConfig.saveUrl()) { text.append(sample.getURL()); } if (saveConfig.saveFileName()) { text.append(sample.getResultFileName()); } if (saveConfig.saveLatency()) { text.append(sample.getLatency()); } if (saveConfig.saveEncoding()) { text.append(sample.getDataEncodingWithDefault()); } if (saveConfig.saveSampleCount()) { // Need both sample and error count to be any use text.append(sample.getSampleCount()); text.append(sample.getErrorCount()); } if (saveConfig.saveHostname()) { text.append(event.getHostname()); } if (saveConfig.saveIdleTime()) { text.append(event.getResult().getIdleTime()); } for (int i = 0; i < SampleEvent.getVarCount(); i++) { text.append(event.getVarValue(i)); } return text.toString(); } // =================================== CSV quote/unquote handling // ============================== /* * Private versions of what might eventually be part of Commons-CSV or * Commons-Lang/Io... */ /* * <p> Returns a <code>String</code> value for a character-delimited column * value enclosed in the quote character, if required. </p> * * <p> If the value contains a special character, then the String value is * returned enclosed in the quote character. </p> * * <p> Any quote characters in the value are doubled up. </p> * * <p> If the value does not contain any special characters, then the String * value is returned unchanged. </p> * * <p> N.B. The list of special characters includes the quote character. * </p> * * @param input the input column String, may be null (without enclosing * delimiters) * * @param specialChars special characters; second one must be the quote * character * * @return the input String, enclosed in quote characters if the value * contains a special character, <code>null</code> for null string input */ private static String quoteDelimiters(String input, char[] specialChars) { if (StringUtils.containsNone(input, specialChars)) { return input; } StringBuilder buffer = new StringBuilder(input.length() + 10); final char quote = specialChars[1]; buffer.append(quote); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c == quote) { buffer.append(quote); // double the quote char } buffer.append(c); } buffer.append(quote); return buffer.toString(); } // State of the parser private static final int INITIAL = 0, PLAIN = 1, QUOTED = 2, EMBEDDEDQUOTE = 3; public static final char QUOTING_CHAR = '"'; /** * Reads from file and splits input into strings according to the delimiter, * taking note of quoted strings. * <p> * Handles DOS (CRLF), Unix (LF), and Mac (CR) line-endings equally. * <p> * N.B. a blank line is returned as a zero length array, whereas "" is * returned as an empty string. This is inconsistent. * * @param infile * input file - must support mark(1) * @param delim * delimiter (e.g. comma) * @return array of strings * @throws IOException * also for unexpected quote characters */ public static String[] csvReadFile(BufferedReader infile, char delim) throws IOException { int ch; int state = INITIAL; List<String> list = new ArrayList<String>(); CharArrayWriter baos = new CharArrayWriter(200); boolean push = false; while (-1 != (ch = infile.read())) { push = false; switch (state) { case INITIAL: if (ch == QUOTING_CHAR) { state = QUOTED; } else if (isDelimOrEOL(delim, ch)) { push = true; } else { baos.write(ch); state = PLAIN; } break; case PLAIN: if (ch == QUOTING_CHAR) { baos.write(ch); throw new IOException( "Cannot have quote-char in plain field:[" + baos.toString() + "]"); } else if (isDelimOrEOL(delim, ch)) { push = true; state = INITIAL; } else { baos.write(ch); } break; case QUOTED: if (ch == QUOTING_CHAR) { state = EMBEDDEDQUOTE; } else { baos.write(ch); } break; case EMBEDDEDQUOTE: if (ch == QUOTING_CHAR) { baos.write(QUOTING_CHAR); // doubled quote => quote state = QUOTED; } else if (isDelimOrEOL(delim, ch)) { push = true; state = INITIAL; } else { baos.write(QUOTING_CHAR); throw new IOException( "Cannot have single quote-char in quoted field:[" + baos.toString() + "]"); } break; } // switch(state) if (push) { if (ch == '\r') {// Remove following \n if present infile.mark(1); if (infile.read() != '\n') { infile.reset(); // did not find \n, put the character // back } } String s = baos.toString(); list.add(s); baos.reset(); } if ((ch == '\n' || ch == '\r') && state != QUOTED) { break; } } // while not EOF if (ch == -1) {// EOF (or end of string) so collect any remaining data if (state == QUOTED) { throw new IOException(state + " Missing trailing quote-char in quoted field:[\"" + baos.toString() + "]"); } // Do we have some data, or a trailing empty field? if (baos.size() > 0 // we have some data || push // we've started a field || state == EMBEDDEDQUOTE // Just seen "" ) { list.add(baos.toString()); } } return list.toArray(new String[list.size()]); } private static boolean isDelimOrEOL(char delim, int ch) { return ch == delim || ch == '\n' || ch == '\r'; } /** * Reads from String and splits into strings according to the delimiter, * taking note of quoted strings. * * Handles DOS (CRLF), Unix (LF), and Mac (CR) line-endings equally. * * @param line * input line * @param delim * delimiter (e.g. comma) * @return array of strings * @throws IOException * also for unexpected quote characters */ public static String[] csvSplitString(String line, char delim) throws IOException { return csvReadFile(new BufferedReader(new StringReader(line)), delim); } }
Javadoc correction git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1384550 13f79535-47bb-0310-9956-ffa450edef68
src/core/org/apache/jmeter/save/CSVSaveService.java
Javadoc correction
Java
apache-2.0
bacf4520c7ba45e142e07a37efae7724cb60287a
0
OHDSI/WebAPI,OHDSI/WebAPI,OHDSI/WebAPI
package org.ohdsi.webapi.versioning.repository; import org.ohdsi.webapi.versioning.domain.Version; import org.ohdsi.webapi.versioning.domain.VersionBase; import org.ohdsi.webapi.versioning.domain.VersionPK; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.NoRepositoryBean; import java.util.List; @NoRepositoryBean public interface VersionRepository<T extends Version> extends JpaRepository<T, VersionPK> { @Query("SELECT max(v.pk.version) from #{#entityName} v WHERE v.pk.assetId = ?1") Integer getLatestVersion(long assetId); @Query("SELECT new org.ohdsi.webapi.versioning.domain.VersionBase(v.pk.assetId, v.comment, " + "v.pk.version, uc, v.createdDate, v.archived) " + "FROM #{#entityName} v " + "LEFT JOIN UserEntity uc " + "ON uc = v.createdBy " + "WHERE v.pk.assetId = ?1") List<VersionBase> findAllVersions(long assetId); @Query("SELECT v from #{#entityName} v WHERE v.pk.assetId = ?1") List<T> findAll(int assetId); }
src/main/java/org/ohdsi/webapi/versioning/repository/VersionRepository.java
package org.ohdsi.webapi.versioning.repository; import org.ohdsi.webapi.versioning.domain.Version; import org.ohdsi.webapi.versioning.domain.VersionBase; import org.ohdsi.webapi.versioning.domain.VersionPK; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.NoRepositoryBean; import java.util.List; @NoRepositoryBean public interface VersionRepository<T extends Version> extends JpaRepository<T, VersionPK> { @Query("SELECT max(v.pk.version) from #{#entityName} v WHERE v.pk.assetId = ?1") Integer getLatestVersion(long assetId); @Query("SELECT new org.ohdsi.webapi.versioning.domain.VersionBase(v.pk.assetId, v.comment, " + "v.pk.version, uc, v.createdDate, v.archived) " + "FROM #{#entityName} v, UserEntity uc " + "WHERE v.pk.assetId = ?1 AND uc = v.createdBy") List<VersionBase> findAllVersions(long assetId); @Query("SELECT v from #{#entityName} v WHERE v.pk.assetId = ?1") List<T> findAll(int assetId); }
fixed empty version history in case when author of asset was anonymous (#1930) Co-authored-by: Sergey Suvorov <[email protected]>
src/main/java/org/ohdsi/webapi/versioning/repository/VersionRepository.java
fixed empty version history in case when author of asset was anonymous (#1930)
Java
apache-2.0
328b6cb52df0dc38e6aea9372f53c8926a7189b0
0
basho/riak-java-client,basho/riak-java-client
/* * Copyright 2014 Basho Technologies 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.basho.riak.client.api.commands.itest; import com.basho.riak.client.api.cap.ConflictResolver; import com.basho.riak.client.api.cap.ConflictResolverFactory; import com.basho.riak.client.api.cap.UnresolvedConflictException; import com.basho.riak.client.core.operations.itest.ITestAutoCleanupBase; import com.basho.riak.client.api.commands.kv.FetchValue.Option; import com.basho.riak.client.api.commands.kv.FetchValue; import com.basho.riak.client.api.RiakClient; import com.basho.riak.client.api.annotations.RiakVClock; import com.basho.riak.client.api.cap.DefaultResolver; import com.basho.riak.client.api.cap.VClock; import com.basho.riak.client.core.operations.StoreBucketPropsOperation; import com.basho.riak.client.api.commands.kv.StoreValue; import com.basho.riak.client.api.convert.JSONConverter; import com.basho.riak.client.core.query.Location; import com.basho.riak.client.core.query.Namespace; import com.basho.riak.client.core.query.RiakObject; import com.basho.riak.client.core.query.indexes.LongIntIndex; import com.basho.riak.client.core.query.indexes.StringBinIndex; import com.basho.riak.client.core.util.BinaryValue; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import static org.junit.Assert.*; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.Assume; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * * @author Brian Roach <roach at basho dot com> */ public class ITestFetchValue extends ITestAutoCleanupBase { private RiakClient client = new RiakClient(cluster); @Test public void simpleTestDefaultType() { simpleTest(Namespace.DEFAULT_BUCKET_TYPE); } @Test public void simpleTestTestType() { Assume.assumeTrue(testBucketType); simpleTest(bucketType.toString()); } private void simpleTest(String bucketType) { try { Namespace ns = new Namespace(bucketType, bucketName.toString()); Location loc = new Location(ns, "test_fetch_key1"); Pojo pojo = new Pojo(); pojo.value = "test value"; StoreValue sv = new StoreValue.Builder(pojo).withLocation(loc).build(); StoreValue.Response resp = client.execute(sv); FetchValue fv = new FetchValue.Builder(loc).build(); FetchValue.Response fResp = client.execute(fv); assertEquals(pojo.value, fResp.getValue(Pojo.class).value); RiakObject ro = fResp.getValue(RiakObject.class); assertNotNull(ro.getValue()); assertEquals("{\"value\":\"test value\"}", ro.getValue().toString()); } catch (ExecutionException ex) { System.out.println(ex.getCause().getCause()); } catch (InterruptedException ex) { Logger.getLogger(ITestFetchValue.class.getName()).log(Level.SEVERE, null, ex); } } @Test public void notFoundDefaultType() throws ExecutionException, InterruptedException { notFound(Namespace.DEFAULT_BUCKET_TYPE); } @Test public void notFoundTestType() throws ExecutionException, InterruptedException { Assume.assumeTrue(testBucketType); notFound(bucketType.toString()); } private void notFound(String bucketType) throws ExecutionException, InterruptedException { Namespace ns = new Namespace(bucketType, bucketName.toString()); Location loc = new Location(ns, "test_fetch_key2"); FetchValue fv = new FetchValue.Builder(loc).build(); FetchValue.Response fResp = client.execute(fv); assertFalse(fResp.hasValues()); assertTrue(fResp.isNotFound()); assertNull(fResp.getValue(Pojo.class)); RiakObject ro = fResp.getValue(RiakObject.class); } // Apparently this isn't happening anymore. or it only happens with leveldb // Leaving it here to investigate @Ignore @Test public void ReproRiakTombstoneBehavior() throws ExecutionException, InterruptedException { // We're back to allow_mult=false as default Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, bucketName.toString()); StoreBucketPropsOperation op = new StoreBucketPropsOperation.Builder(ns) .withAllowMulti(true) .build(); cluster.execute(op); op.get(); Location loc = new Location(ns, "test_fetch_key3"); Pojo pojo = new Pojo(); pojo.value = "test value"; StoreValue sv = new StoreValue.Builder(pojo).withLocation(loc).build(); client.execute(sv); resetAndEmptyBucket(bucketName); client.execute(sv); FetchValue fv = new FetchValue.Builder(loc) .withOption(Option.DELETED_VCLOCK, false) .build(); FetchValue.Response fResp = client.execute(fv); assertEquals(2, fResp.getValues(RiakObject.class).size()); } @Test public void resolveSiblingsDefaultType() throws ExecutionException, InterruptedException { ConflictResolver<Pojo> resolver = new MyResolver(); Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, bucketName.toString()); setAllowMultToTrue(ns); resolveSiblings(ns, resolver); resetAndEmptyBucket(ns); } private void setAllowMultToTrue(Namespace namespace) throws ExecutionException, InterruptedException { StoreBucketPropsOperation op = new StoreBucketPropsOperation.Builder(namespace) .withAllowMulti(true) .withLastWriteWins(false) .build(); cluster.execute(op); op.get(); } @Test public void resolveSiblingsTestType() throws ExecutionException, InterruptedException { Assume.assumeTrue(testBucketType); ConflictResolver<Pojo> resolver = new MyResolver(); Namespace ns = new Namespace(bucketType.toString(), bucketName.toString()); resolveSiblings(ns, resolver); } private void resolveSiblings(Namespace ns, ConflictResolver<Pojo> resolver) throws ExecutionException, InterruptedException { Location loc = new Location(ns, "test_fetch_key4"); Pojo pojo = storeSiblings(loc); TypeReference<Pojo> pojoTypeRef = new TypeReference<Pojo>() {}; ConflictResolverFactory.getInstance() .registerConflictResolver(Pojo.class, resolver); ConflictResolverFactory.getInstance() .registerConflictResolver(pojoTypeRef, resolver); FetchValue fv = new FetchValue.Builder(loc).build(); FetchValue.Response fResp = client.execute(fv); assertEquals(2, fResp.getNumberOfValues()); assertNotNull(fResp.getVectorClock()); assertEquals(pojo.value, fResp.getValue(Pojo.class).value); JSONConverter<Pojo> converter = new JSONConverter<Pojo>(Pojo.class); assertEquals(pojo.value, fResp.getValues(converter).get(0).value); assertEquals(pojo.value, fResp.getValue(converter, resolver).value); assertEquals(pojo.value, fResp.getValue(pojoTypeRef).value); assertEquals(loc, fResp.getLocation()); } private Pojo storeSiblings(Location loc) throws ExecutionException, InterruptedException { Pojo pojo = new Pojo(); pojo.value = "test value"; StoreValue sv = new StoreValue.Builder(pojo).withLocation(loc).build(); client.execute(sv); pojo.value = "Pick me!"; sv = new StoreValue.Builder(pojo).withLocation(loc).build(); client.execute(sv); return pojo; } @Test public void fetchAnnotatedPojoDefaultType() throws ExecutionException, InterruptedException { fetchAnnotatedPojo(Namespace.DEFAULT_BUCKET_TYPE); } @Test public void fetchAnnotatedPojoTestType() throws ExecutionException, InterruptedException { Assume.assumeTrue(testBucketType); fetchAnnotatedPojo(bucketType.toString()); } private void fetchAnnotatedPojo(String bucketType) throws ExecutionException, InterruptedException { Namespace ns = new Namespace(bucketType, bucketName.toString()); Location loc = new Location(ns, "test_fetch_key5"); String jsonValue = "{\"value\":\"my value\"}"; RiakObject ro = new RiakObject() .setValue(BinaryValue.create(jsonValue)) .setContentType("application/json"); StoreValue sv = new StoreValue.Builder(ro).withLocation(loc).build(); client.execute(sv); FetchValue fv = new FetchValue.Builder(loc).build(); FetchValue.Response resp = client.execute(fv); RiakAnnotatedPojo rap = resp.getValue(RiakAnnotatedPojo.class); assertNotNull(rap.bucketName); assertEquals(ns.getBucketNameAsString(), rap.bucketName); assertNotNull(rap.key); assertEquals(loc.getKeyAsString(), rap.key); assertNotNull(rap.bucketType); assertEquals(ns.getBucketTypeAsString(), rap.bucketType); assertNotNull(rap.contentType); assertEquals(ro.getContentType(), rap.contentType); assertNotNull(rap.vclock); assertNotNull(rap.vtag); assertNotNull(rap.lastModified); assertNotNull(rap.value); assertFalse(rap.deleted); assertNotNull(rap.value); assertEquals("my value", rap.value); } @Test public void fetchAnnotatedPojoWIthIndexes() throws ExecutionException, InterruptedException { Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, bucketName.toString()); Location loc = new Location(ns,"test_fetch_key6"); String jsonValue = "{\"value\":\"my value\"}"; RiakObject ro = new RiakObject() .setValue(BinaryValue.create(jsonValue)) .setContentType("application/json"); ro.getIndexes().getIndex(StringBinIndex.named("email")).add("[email protected]"); ro.getIndexes().getIndex(LongIntIndex.named("user_id")).add(1L); StoreValue sv = new StoreValue.Builder(ro).withLocation(loc).build(); client.execute(sv); FetchValue fv = new FetchValue.Builder(loc).build(); FetchValue.Response resp = client.execute(fv); RiakAnnotatedPojo rap = resp.getValue(RiakAnnotatedPojo.class); assertNotNull(rap.emailIndx); assertTrue(rap.emailIndx.contains("[email protected]")); assertEquals(rap.userId.longValue(), 1L); } public static class Pojo { @JsonProperty String value; @RiakVClock VClock vclock; } public static class MyResolver implements ConflictResolver<Pojo> { @Override public Pojo resolve(List<Pojo> objectList) throws UnresolvedConflictException { if (objectList.size() > 0) { for (Pojo p : objectList) { if (p.value.equals("Pick me!")) { return p; } } return objectList.get(0); } return null; } } }
src/test/java/com/basho/riak/client/api/commands/itest/ITestFetchValue.java
/* * Copyright 2014 Basho Technologies 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.basho.riak.client.api.commands.itest; import com.basho.riak.client.api.cap.ConflictResolver; import com.basho.riak.client.api.cap.ConflictResolverFactory; import com.basho.riak.client.api.cap.UnresolvedConflictException; import com.basho.riak.client.core.operations.itest.ITestAutoCleanupBase; import com.basho.riak.client.api.commands.kv.FetchValue.Option; import com.basho.riak.client.api.commands.kv.FetchValue; import com.basho.riak.client.api.RiakClient; import com.basho.riak.client.api.annotations.RiakVClock; import com.basho.riak.client.api.cap.DefaultResolver; import com.basho.riak.client.api.cap.VClock; import com.basho.riak.client.core.operations.StoreBucketPropsOperation; import com.basho.riak.client.api.commands.kv.StoreValue; import com.basho.riak.client.api.convert.JSONConverter; import com.basho.riak.client.core.query.Location; import com.basho.riak.client.core.query.Namespace; import com.basho.riak.client.core.query.RiakObject; import com.basho.riak.client.core.query.indexes.LongIntIndex; import com.basho.riak.client.core.query.indexes.StringBinIndex; import com.basho.riak.client.core.util.BinaryValue; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import static org.junit.Assert.*; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.Assume; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * * @author Brian Roach <roach at basho dot com> */ public class ITestFetchValue extends ITestAutoCleanupBase { private RiakClient client = new RiakClient(cluster); @Test public void simpleTestDefaultType() { simpleTest(Namespace.DEFAULT_BUCKET_TYPE); } @Test public void simpleTestTestType() { Assume.assumeTrue(testBucketType); simpleTest(bucketType.toString()); } private void simpleTest(String bucketType) { try { Namespace ns = new Namespace(bucketType, bucketName.toString()); Location loc = new Location(ns, "test_fetch_key1"); Pojo pojo = new Pojo(); pojo.value = "test value"; StoreValue sv = new StoreValue.Builder(pojo).withLocation(loc).build(); StoreValue.Response resp = client.execute(sv); FetchValue fv = new FetchValue.Builder(loc).build(); FetchValue.Response fResp = client.execute(fv); assertEquals(pojo.value, fResp.getValue(Pojo.class).value); RiakObject ro = fResp.getValue(RiakObject.class); assertNotNull(ro.getValue()); assertEquals("{\"value\":\"test value\"}", ro.getValue().toString()); } catch (ExecutionException ex) { System.out.println(ex.getCause().getCause()); } catch (InterruptedException ex) { Logger.getLogger(ITestFetchValue.class.getName()).log(Level.SEVERE, null, ex); } } @Test public void notFoundDefaultType() throws ExecutionException, InterruptedException { notFound(Namespace.DEFAULT_BUCKET_TYPE); } @Test public void notFoundTestType() throws ExecutionException, InterruptedException { Assume.assumeTrue(testBucketType); notFound(bucketType.toString()); } private void notFound(String bucketType) throws ExecutionException, InterruptedException { Namespace ns = new Namespace(bucketType, bucketName.toString()); Location loc = new Location(ns, "test_fetch_key2"); FetchValue fv = new FetchValue.Builder(loc).build(); FetchValue.Response fResp = client.execute(fv); assertFalse(fResp.hasValues()); assertTrue(fResp.isNotFound()); assertNull(fResp.getValue(Pojo.class)); RiakObject ro = fResp.getValue(RiakObject.class); } // Apparently this isn't happening anymore. or it only happens with leveldb // Leaving it here to investigate @Ignore @Test public void ReproRiakTombstoneBehavior() throws ExecutionException, InterruptedException { // We're back to allow_mult=false as default Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, bucketName.toString()); StoreBucketPropsOperation op = new StoreBucketPropsOperation.Builder(ns) .withAllowMulti(true) .build(); cluster.execute(op); op.get(); Location loc = new Location(ns, "test_fetch_key3"); Pojo pojo = new Pojo(); pojo.value = "test value"; StoreValue sv = new StoreValue.Builder(pojo).withLocation(loc).build(); client.execute(sv); resetAndEmptyBucket(bucketName); client.execute(sv); FetchValue fv = new FetchValue.Builder(loc) .withOption(Option.DELETED_VCLOCK, false) .build(); FetchValue.Response fResp = client.execute(fv); assertEquals(2, fResp.getValues(RiakObject.class).size()); } @Test public void resolveSiblingsDefaultType() throws ExecutionException, InterruptedException { ConflictResolver<Pojo> resolver = new MyResolver(); Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, bucketName.toString()); setAllowMultToTrue(ns); resolveSiblings(ns, resolver); resetAndEmptyBucket(ns); } private void setAllowMultToTrue(Namespace namespace) throws ExecutionException, InterruptedException { StoreBucketPropsOperation op = new StoreBucketPropsOperation.Builder(namespace) .withAllowMulti(true) .withLastWriteWins(false) .build(); cluster.execute(op); op.get(); } @Test public void resolveSiblingsTestType() throws ExecutionException, InterruptedException { Assume.assumeTrue(testBucketType); ConflictResolver<Pojo> resolver = new MyResolver(); Namespace ns = new Namespace(bucketType.toString(), bucketName.toString()); resolveSiblings(ns, resolver); } private void resolveSiblings(Namespace ns, ConflictResolver<Pojo> resolver) throws ExecutionException, InterruptedException { Location loc = new Location(ns, "test_fetch_key4"); Pojo pojo = storeSiblings(loc); TypeReference<Pojo> pojoTypeRef = new TypeReference<Pojo>() {}; ConflictResolverFactory.getInstance() .registerConflictResolver(Pojo.class, resolver); ConflictResolverFactory.getInstance() .registerConflictResolver(pojoTypeRef, resolver); FetchValue fv = new FetchValue.Builder(loc).build(); FetchValue.Response fResp = client.execute(fv); assertEquals(2, fResp.getNumberOfValues()); assertNotNull(fResp.getVectorClock()); assertEquals(pojo.value, fResp.getValue(Pojo.class).value); JSONConverter<Pojo> converter = new JSONConverter<Pojo>(Pojo.class); assertEquals(pojo.value, fResp.getValues(converter).get(0).value); assertEquals(pojo.value, fResp.getValue(converter, resolver).value); assertEquals(pojo.value, fResp.getValue(pojoTypeRef).value); } private Pojo storeSiblings(Location loc) throws ExecutionException, InterruptedException { Pojo pojo = new Pojo(); pojo.value = "test value"; StoreValue sv = new StoreValue.Builder(pojo).withLocation(loc).build(); client.execute(sv); pojo.value = "Pick me!"; sv = new StoreValue.Builder(pojo).withLocation(loc).build(); client.execute(sv); return pojo; } @Test public void fetchAnnotatedPojoDefaultType() throws ExecutionException, InterruptedException { fetchAnnotatedPojo(Namespace.DEFAULT_BUCKET_TYPE); } @Test public void fetchAnnotatedPojoTestType() throws ExecutionException, InterruptedException { Assume.assumeTrue(testBucketType); fetchAnnotatedPojo(bucketType.toString()); } private void fetchAnnotatedPojo(String bucketType) throws ExecutionException, InterruptedException { Namespace ns = new Namespace(bucketType, bucketName.toString()); Location loc = new Location(ns, "test_fetch_key5"); String jsonValue = "{\"value\":\"my value\"}"; RiakObject ro = new RiakObject() .setValue(BinaryValue.create(jsonValue)) .setContentType("application/json"); StoreValue sv = new StoreValue.Builder(ro).withLocation(loc).build(); client.execute(sv); FetchValue fv = new FetchValue.Builder(loc).build(); FetchValue.Response resp = client.execute(fv); RiakAnnotatedPojo rap = resp.getValue(RiakAnnotatedPojo.class); assertNotNull(rap.bucketName); assertEquals(ns.getBucketNameAsString(), rap.bucketName); assertNotNull(rap.key); assertEquals(loc.getKeyAsString(), rap.key); assertNotNull(rap.bucketType); assertEquals(ns.getBucketTypeAsString(), rap.bucketType); assertNotNull(rap.contentType); assertEquals(ro.getContentType(), rap.contentType); assertNotNull(rap.vclock); assertNotNull(rap.vtag); assertNotNull(rap.lastModified); assertNotNull(rap.value); assertFalse(rap.deleted); assertNotNull(rap.value); assertEquals("my value", rap.value); } @Test public void fetchAnnotatedPojoWIthIndexes() throws ExecutionException, InterruptedException { Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, bucketName.toString()); Location loc = new Location(ns,"test_fetch_key6"); String jsonValue = "{\"value\":\"my value\"}"; RiakObject ro = new RiakObject() .setValue(BinaryValue.create(jsonValue)) .setContentType("application/json"); ro.getIndexes().getIndex(StringBinIndex.named("email")).add("[email protected]"); ro.getIndexes().getIndex(LongIntIndex.named("user_id")).add(1L); StoreValue sv = new StoreValue.Builder(ro).withLocation(loc).build(); client.execute(sv); FetchValue fv = new FetchValue.Builder(loc).build(); FetchValue.Response resp = client.execute(fv); RiakAnnotatedPojo rap = resp.getValue(RiakAnnotatedPojo.class); assertNotNull(rap.emailIndx); assertTrue(rap.emailIndx.contains("[email protected]")); assertEquals(rap.userId.longValue(), 1L); } public static class Pojo { @JsonProperty String value; @RiakVClock VClock vclock; } public static class MyResolver implements ConflictResolver<Pojo> { @Override public Pojo resolve(List<Pojo> objectList) throws UnresolvedConflictException { if (objectList.size() > 0) { for (Pojo p : objectList) { if (p.value.equals("Pick me!")) { return p; } } return objectList.get(0); } return null; } } }
Add test for KVResponseBase:getLocation()
src/test/java/com/basho/riak/client/api/commands/itest/ITestFetchValue.java
Add test for KVResponseBase:getLocation()
Java
apache-2.0
38f0e7bb3ea75f3504315b264e6fda0ebd661e97
0
b2ihealthcare/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl
/* * Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.server.console; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.collect.Lists.newArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.eclipse.osgi.framework.console.CommandInterpreter; import org.eclipse.osgi.framework.console.CommandProvider; import org.slf4j.LoggerFactory; import com.b2international.commons.StringUtils; import com.b2international.index.revision.Purge; import com.b2international.snowowl.core.ApplicationContext; import com.b2international.snowowl.core.Repositories; import com.b2international.snowowl.core.RepositoryInfo; import com.b2international.snowowl.core.branch.Branch; import com.b2international.snowowl.core.date.DateFormats; import com.b2international.snowowl.core.date.Dates; import com.b2international.snowowl.core.exceptions.NotFoundException; import com.b2international.snowowl.datastore.cdo.ICDORepositoryManager; import com.b2international.snowowl.datastore.request.RepositoryRequests; import com.b2international.snowowl.datastore.request.repository.RepositorySearchRequestBuilder; import com.b2international.snowowl.datastore.server.ServerDbUtils; import com.b2international.snowowl.datastore.server.reindex.OptimizeRequest; import com.b2international.snowowl.datastore.server.reindex.PurgeRequest; import com.b2international.snowowl.datastore.server.reindex.ReindexRequest; import com.b2international.snowowl.datastore.server.reindex.ReindexRequestBuilder; import com.b2international.snowowl.datastore.server.reindex.ReindexResult; import com.b2international.snowowl.eventbus.IEventBus; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; /** * OSGI command contribution with Snow Owl maintenance type commands. */ public class MaintenanceCommandProvider implements CommandProvider { private static final String DEFAULT_BRANCH_PREFIX = "|--"; private static final String DEFAULT_INDENT = " "; private static final String LISTBRANCHES_COMMAND = "listbranches"; private static final String DBCREATEINDEX_COMMAND = "dbcreateindex"; private static final String REPOSITORIES_COMMAND = "repositories"; private static final String VERSION_COMMAND = "--version"; @Override public String getHelp() { StringBuffer buffer = new StringBuffer(); buffer.append("---Snow Owl commands---\n"); buffer.append("\tsnowowl --version - returns the current version\n"); buffer.append("\tsnowowl dbcreateindex [nsUri] - creates the CDO_CREATED index on the proper DB tables for all classes contained by a package identified by its unique namespace URI.\n"); buffer.append("\tsnowowl listrepositories - prints all the repositories in the system. \n"); buffer.append("\tsnowowl listbranches [repository] [branchPath] - prints all the child branches of the specified branch path in the system for a repository. Branch path is MAIN by default and has to be full path (e.g. MAIN/PROJECT/TASK)\n"); buffer.append("\tsnowowl reindex [repositoryId] [failedCommitTimestamp] - reindexes the content for the given repository ID from the given failed commit timestamp (optional, default timestamp is 1 which means no failed commit).\n"); buffer.append("\tsnowowl optimize [repositoryId] [maxSegments] - optimizes the underlying index for the repository to have the supplied maximum number of segments (default number is 1)\n"); buffer.append("\tsnowowl purge [repositoryId] [branchPath] [ALL|LATEST|HISTORY] - optimizes the underlying index by deleting unnecessary documents from the given branch using the given purge strategy (default strategy is LATEST)\n"); buffer.append("\tsnowowl repositories [repositoryId] - prints all currently available repositories and their health statuses"); return buffer.toString(); } /** * Reflective template method declaratively registered. Needs to start with * "_". * * @param interpreter * @throws InterruptedException */ public void _snowowl(CommandInterpreter interpreter) throws InterruptedException { String cmd = interpreter.nextArgument(); try { if (DBCREATEINDEX_COMMAND.equals(cmd)) { createDbIndex(interpreter); return; } if (LISTBRANCHES_COMMAND.equals(cmd)) { listBranches(interpreter); return; } if (REPOSITORIES_COMMAND.equals(cmd)) { repositories(interpreter); return; } if (VERSION_COMMAND.equals(cmd)) { String version = RepositoryRequests.prepareGetServerInfo().buildAsync().execute(getBus()).getSync().version(); interpreter.println(version); return; } if ("reindex".equals(cmd)) { reindex(interpreter); return; } if ("optimize".equals(cmd)) { optimize(interpreter); return; } if ("purge".equals(cmd)) { purge(interpreter); return; } interpreter.println(getHelp()); } catch (Exception ex) { LoggerFactory.getLogger("console").error("Failed to execute command", ex); if (Strings.isNullOrEmpty(ex.getMessage())) { interpreter.println("Something went wrong during the processing of your request."); } else { interpreter.println(ex.getMessage()); } } } private static final String COLUMN_FORMAT = "|%16s|%-16s|%-16s|"; private void repositories(CommandInterpreter interpreter) { final String repositoryId = interpreter.nextArgument(); RepositorySearchRequestBuilder req = RepositoryRequests.prepareSearch(); if (!Strings.isNullOrEmpty(repositoryId)) { req.one().filterById(repositoryId); } else { req.all(); } final Repositories repositories = req.buildAsync().execute(getBus()).getSync(); final int maxDiagLength = ImmutableList.copyOf(repositories) .stream() .map(RepositoryInfo::diagnosis) .map(diag -> Strings.isNullOrEmpty(diag) ? "-" : diag) .map(diag -> diag.length()) .max(Ints::compare) .orElse(16); final int maxLength = maxDiagLength + 36; printSeparator(interpreter, maxLength); printHeader(interpreter, "id", "health", Strings.padEnd("diagnosis", maxDiagLength, ' ')); printSeparator(interpreter, maxLength); repositories.forEach(repository -> { printLine(interpreter, repository, RepositoryInfo::id, RepositoryInfo::health, RepositoryInfo::diagnosis); printSeparator(interpreter, maxLength); }); } private void printHeader(final CommandInterpreter interpreter, Object...columns) { interpreter.println(String.format(COLUMN_FORMAT, columns)); } private void printSeparator(final CommandInterpreter interpreter, int length) { interpreter.println(Strings.repeat("-", length)); } private <T> void printLine(final CommandInterpreter interpreter, T item, Function<T, Object>...values) { interpreter.println(String.format(COLUMN_FORMAT, newArrayList(values).stream().map(func -> func.apply(item)).toArray())); } private List<String> resolveArguments(CommandInterpreter interpreter) { List<String> results = Lists.newArrayList(); String argument = interpreter.nextArgument(); while(!isNullOrEmpty(argument)) { results.add(argument); argument = interpreter.nextArgument(); } return results; } public synchronized void createDbIndex(CommandInterpreter interpreter) { String nsUri = interpreter.nextArgument(); if (!Strings.isNullOrEmpty(nsUri)) { ServerDbUtils.createCdoCreatedIndexOnTables(nsUri); } else { interpreter.println("Namespace URI should be specified."); } } private void purge(CommandInterpreter interpreter) { final String repositoryId = interpreter.nextArgument(); if (Strings.isNullOrEmpty(repositoryId)) { interpreter.println("RepositoryId parameter is required"); return; } final String branchPath = interpreter.nextArgument(); if (Strings.isNullOrEmpty(branchPath)) { interpreter.print("BranchPath parameter is required"); return; } final String purgeArg = interpreter.nextArgument(); final Purge purge = Strings.isNullOrEmpty(purgeArg) ? Purge.LATEST : Purge.valueOf(purgeArg); if (purge == null) { interpreter.print("Invalid purge parameter. Select one of " + Joiner.on(",").join(Purge.values())); return; } PurgeRequest.builder() .setBranchPath(branchPath) .setPurge(purge) .build(repositoryId) .execute(getBus()) .getSync(); } private void reindex(CommandInterpreter interpreter) { final String repositoryId = interpreter.nextArgument(); if (Strings.isNullOrEmpty(repositoryId)) { interpreter.println("RepositoryId parameter is required"); return; } final ReindexRequestBuilder req = ReindexRequest.builder(); final String failedCommitTimestamp = interpreter.nextArgument(); if (!StringUtils.isEmpty(failedCommitTimestamp)) { req.setFailedCommitTimestamp(Long.parseLong(failedCommitTimestamp)); } final ReindexResult result = req .build(repositoryId) .execute(getBus()) .getSync(); interpreter.println(result.getMessage()); } private static IEventBus getBus() { return ApplicationContext.getServiceForClass(IEventBus.class); } private void optimize(CommandInterpreter interpreter) { final String repositoryId = interpreter.nextArgument(); if (Strings.isNullOrEmpty(repositoryId)) { interpreter.println("RepositoryId parameter is required."); return; } // default max segments is 1 int maxSegments = 1; final String maxSegmentsArg = interpreter.nextArgument(); if (!Strings.isNullOrEmpty(maxSegmentsArg)) { maxSegments = Integer.parseInt(maxSegmentsArg); } interpreter.println("Optimizing index to max. " + maxSegments + " number of segments..."); OptimizeRequest.builder() .setMaxSegments(maxSegments) .build(repositoryId) .execute(getBus()) .getSync(); interpreter.println("Index optimization completed."); } public synchronized void listBranches(CommandInterpreter interpreter) { String repositoryUUID = interpreter.nextArgument(); if (isValidRepositoryName(repositoryUUID, interpreter)) { String parentBranchPath = interpreter.nextArgument(); if (Strings.isNullOrEmpty(parentBranchPath)) { interpreter.println("Parent branch path was not specified, falling back to MAIN"); parentBranchPath = Branch.MAIN_PATH; } else if (!parentBranchPath.startsWith(Branch.MAIN_PATH)) { interpreter.println("Specify parent branch with full path. i.e. MAIN/PROJECT/TASK1"); return; } Branch parentBranch = null; try { parentBranch = RepositoryRequests.branching() .prepareGet(parentBranchPath) .build(repositoryUUID) .execute(getBus()) .getSync(1000, TimeUnit.MILLISECONDS); } catch (NotFoundException e) { interpreter.println(String.format("Unable to find %s", parentBranchPath)); return; } if (parentBranch != null) { interpreter.println(String.format("Branch hierarchy for %s in repository %s:", parentBranchPath, repositoryUUID)); print(parentBranch, getDepthOfBranch(parentBranch), interpreter); } } } private void print(final Branch branch, final int parentDepth, CommandInterpreter interpreter) { printBranch(branch, getDepthOfBranch(branch) - parentDepth, interpreter); List<? extends Branch> children = FluentIterable.from(branch.children()).filter(new Predicate<Branch>() { @Override public boolean apply(Branch input) { return input.parentPath().equals(branch.path()); } }).toSortedList(new Comparator<Branch>() { @Override public int compare(Branch o1, Branch o2) { return Longs.compare(o1.baseTimestamp(), o2.baseTimestamp()); } }); if (children.size() != 0) { for (Branch child : children) { print(child, parentDepth, interpreter); } } } private void printBranch(Branch branch, int depth, CommandInterpreter interpreter) { interpreter.println(String.format("%-30s %-12s B: %s H: %s", String.format("%s%s%s", getIndentationForBranch(depth), DEFAULT_BRANCH_PREFIX, branch.name()), String.format("[%s]", branch.state()), Dates.formatByGmt(branch.baseTimestamp(), DateFormats.LONG), Dates.formatByGmt(branch.headTimestamp(), DateFormats.LONG))); } private String getIndentationForBranch(int depth) { String indent = ""; for (int i = 0; i < depth; i++) { indent += DEFAULT_INDENT; } return indent; } private int getDepthOfBranch(Branch currentBranch) { return Iterables.size(Splitter.on(Branch.SEPARATOR).split(currentBranch.path())); } private boolean isValidRepositoryName(String repositoryName, CommandInterpreter interpreter) { Set<String> uuidKeySet = getRepositoryManager().uuidKeySet(); if (!uuidKeySet.contains(repositoryName)) { interpreter.println("Could not find repository called: " + repositoryName); interpreter.println("Available repository names are: " + uuidKeySet); return false; } return true; } private ICDORepositoryManager getRepositoryManager() { return ApplicationContext.getServiceForClass(ICDORepositoryManager.class); } }
core/com.b2international.snowowl.server.console/src/com/b2international/snowowl/server/console/MaintenanceCommandProvider.java
/* * Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.server.console; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.collect.Lists.newArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.eclipse.osgi.framework.console.CommandInterpreter; import org.eclipse.osgi.framework.console.CommandProvider; import org.slf4j.LoggerFactory; import com.b2international.commons.StringUtils; import com.b2international.index.revision.Purge; import com.b2international.snowowl.core.ApplicationContext; import com.b2international.snowowl.core.Repositories; import com.b2international.snowowl.core.RepositoryInfo; import com.b2international.snowowl.core.branch.Branch; import com.b2international.snowowl.core.date.DateFormats; import com.b2international.snowowl.core.date.Dates; import com.b2international.snowowl.core.exceptions.NotFoundException; import com.b2international.snowowl.datastore.cdo.ICDORepositoryManager; import com.b2international.snowowl.datastore.request.RepositoryRequests; import com.b2international.snowowl.datastore.request.repository.RepositorySearchRequestBuilder; import com.b2international.snowowl.datastore.server.ServerDbUtils; import com.b2international.snowowl.datastore.server.reindex.OptimizeRequest; import com.b2international.snowowl.datastore.server.reindex.PurgeRequest; import com.b2international.snowowl.datastore.server.reindex.ReindexRequest; import com.b2international.snowowl.datastore.server.reindex.ReindexRequestBuilder; import com.b2international.snowowl.datastore.server.reindex.ReindexResult; import com.b2international.snowowl.eventbus.IEventBus; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; /** * OSGI command contribution with Snow Owl maintenance type commands. */ public class MaintenanceCommandProvider implements CommandProvider { private static final String DEFAULT_BRANCH_PREFIX = "|--"; private static final String DEFAULT_INDENT = " "; private static final String LISTBRANCHES_COMMAND = "listbranches"; private static final String DBCREATEINDEX_COMMAND = "dbcreateindex"; private static final String REPOSITORIES_COMMAND = "repositories"; @Override public String getHelp() { StringBuffer buffer = new StringBuffer(); buffer.append("---Snow Owl commands---\n"); buffer.append("\tsnowowl dbcreateindex [nsUri] - creates the CDO_CREATED index on the proper DB tables for all classes contained by a package identified by its unique namespace URI.\n"); buffer.append("\tsnowowl listrepositories - prints all the repositories in the system. \n"); buffer.append("\tsnowowl listbranches [repository] [branchPath] - prints all the child branches of the specified branch path in the system for a repository. Branch path is MAIN by default and has to be full path (e.g. MAIN/PROJECT/TASK)\n"); buffer.append("\tsnowowl reindex [repositoryId] [failedCommitTimestamp] - reindexes the content for the given repository ID from the given failed commit timestamp (optional, default timestamp is 1 which means no failed commit).\n"); buffer.append("\tsnowowl optimize [repositoryId] [maxSegments] - optimizes the underlying index for the repository to have the supplied maximum number of segments (default number is 1)\n"); buffer.append("\tsnowowl purge [repositoryId] [branchPath] [ALL|LATEST|HISTORY] - optimizes the underlying index by deleting unnecessary documents from the given branch using the given purge strategy (default strategy is LATEST)\n"); buffer.append("\tsnowowl repositories [repositoryId] - prints all currently available repositories and their health statuses"); return buffer.toString(); } /** * Reflective template method declaratively registered. Needs to start with * "_". * * @param interpreter * @throws InterruptedException */ public void _snowowl(CommandInterpreter interpreter) throws InterruptedException { String cmd = interpreter.nextArgument(); try { if (DBCREATEINDEX_COMMAND.equals(cmd)) { createDbIndex(interpreter); return; } if (LISTBRANCHES_COMMAND.equals(cmd)) { listBranches(interpreter); return; } if (REPOSITORIES_COMMAND.equals(cmd)) { repositories(interpreter); return; } if ("reindex".equals(cmd)) { reindex(interpreter); return; } if ("optimize".equals(cmd)) { optimize(interpreter); return; } if ("purge".equals(cmd)) { purge(interpreter); return; } interpreter.println(getHelp()); } catch (Exception ex) { LoggerFactory.getLogger("console").error("Failed to execute command", ex); if (Strings.isNullOrEmpty(ex.getMessage())) { interpreter.println("Something went wrong during the processing of your request."); } else { interpreter.println(ex.getMessage()); } } } private static final String COLUMN_FORMAT = "|%16s|%-16s|%-16s|"; private void repositories(CommandInterpreter interpreter) { final String repositoryId = interpreter.nextArgument(); RepositorySearchRequestBuilder req = RepositoryRequests.prepareSearch(); if (!Strings.isNullOrEmpty(repositoryId)) { req.one().filterById(repositoryId); } else { req.all(); } final Repositories repositories = req.buildAsync().execute(getBus()).getSync(); final int maxDiagLength = ImmutableList.copyOf(repositories) .stream() .map(RepositoryInfo::diagnosis) .map(diag -> Strings.isNullOrEmpty(diag) ? "-" : diag) .map(diag -> diag.length()) .max(Ints::compare) .orElse(16); final int maxLength = maxDiagLength + 36; printSeparator(interpreter, maxLength); printHeader(interpreter, "id", "health", Strings.padEnd("diagnosis", maxDiagLength, ' ')); printSeparator(interpreter, maxLength); repositories.forEach(repository -> { printLine(interpreter, repository, RepositoryInfo::id, RepositoryInfo::health, RepositoryInfo::diagnosis); printSeparator(interpreter, maxLength); }); } private void printHeader(final CommandInterpreter interpreter, Object...columns) { interpreter.println(String.format(COLUMN_FORMAT, columns)); } private void printSeparator(final CommandInterpreter interpreter, int length) { interpreter.println(Strings.repeat("-", length)); } private <T> void printLine(final CommandInterpreter interpreter, T item, Function<T, Object>...values) { interpreter.println(String.format(COLUMN_FORMAT, newArrayList(values).stream().map(func -> func.apply(item)).toArray())); } private List<String> resolveArguments(CommandInterpreter interpreter) { List<String> results = Lists.newArrayList(); String argument = interpreter.nextArgument(); while(!isNullOrEmpty(argument)) { results.add(argument); argument = interpreter.nextArgument(); } return results; } public synchronized void createDbIndex(CommandInterpreter interpreter) { String nsUri = interpreter.nextArgument(); if (!Strings.isNullOrEmpty(nsUri)) { ServerDbUtils.createCdoCreatedIndexOnTables(nsUri); } else { interpreter.println("Namespace URI should be specified."); } } private void purge(CommandInterpreter interpreter) { final String repositoryId = interpreter.nextArgument(); if (Strings.isNullOrEmpty(repositoryId)) { interpreter.println("RepositoryId parameter is required"); return; } final String branchPath = interpreter.nextArgument(); if (Strings.isNullOrEmpty(branchPath)) { interpreter.print("BranchPath parameter is required"); return; } final String purgeArg = interpreter.nextArgument(); final Purge purge = Strings.isNullOrEmpty(purgeArg) ? Purge.LATEST : Purge.valueOf(purgeArg); if (purge == null) { interpreter.print("Invalid purge parameter. Select one of " + Joiner.on(",").join(Purge.values())); return; } PurgeRequest.builder() .setBranchPath(branchPath) .setPurge(purge) .build(repositoryId) .execute(getBus()) .getSync(); } private void reindex(CommandInterpreter interpreter) { final String repositoryId = interpreter.nextArgument(); if (Strings.isNullOrEmpty(repositoryId)) { interpreter.println("RepositoryId parameter is required"); return; } final ReindexRequestBuilder req = ReindexRequest.builder(); final String failedCommitTimestamp = interpreter.nextArgument(); if (!StringUtils.isEmpty(failedCommitTimestamp)) { req.setFailedCommitTimestamp(Long.parseLong(failedCommitTimestamp)); } final ReindexResult result = req .build(repositoryId) .execute(getBus()) .getSync(); interpreter.println(result.getMessage()); } private static IEventBus getBus() { return ApplicationContext.getServiceForClass(IEventBus.class); } private void optimize(CommandInterpreter interpreter) { final String repositoryId = interpreter.nextArgument(); if (Strings.isNullOrEmpty(repositoryId)) { interpreter.println("RepositoryId parameter is required."); return; } // default max segments is 1 int maxSegments = 1; final String maxSegmentsArg = interpreter.nextArgument(); if (!Strings.isNullOrEmpty(maxSegmentsArg)) { maxSegments = Integer.parseInt(maxSegmentsArg); } interpreter.println("Optimizing index to max. " + maxSegments + " number of segments..."); OptimizeRequest.builder() .setMaxSegments(maxSegments) .build(repositoryId) .execute(getBus()) .getSync(); interpreter.println("Index optimization completed."); } public synchronized void listBranches(CommandInterpreter interpreter) { String repositoryUUID = interpreter.nextArgument(); if (isValidRepositoryName(repositoryUUID, interpreter)) { String parentBranchPath = interpreter.nextArgument(); if (Strings.isNullOrEmpty(parentBranchPath)) { interpreter.println("Parent branch path was not specified, falling back to MAIN"); parentBranchPath = Branch.MAIN_PATH; } else if (!parentBranchPath.startsWith(Branch.MAIN_PATH)) { interpreter.println("Specify parent branch with full path. i.e. MAIN/PROJECT/TASK1"); return; } Branch parentBranch = null; try { parentBranch = RepositoryRequests.branching() .prepareGet(parentBranchPath) .build(repositoryUUID) .execute(getBus()) .getSync(1000, TimeUnit.MILLISECONDS); } catch (NotFoundException e) { interpreter.println(String.format("Unable to find %s", parentBranchPath)); return; } if (parentBranch != null) { interpreter.println(String.format("Branch hierarchy for %s in repository %s:", parentBranchPath, repositoryUUID)); print(parentBranch, getDepthOfBranch(parentBranch), interpreter); } } } private void print(final Branch branch, final int parentDepth, CommandInterpreter interpreter) { printBranch(branch, getDepthOfBranch(branch) - parentDepth, interpreter); List<? extends Branch> children = FluentIterable.from(branch.children()).filter(new Predicate<Branch>() { @Override public boolean apply(Branch input) { return input.parentPath().equals(branch.path()); } }).toSortedList(new Comparator<Branch>() { @Override public int compare(Branch o1, Branch o2) { return Longs.compare(o1.baseTimestamp(), o2.baseTimestamp()); } }); if (children.size() != 0) { for (Branch child : children) { print(child, parentDepth, interpreter); } } } private void printBranch(Branch branch, int depth, CommandInterpreter interpreter) { interpreter.println(String.format("%-30s %-12s B: %s H: %s", String.format("%s%s%s", getIndentationForBranch(depth), DEFAULT_BRANCH_PREFIX, branch.name()), String.format("[%s]", branch.state()), Dates.formatByGmt(branch.baseTimestamp(), DateFormats.LONG), Dates.formatByGmt(branch.headTimestamp(), DateFormats.LONG))); } private String getIndentationForBranch(int depth) { String indent = ""; for (int i = 0; i < depth; i++) { indent += DEFAULT_INDENT; } return indent; } private int getDepthOfBranch(Branch currentBranch) { return Iterables.size(Splitter.on(Branch.SEPARATOR).split(currentBranch.path())); } private boolean isValidRepositoryName(String repositoryName, CommandInterpreter interpreter) { Set<String> uuidKeySet = getRepositoryManager().uuidKeySet(); if (!uuidKeySet.contains(repositoryName)) { interpreter.println("Could not find repository called: " + repositoryName); interpreter.println("Available repository names are: " + uuidKeySet); return false; } return true; } private ICDORepositoryManager getRepositoryManager() { return ApplicationContext.getServiceForClass(ICDORepositoryManager.class); } }
[console] add --version command to return the server version
core/com.b2international.snowowl.server.console/src/com/b2international/snowowl/server/console/MaintenanceCommandProvider.java
[console] add --version command to return the server version
Java
apache-2.0
435eacdf8abbfff1da8e897abf288e9ec27f7361
0
j-coll/opencga,javild/opencga,kalyanreddyemani/opencga,j-coll/opencga,roalva1/opencga,roalva1/opencga,kalyanreddyemani/opencga,kalyanreddyemani/opencga,javild/opencga,opencb/opencga,roalva1/opencga,j-coll/opencga,kalyanreddyemani/opencga,javild/opencga,roalva1/opencga,j-coll/opencga,roalva1/opencga,opencb/opencga,kalyanreddyemani/opencga,roalva1/opencga,opencb/opencga,roalva1/opencga,roalva1/opencga,roalva1/opencga,opencb/opencga,j-coll/opencga,javild/opencga,javild/opencga,j-coll/opencga,javild/opencga,opencb/opencga,kalyanreddyemani/opencga,opencb/opencga
package org.opencb.opencga.storage.core.variant.stats; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import org.opencb.biodata.models.variant.Variant; import org.opencb.biodata.models.variant.VariantSource; import org.opencb.biodata.models.variant.VariantSourceEntry; import org.opencb.biodata.models.variant.stats.VariantSourceStats; import org.opencb.biodata.models.variant.stats.VariantStats; import org.opencb.datastore.core.QueryOptions; import org.opencb.datastore.core.QueryResult; import org.opencb.opencga.storage.core.variant.VariantStorageManager; import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor; import org.opencb.opencga.storage.core.variant.io.json.VariantStatsJsonMixin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Created by jmmut on 12/02/15. */ public class VariantStatisticsManager { public static final String BATCH_SIZE = "batchSize"; private String VARIANT_STATS_SUFFIX = ".variants.stats.json.gz"; private String SOURCE_STATS_SUFFIX = ".source.stats.json.gz"; private final JsonFactory jsonFactory; private ObjectMapper jsonObjectMapper; protected static Logger logger = LoggerFactory.getLogger(VariantStatisticsManager.class); public VariantStatisticsManager() { jsonFactory = new JsonFactory(); jsonObjectMapper = new ObjectMapper(jsonFactory); jsonObjectMapper.addMixInAnnotations(VariantStats.class, VariantStatsJsonMixin.class); } /** * retrieves batches of Variants, delegates to obtain VariantStatsWrappers from those Variants, and writes them to the output URI. * * @param variantDBAdaptor to obtain the Variants * @param output where to write the VariantStats * @param samples cohorts (subsets) of the samples. key: cohort name, value: list of sample names. * @param options VariantSource, filters to the query, batch size, number of threads to use... * * @return outputUri prefix for the file names (without the "._type_.stats.json.gz") * @throws IOException */ public URI createStats(VariantDBAdaptor variantDBAdaptor, URI output, Map<String, Set<String>> samples, QueryOptions options) throws IOException { /** Open output streams **/ Path fileVariantsPath = Paths.get(output.getPath() + VARIANT_STATS_SUFFIX); OutputStream outputVariantsStream = getOutputStream(fileVariantsPath, options); // PrintWriter printWriter = new PrintWriter(getOutputStream(fileVariantsPath, options)); Path fileSourcePath = Paths.get(output.getPath() + SOURCE_STATS_SUFFIX); OutputStream outputSourceStream = getOutputStream(fileSourcePath, options); /** Initialize Json serializer **/ ObjectWriter variantsWriter = jsonObjectMapper.writerWithType(VariantStatsWrapper.class); ObjectWriter sourceWriter = jsonObjectMapper.writerWithType(VariantSourceStats.class); /** Variables for statistics **/ VariantSource variantSource = options.get(VariantStorageManager.VARIANT_SOURCE, VariantSource.class); // TODO Is this retrievable from the adaptor? VariantSourceStats variantSourceStats = new VariantSourceStats(variantSource.getFileId(), variantSource.getStudyId()); options.put(VariantDBAdaptor.STUDIES, Collections.singletonList(variantSource.getStudyId())); options.put(VariantDBAdaptor.FILES, Collections.singletonList(variantSource.getFileId())); // query just the asked file int batchSize = 1000; // future optimization, threads, etc boolean overwrite = false; batchSize = options.getInt(BATCH_SIZE, batchSize); overwrite = options.getBoolean(VariantStorageManager.OVERWRITE_STATS, overwrite); List<Variant> variantBatch = new ArrayList<>(batchSize); int retrievedVariants = 0; VariantStatisticsCalculator variantStatisticsCalculator = new VariantStatisticsCalculator(overwrite); boolean defaultCohortAbsent = false; logger.info("starting stats calculation"); long start = System.currentTimeMillis(); Iterator<Variant> iterator = obtainIterator(variantDBAdaptor, options); while (iterator.hasNext()) { Variant variant = iterator.next(); retrievedVariants++; variantBatch.add(variant); // variantBatch.add(filterSample(variant, samples)); if (variantBatch.size() == batchSize) { List<VariantStatsWrapper> variantStatsWrappers = variantStatisticsCalculator.calculateBatch(variantBatch, variantSource, samples); for (VariantStatsWrapper variantStatsWrapper : variantStatsWrappers) { outputVariantsStream.write(variantsWriter.writeValueAsBytes(variantStatsWrapper)); if (variantStatsWrapper.getCohortStats().get(VariantSourceEntry.DEFAULT_COHORT) == null) { defaultCohortAbsent = true; } } // we don't want to overwrite file stats regarding all samples with stats about a subset of samples. Maybe if we change VariantSource.stats to a map with every subset... if (!defaultCohortAbsent) { variantSourceStats.updateFileStats(variantBatch); variantSourceStats.updateSampleStats(variantBatch, variantSource.getPedigree()); // TODO test } logger.info("stats created up to position {}:{}", variantBatch.get(variantBatch.size()-1).getChromosome(), variantBatch.get(variantBatch.size()-1).getStart()); variantBatch.clear(); } } if (variantBatch.size() != 0) { List<VariantStatsWrapper> variantStatsWrappers = variantStatisticsCalculator.calculateBatch(variantBatch, variantSource, samples); for (VariantStatsWrapper variantStatsWrapper : variantStatsWrappers) { outputVariantsStream.write(variantsWriter.writeValueAsBytes(variantStatsWrapper)); if (variantStatsWrapper.getCohortStats().get(VariantSourceEntry.DEFAULT_COHORT) == null) { defaultCohortAbsent = true; } } if (!defaultCohortAbsent) { variantSourceStats.updateFileStats(variantBatch); variantSourceStats.updateSampleStats(variantBatch, variantSource.getPedigree()); // TODO test } logger.info("stats created up to position {}:{}", variantBatch.get(variantBatch.size()-1).getChromosome(), variantBatch.get(variantBatch.size()-1).getStart()); variantBatch.clear(); } logger.info("finishing stats calculation, time: {}ms", System.currentTimeMillis() - start); if (variantStatisticsCalculator.getSkippedFiles() != 0) { logger.warn("the sources in {} (of {}) variants were not found, and therefore couldn't run its stats", variantStatisticsCalculator.getSkippedFiles(), retrievedVariants); logger.info("note: maybe the file-id and study-id were not correct?"); } if (variantStatisticsCalculator.getSkippedFiles() == retrievedVariants) { throw new IllegalArgumentException("given fileId and studyId were not found in any variant. Nothing to write."); } outputSourceStream.write(sourceWriter.writeValueAsString(variantSourceStats).getBytes()); outputVariantsStream.close(); outputSourceStream.close(); return output; } private OutputStream getOutputStream(Path filePath, QueryOptions options) throws IOException { OutputStream outputStream = new FileOutputStream(filePath.toFile()); logger.info("will write stats to {}", filePath); if(options != null && options.getBoolean("gzip", true)) { outputStream = new GZIPOutputStream(outputStream); } return outputStream; } /** Gets iterator from OpenCGA Variant database. **/ private Iterator<Variant> obtainIterator(VariantDBAdaptor variantDBAdaptor, QueryOptions options) { QueryOptions iteratorQueryOptions = new QueryOptions(); if(options != null) { //Parse query options iteratorQueryOptions = options; } // TODO rethink this way to refer to the Variant fields (through DBObjectToVariantConverter) List<String> include = Arrays.asList("chromosome", "start", "end", "alternative", "reference", "sourceEntries"); iteratorQueryOptions.add("include", include); return variantDBAdaptor.iterator(iteratorQueryOptions); } /** * Removes samples not present in 'samplesToKeep' * @param variant will be modified * @param samplesToKeep set of names of samples * @return variant with just the samples in 'samplesToKeep' */ public Variant filterSample(Variant variant, Set<String> samplesToKeep) { List<String> toRemove = new ArrayList<>(); if (samplesToKeep != null) { Collection<VariantSourceEntry> sourceEntries = variant.getSourceEntries().values(); Map<String, VariantSourceEntry> filteredSourceEntries = new HashMap<>(sourceEntries.size()); for (VariantSourceEntry sourceEntry : sourceEntries) { for (String name : sourceEntry.getSampleNames()) { if (!samplesToKeep.contains(name)) { toRemove.add(name); } } Set<String> sampleNames = sourceEntry.getSampleNames(); for (String name : toRemove) { sampleNames.remove(name); } } } return variant; } public void loadStats(VariantDBAdaptor variantDBAdaptor, URI uri, QueryOptions options) throws IOException { URI variantStatsUri = Paths.get(uri.getPath() + VARIANT_STATS_SUFFIX).toUri(); URI sourceStatsUri = Paths.get(uri.getPath() + SOURCE_STATS_SUFFIX).toUri(); logger.info("starting stats loading from {} and {}", variantStatsUri, sourceStatsUri); long start = System.currentTimeMillis(); loadVariantStats(variantDBAdaptor, variantStatsUri, options); loadSourceStats(variantDBAdaptor, sourceStatsUri, options); logger.info("finishing stats loading, time: {}ms", System.currentTimeMillis() - start); } public void loadVariantStats(VariantDBAdaptor variantDBAdaptor, URI uri, QueryOptions options) throws IOException { /** Open input streams **/ Path variantInput = Paths.get(uri.getPath()); InputStream variantInputStream; variantInputStream = new FileInputStream(variantInput.toFile()); variantInputStream = new GZIPInputStream(variantInputStream); /** Initialize Json parse **/ JsonParser parser = jsonFactory.createParser(variantInputStream); int batchSize = options.getInt(BATCH_SIZE, 1000); ArrayList<VariantStatsWrapper> statsBatch = new ArrayList<>(batchSize); int writes = 0; int variantsNumber = 0; while (parser.nextToken() != null) { variantsNumber++; statsBatch.add(parser.readValueAs(VariantStatsWrapper.class)); if (statsBatch.size() == batchSize) { QueryResult writeResult = variantDBAdaptor.updateStats(statsBatch, options); writes += writeResult.getNumResults(); logger.info("stats loaded up to position {}:{}", statsBatch.get(statsBatch.size()-1).getChromosome(), statsBatch.get(statsBatch.size()-1).getPosition()); statsBatch.clear(); } } if (!statsBatch.isEmpty()) { QueryResult writeResult = variantDBAdaptor.updateStats(statsBatch, options); writes += writeResult.getNumResults(); logger.info("stats loaded up to position {}:{}", statsBatch.get(statsBatch.size()-1).getChromosome(), statsBatch.get(statsBatch.size()-1).getPosition()); statsBatch.clear(); } if (writes < variantsNumber) { logger.warn("provided statistics of {} variants, but only {} were updated", variantsNumber, writes); logger.info("note: maybe those variants didn't had the proper study? maybe the new and the old stats were the same?"); } } public void loadSourceStats(VariantDBAdaptor variantDBAdaptor, URI uri, QueryOptions options) throws IOException { /** Open input streams **/ Path sourceInput = Paths.get(uri.getPath()); InputStream sourceInputStream; sourceInputStream = new FileInputStream(sourceInput.toFile()); sourceInputStream = new GZIPInputStream(sourceInputStream); /** Initialize Json parse **/ JsonParser sourceParser = jsonFactory.createParser(sourceInputStream); VariantSourceStats variantSourceStats; // if (sourceParser.nextToken() != null) { variantSourceStats = sourceParser.readValueAs(VariantSourceStats.class); // } VariantSource variantSource = options.get(VariantStorageManager.VARIANT_SOURCE, VariantSource.class); // needed? // TODO if variantSourceStats doesn't have studyId and fileId, create another with variantSource.getStudyId() and variantSource.getFileId() variantDBAdaptor.getVariantSourceDBAdaptor().updateSourceStats(variantSourceStats, options); // DBObject studyMongo = sourceConverter.convertToStorageType(source); // DBObject query = new BasicDBObject(DBObjectToVariantSourceConverter.FILEID_FIELD, source.getFileName()); // WriteResult wr = filesCollection.update(query, studyMongo, true, false); } }
opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsManager.java
package org.opencb.opencga.storage.core.variant.stats; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import org.opencb.biodata.models.variant.Variant; import org.opencb.biodata.models.variant.VariantSource; import org.opencb.biodata.models.variant.VariantSourceEntry; import org.opencb.biodata.models.variant.stats.VariantSourceStats; import org.opencb.biodata.models.variant.stats.VariantStats; import org.opencb.datastore.core.QueryOptions; import org.opencb.datastore.core.QueryResult; import org.opencb.opencga.storage.core.variant.VariantStorageManager; import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor; import org.opencb.opencga.storage.core.variant.io.json.VariantStatsJsonMixin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Created by jmmut on 12/02/15. */ public class VariantStatisticsManager { public static final String BATCH_SIZE = "batchSize"; private String VARIANT_STATS_SUFFIX = ".variants.stats.json.gz"; private String SOURCE_STATS_SUFFIX = ".source.stats.json.gz"; private final JsonFactory jsonFactory; private ObjectMapper jsonObjectMapper; protected static Logger logger = LoggerFactory.getLogger(VariantStatisticsManager.class); public VariantStatisticsManager() { jsonFactory = new JsonFactory(); jsonObjectMapper = new ObjectMapper(jsonFactory); jsonObjectMapper.addMixInAnnotations(VariantStats.class, VariantStatsJsonMixin.class); } /** * retrieves batches of Variants, delegates to obtain VariantStatsWrappers from those Variants, and writes them to the output URI. * * @param variantDBAdaptor to obtain the Variants * @param output where to write the VariantStats * @param samples cohorts (subsets) of the samples. key: cohort name, value: list of sample names. * @param options VariantSource, filters to the query, batch size, number of threads to use... * * @return outputUri prefix for the file names (without the "._type_.stats.json.gz") * @throws IOException */ public URI createStats(VariantDBAdaptor variantDBAdaptor, URI output, Map<String, Set<String>> samples, QueryOptions options) throws IOException { /** Open output streams **/ Path fileVariantsPath = Paths.get(output.getPath() + VARIANT_STATS_SUFFIX); OutputStream outputVariantsStream = getOutputStream(fileVariantsPath, options); // PrintWriter printWriter = new PrintWriter(getOutputStream(fileVariantsPath, options)); Path fileSourcePath = Paths.get(output.getPath() + SOURCE_STATS_SUFFIX); OutputStream outputSourceStream = getOutputStream(fileSourcePath, options); /** Initialize Json serializer **/ ObjectWriter variantsWriter = jsonObjectMapper.writerWithType(VariantStatsWrapper.class); ObjectWriter sourceWriter = jsonObjectMapper.writerWithType(VariantSourceStats.class); /** Variables for statistics **/ VariantSource variantSource = options.get(VariantStorageManager.VARIANT_SOURCE, VariantSource.class); // TODO Is this retrievable from the adaptor? VariantSourceStats variantSourceStats = new VariantSourceStats(variantSource.getFileId(), variantSource.getStudyId()); // options.put(VariantDBAdaptor.STUDIES, Collections.singletonList(variantSource.getStudyId())); options.put(VariantDBAdaptor.FILES, Collections.singletonList(variantSource.getFileId())); // query just the asked file int batchSize = 1000; // future optimization, threads, etc boolean overwrite = false; batchSize = options.getInt(BATCH_SIZE, batchSize); overwrite = options.getBoolean(VariantStorageManager.OVERWRITE_STATS, overwrite); List<Variant> variantBatch = new ArrayList<>(batchSize); int retrievedVariants = 0; VariantStatisticsCalculator variantStatisticsCalculator = new VariantStatisticsCalculator(overwrite); boolean defaultCohortAbsent = false; logger.info("starting stats calculation"); long start = System.currentTimeMillis(); Iterator<Variant> iterator = obtainIterator(variantDBAdaptor, options); while (iterator.hasNext()) { Variant variant = iterator.next(); retrievedVariants++; variantBatch.add(variant); // variantBatch.add(filterSample(variant, samples)); if (variantBatch.size() == batchSize) { List<VariantStatsWrapper> variantStatsWrappers = variantStatisticsCalculator.calculateBatch(variantBatch, variantSource, samples); for (VariantStatsWrapper variantStatsWrapper : variantStatsWrappers) { outputVariantsStream.write(variantsWriter.writeValueAsBytes(variantStatsWrapper)); if (variantStatsWrapper.getCohortStats().get(VariantSourceEntry.DEFAULT_COHORT) == null) { defaultCohortAbsent = true; } } // we don't want to overwrite file stats regarding all samples with stats about a subset of samples. Maybe if we change VariantSource.stats to a map with every subset... if (!defaultCohortAbsent) { variantSourceStats.updateFileStats(variantBatch); variantSourceStats.updateSampleStats(variantBatch, variantSource.getPedigree()); // TODO test } logger.info("stats created up to position {}:{}", variantBatch.get(variantBatch.size()-1).getChromosome(), variantBatch.get(variantBatch.size()-1).getStart()); variantBatch.clear(); } } if (variantBatch.size() != 0) { List<VariantStatsWrapper> variantStatsWrappers = variantStatisticsCalculator.calculateBatch(variantBatch, variantSource, samples); for (VariantStatsWrapper variantStatsWrapper : variantStatsWrappers) { outputVariantsStream.write(variantsWriter.writeValueAsBytes(variantStatsWrapper)); if (variantStatsWrapper.getCohortStats().get(VariantSourceEntry.DEFAULT_COHORT) == null) { defaultCohortAbsent = true; } } if (!defaultCohortAbsent) { variantSourceStats.updateFileStats(variantBatch); variantSourceStats.updateSampleStats(variantBatch, variantSource.getPedigree()); // TODO test } logger.info("stats created up to position {}:{}", variantBatch.get(variantBatch.size()-1).getChromosome(), variantBatch.get(variantBatch.size()-1).getStart()); variantBatch.clear(); } logger.info("finishing stats calculation, time: {}ms", System.currentTimeMillis() - start); if (variantStatisticsCalculator.getSkippedFiles() != 0) { logger.warn("the sources in {} (of {}) variants were not found, and therefore couldn't run its stats", variantStatisticsCalculator.getSkippedFiles(), retrievedVariants); logger.info("note: maybe the file-id and study-id were not correct?"); } if (variantStatisticsCalculator.getSkippedFiles() == retrievedVariants) { throw new IllegalArgumentException("given fileId and studyId were not found in any variant. Nothing to write."); } outputSourceStream.write(sourceWriter.writeValueAsString(variantSourceStats).getBytes()); outputVariantsStream.close(); outputSourceStream.close(); return output; } private OutputStream getOutputStream(Path filePath, QueryOptions options) throws IOException { OutputStream outputStream = new FileOutputStream(filePath.toFile()); logger.info("will write stats to {}", filePath); if(options != null && options.getBoolean("gzip", true)) { outputStream = new GZIPOutputStream(outputStream); } return outputStream; } /** Gets iterator from OpenCGA Variant database. **/ private Iterator<Variant> obtainIterator(VariantDBAdaptor variantDBAdaptor, QueryOptions options) { QueryOptions iteratorQueryOptions = new QueryOptions(); if(options != null) { //Parse query options iteratorQueryOptions = options; } // TODO rethink this way to refer to the Variant fields (through DBObjectToVariantConverter) List<String> include = Arrays.asList("chromosome", "start", "end", "alternative", "reference", "sourceEntries"); iteratorQueryOptions.add("include", include); return variantDBAdaptor.iterator(iteratorQueryOptions); } /** * Removes samples not present in 'samplesToKeep' * @param variant will be modified * @param samplesToKeep set of names of samples * @return variant with just the samples in 'samplesToKeep' */ public Variant filterSample(Variant variant, Set<String> samplesToKeep) { List<String> toRemove = new ArrayList<>(); if (samplesToKeep != null) { Collection<VariantSourceEntry> sourceEntries = variant.getSourceEntries().values(); Map<String, VariantSourceEntry> filteredSourceEntries = new HashMap<>(sourceEntries.size()); for (VariantSourceEntry sourceEntry : sourceEntries) { for (String name : sourceEntry.getSampleNames()) { if (!samplesToKeep.contains(name)) { toRemove.add(name); } } Set<String> sampleNames = sourceEntry.getSampleNames(); for (String name : toRemove) { sampleNames.remove(name); } } } return variant; } public void loadStats(VariantDBAdaptor variantDBAdaptor, URI uri, QueryOptions options) throws IOException { URI variantStatsUri = Paths.get(uri.getPath() + VARIANT_STATS_SUFFIX).toUri(); URI sourceStatsUri = Paths.get(uri.getPath() + SOURCE_STATS_SUFFIX).toUri(); logger.info("starting stats loading from {} and {}", variantStatsUri, sourceStatsUri); long start = System.currentTimeMillis(); loadVariantStats(variantDBAdaptor, variantStatsUri, options); loadSourceStats(variantDBAdaptor, sourceStatsUri, options); logger.info("finishing stats loading, time: {}ms", System.currentTimeMillis() - start); } public void loadVariantStats(VariantDBAdaptor variantDBAdaptor, URI uri, QueryOptions options) throws IOException { /** Open input streams **/ Path variantInput = Paths.get(uri.getPath()); InputStream variantInputStream; variantInputStream = new FileInputStream(variantInput.toFile()); variantInputStream = new GZIPInputStream(variantInputStream); /** Initialize Json parse **/ JsonParser parser = jsonFactory.createParser(variantInputStream); int batchSize = options.getInt(BATCH_SIZE, 1000); ArrayList<VariantStatsWrapper> statsBatch = new ArrayList<>(batchSize); int writes = 0; int variantsNumber = 0; while (parser.nextToken() != null) { variantsNumber++; statsBatch.add(parser.readValueAs(VariantStatsWrapper.class)); if (statsBatch.size() == batchSize) { QueryResult writeResult = variantDBAdaptor.updateStats(statsBatch, options); writes += writeResult.getNumResults(); logger.info("stats loaded up to position {}:{}", statsBatch.get(statsBatch.size()-1).getChromosome(), statsBatch.get(statsBatch.size()-1).getPosition()); statsBatch.clear(); } } if (!statsBatch.isEmpty()) { QueryResult writeResult = variantDBAdaptor.updateStats(statsBatch, options); writes += writeResult.getNumResults(); logger.info("stats loaded up to position {}:{}", statsBatch.get(statsBatch.size()-1).getChromosome(), statsBatch.get(statsBatch.size()-1).getPosition()); statsBatch.clear(); } if (writes < variantsNumber) { logger.warn("provided statistics of {} variants, but only {} were updated", variantsNumber, writes); logger.info("note: maybe those variants didn't had the proper study? maybe the new and the old stats were the same?"); } } public void loadSourceStats(VariantDBAdaptor variantDBAdaptor, URI uri, QueryOptions options) throws IOException { /** Open input streams **/ Path sourceInput = Paths.get(uri.getPath()); InputStream sourceInputStream; sourceInputStream = new FileInputStream(sourceInput.toFile()); sourceInputStream = new GZIPInputStream(sourceInputStream); /** Initialize Json parse **/ JsonParser sourceParser = jsonFactory.createParser(sourceInputStream); VariantSourceStats variantSourceStats; // if (sourceParser.nextToken() != null) { variantSourceStats = sourceParser.readValueAs(VariantSourceStats.class); // } VariantSource variantSource = options.get(VariantStorageManager.VARIANT_SOURCE, VariantSource.class); // needed? // TODO if variantSourceStats doesn't have studyId and fileId, create another with variantSource.getStudyId() and variantSource.getFileId() variantDBAdaptor.getVariantSourceDBAdaptor().updateSourceStats(variantSourceStats, options); // DBObject studyMongo = sourceConverter.convertToStorageType(source); // DBObject query = new BasicDBObject(DBObjectToVariantSourceConverter.FILEID_FIELD, source.getFileName()); // WriteResult wr = filesCollection.update(query, studyMongo, true, false); } }
Statistics query by study and file ID to improve index usage #137
opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsManager.java
Statistics query by study and file ID to improve index usage #137
Java
apache-2.0
4dfb4502a6633d8ca50f1d466f80816f1e905550
0
EsupPortail/esup-smsu,EsupPortail/esup-smsu,EsupPortail/esup-smsu
package org.esupportail.smsu.business; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.esupportail.commons.services.logging.Logger; import org.esupportail.commons.services.logging.LoggerImpl; import org.esupportail.smsu.dao.DaoService; import org.esupportail.smsu.dao.beans.Fonction; import org.esupportail.smsu.dao.beans.Role; import org.esupportail.smsu.domain.beans.role.RoleEnum; import org.esupportail.smsu.web.beans.UIRole; import org.springframework.beans.factory.annotation.Autowired; /** * Business layer concerning smsu service. * */ public class RoleManager { @Autowired private DaoService daoService; /** * Log4j logger. */ private final Logger logger = new LoggerImpl(getClass()); /** * retrieve all the roles defined in smsu database. * @return list of uiRoles */ public List<UIRole> getAllRoles() { logger.debug("Retrieve the smsu roles from the database"); List<UIRole> allUIRoles = new ArrayList<UIRole>(); for (Role role : daoService.getRoles()) { allUIRoles.add(convertToUI(role)); } return allUIRoles; } /** * save action. */ public void saveRole(final UIRole role) { daoService.saveRole(convertFromUI(role, true)); } /** * delete action. */ public void deleteRole(int id) { daoService.deleteRole(daoService.getRoleById(id)); } /** * update action. */ public void updateRole(final UIRole uiRole) { Role role = convertFromUI(uiRole, false); Role persistent = daoService.getRoleById(role.getId()); persistent.setName(role.getName()); persistent.setFonctions(role.getFonctions()); daoService.updateRole(persistent); } private Role convertFromUI(UIRole uiRole, boolean isAddMode) { Role result = new Role(); if (!isAddMode) { result.setId(uiRole.id); } result.setName(uiRole.name); result.setFonctions(stringNamesToFonctions(uiRole.fonctions)); return result; } private Fonction stringNameToFonction(String val) { return daoService.getFonctionByName(val); } private Set<Fonction> stringNamesToFonctions(List<String> selectedValues) { Set<Fonction> fonctions = new HashSet<Fonction>(); for (String val : selectedValues) { fonctions.add(stringNameToFonction(val)); } return fonctions; } private UIRole convertToUI(Role role) { boolean isDeletable = !daoService.isRoleInUse(role); // if not attached to Customized Groups boolean isUpdateable = true; // Role super admin (Id=1) et utilisateur connected n'est pas supprimable ni modifiable if (role.getName().equals(RoleEnum.SUPER_ADMIN.toString())) { isDeletable = false; isUpdateable = false; } UIRole result = new UIRole(); result.id = role.getId(); result.name = role.getName(); result.fonctions = fonctionsToStringNames(role.getFonctions()); result.isDeletable = isDeletable; result.isUpdateable = isUpdateable; return result; } private List<String> fonctionsToStringNames(Set<Fonction> fonctions) { List<String> selectedValues = new ArrayList<String>(); for (Fonction fct : fonctions) { if (FonctionManager.toFonctionName(fct.getName()) != null) // filter obsolete Fonctions (eg: FCTN_APPROBATION_ENVOI) selectedValues.add(fct.getName()); } return selectedValues; } }
src/main/java/org/esupportail/smsu/business/RoleManager.java
package org.esupportail.smsu.business; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.esupportail.commons.services.logging.Logger; import org.esupportail.commons.services.logging.LoggerImpl; import org.esupportail.smsu.dao.DaoService; import org.esupportail.smsu.dao.beans.Fonction; import org.esupportail.smsu.dao.beans.Role; import org.esupportail.smsu.domain.beans.role.RoleEnum; import org.esupportail.smsu.web.beans.UIRole; import org.springframework.beans.factory.annotation.Autowired; /** * Business layer concerning smsu service. * */ public class RoleManager { @Autowired private DaoService daoService; /** * Log4j logger. */ private final Logger logger = new LoggerImpl(getClass()); /** * retrieve all the roles defined in smsu database. * @return list of uiRoles */ public List<UIRole> getAllRoles() { logger.debug("Retrieve the smsu roles from the database"); List<UIRole> allUIRoles = new ArrayList<UIRole>(); for (Role role : daoService.getRoles()) { allUIRoles.add(convertToUI(role)); } return allUIRoles; } /** * save action. */ public void saveRole(final UIRole role) { daoService.saveRole(convertFromUI(role, true)); } /** * delete action. */ public void deleteRole(int id) { daoService.deleteRole(daoService.getRoleById(id)); } /** * update action. */ public void updateRole(final UIRole uiRole) { Role role = convertFromUI(uiRole, false); Role persistent = daoService.getRoleById(role.getId()); persistent.setName(role.getName()); persistent.setFonctions(role.getFonctions()); daoService.updateRole(persistent); } private Role convertFromUI(UIRole uiRole, boolean isAddMode) { Role result = new Role(); if (!isAddMode) { result.setId(uiRole.id); } result.setName(uiRole.name); result.setFonctions(stringNamesToFonctions(uiRole.fonctions)); return result; } private Fonction stringNameToFonction(String val) { return daoService.getFonctionByName(val); } private Set<Fonction> stringNamesToFonctions(List<String> selectedValues) { Set<Fonction> fonctions = new HashSet<Fonction>(); for (String val : selectedValues) { fonctions.add(stringNameToFonction(val)); } return fonctions; } private UIRole convertToUI(Role role) { boolean isDeletable = !daoService.isRoleInUse(role); // if not attached to Customized Groups boolean isUpdateable = true; // Role super admin (Id=1) et utilisateur connected n'est pas supprimable ni modifiable if (role.getName().equals(RoleEnum.SUPER_ADMIN.toString())) { isDeletable = false; isUpdateable = false; } UIRole result = new UIRole(); result.id = role.getId(); result.name = role.getName(); result.fonctions = fonctionsToStringNames(role.getFonctions()); result.isDeletable = isDeletable; result.isUpdateable = isUpdateable; return result; } private List<String> fonctionsToStringNames(Set<Fonction> fonctions) { List<String> selectedValues = new ArrayList<String>(); for (Fonction fct : fonctions) { selectedValues.add(fct.getName()); } return selectedValues; } }
RoleManager: filter obsolete Fonctions when creating UIRole
src/main/java/org/esupportail/smsu/business/RoleManager.java
RoleManager: filter obsolete Fonctions when creating UIRole
Java
apache-2.0
f7ce3c1e5f1f083b045f92c3b08d4307aad5e47b
0
statsbiblioteket/summa,statsbiblioteket/summa,statsbiblioteket/summa,statsbiblioteket/summa
/* * 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 dk.statsbiblioteket.summa.search; import dk.statsbiblioteket.summa.common.configuration.Configuration; import dk.statsbiblioteket.summa.search.api.Request; import dk.statsbiblioteket.summa.search.api.Response; import dk.statsbiblioteket.summa.search.api.ResponseCollection; import dk.statsbiblioteket.summa.search.api.document.DocumentKeys; import dk.statsbiblioteket.summa.search.api.document.DocumentResponse; import dk.statsbiblioteket.util.qa.QAInfo; import junit.framework.TestCase; import java.io.IOException; import java.rmi.RemoteException; @QAInfo(level = QAInfo.Level.NORMAL, state = QAInfo.State.IN_DEVELOPMENT, author = "te") public class PagingSearchNodeTest extends TestCase { public void testBasicSearch() throws Exception { ResponseCollection responses = search(true, 50, 20, new Request( DocumentKeys.SEARCH_QUERY, "foo" )); assertResponse("Base search", responses, 0, 20, 20, 20); } public void testLargeSearch() throws Exception { ResponseCollection responses = search(true, 50, 20, new Request( DocumentKeys.SEARCH_QUERY, "foo", DocumentKeys.SEARCH_MAX_RECORDS, 40 )); assertResponse("Base search", responses, 0, 40, 40, 40); } public void testExceedingMaxPage() throws Exception { ResponseCollection responses = search(true, 50, 20, new Request( DocumentKeys.SEARCH_QUERY, "foo", DocumentKeys.SEARCH_MAX_RECORDS, 60 )); assertResponse("Base search", responses, 0, 60, 60, 60); } public void testStartPagePlain() throws Exception { ResponseCollection responses = search(true, 50, 20, new Request( DocumentKeys.SEARCH_QUERY, "foo", DocumentKeys.SEARCH_START_INDEX, 20, DocumentKeys.SEARCH_MAX_RECORDS, 20 )); assertResponse("Base search", responses, 20, 20, 20, 20); } public void testStartPageExceeding() throws Exception { ResponseCollection responses = search(true, 50, 20, new Request( DocumentKeys.SEARCH_QUERY, "foo", DocumentKeys.SEARCH_START_INDEX, 20, DocumentKeys.SEARCH_MAX_RECORDS, 60 )); assertResponse("Base search", responses, 20, 60, 60, 60); } public void testDummyNode() { new DummyNode(Configuration.newMemoryBased()); } private void assertResponse(String message, ResponseCollection responses, int startIndex, int maxRecords, int hitCount, int recordCount) { DocumentResponse docs = null; for (Response response: responses) { if (response instanceof DocumentResponse) { docs = (DocumentResponse)response; } } if (docs == null) { fail("No DocumentResponse in " + responses); } assertEquals(message + ". startIndex should be correct", startIndex, docs.getStartIndex()); assertEquals(message + ". maxRecords should be correct", maxRecords, docs.getMaxRecords()); assertEquals(message + ". hitCount should be correct", hitCount, docs.getHitCount()); assertEquals(message + ". recordCount should be correct", recordCount, docs.getRecords().size()); int id = startIndex; for (DocumentResponse.Record record: docs.getRecords()) { assertEquals(message + ". Record ID should be correct ", "index_" + id++, record.getId()); } } private ResponseCollection search(boolean sequential, int maxPagesize, int guiPagesize, Request request) throws IOException { SearchNode pager = getPager(sequential, maxPagesize, guiPagesize); ResponseCollection responses = new ResponseCollection(); pager.search(request, responses); return responses; } private SearchNode getPager(boolean sequential, int maxPagesize, int guiPagesize) throws IOException { Configuration conf = Configuration.newMemoryBased( PagingSearchNode.CONF_SEQUENTIAL, sequential, PagingSearchNode.CONF_MAXPAGESIZE, maxPagesize, PagingSearchNode.CONF_GUIPAGESIZE, guiPagesize, SearchNodeFactory.CONF_NODE_CLASS, DummyNode.class); return new PagingSearchNode(conf); } public static class DummyNode implements SearchNode { public DummyNode(Configuration conf) { } @Override public void search(Request request, ResponseCollection responses) throws RemoteException { int start = request.getInt(DocumentKeys.SEARCH_START_INDEX, 0); int maxRecords = request.getInt(DocumentKeys.SEARCH_MAX_RECORDS, 20); DocumentResponse docs = new DocumentResponse( request.getString(DocumentKeys.SEARCH_FILTER, null), request.getString(DocumentKeys.SEARCH_QUERY, null), request.getInt(DocumentKeys.SEARCH_START_INDEX, 0), maxRecords, request.getString(DocumentKeys.SEARCH_SORTKEY, null), request.getBoolean(DocumentKeys.SEARCH_REVERSE, false), request.getStrings(DocumentKeys.SEARCH_RESULT_FIELDS, new String[0]), 0L, // searchTime maxRecords); for (int i = start ; i < start + maxRecords ; i++) { DocumentResponse.Record record = new DocumentResponse.Record( "index_" + i, "dummy", 0.001f + i, Integer.toString(i)); record.addField(new DocumentResponse.Field("recordID", "index_" + i, false)); record.addField(new DocumentResponse.Field("recordBase", "dummy", false)); docs.addRecord(record); } responses.add(docs); } @Override public void warmup(String request) { } @Override public void open(String location) throws RemoteException { } @Override public void close() throws RemoteException { } @Override public int getFreeSlots() { return Integer.MAX_VALUE; } } }
Core/src/test/java/dk/statsbiblioteket/summa/search/PagingSearchNodeTest.java
/* * 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 dk.statsbiblioteket.summa.search; import dk.statsbiblioteket.summa.common.configuration.Configuration; import dk.statsbiblioteket.summa.search.api.Request; import dk.statsbiblioteket.summa.search.api.Response; import dk.statsbiblioteket.summa.search.api.ResponseCollection; import dk.statsbiblioteket.summa.search.api.document.DocumentKeys; import dk.statsbiblioteket.summa.search.api.document.DocumentResponse; import dk.statsbiblioteket.util.qa.QAInfo; import junit.framework.TestCase; import java.io.IOException; import java.rmi.RemoteException; @QAInfo(level = QAInfo.Level.NORMAL, state = QAInfo.State.IN_DEVELOPMENT, author = "te") public class PagingSearchNodeTest extends TestCase { public void testBasicSearch() throws Exception { ResponseCollection responses = search(true, 50, 20, new Request( DocumentKeys.SEARCH_QUERY, "foo" )); assertResponse("Base search", responses, 0, 20, 20, 20); } public void testLargeSearch() throws Exception { ResponseCollection responses = search(true, 50, 20, new Request( DocumentKeys.SEARCH_QUERY, "foo", DocumentKeys.SEARCH_MAX_RECORDS, 40 )); assertResponse("Base search", responses, 0, 40, 40, 40); } public void testExceedingMaxPage() throws Exception { ResponseCollection responses = search(true, 50, 20, new Request( DocumentKeys.SEARCH_QUERY, "foo", DocumentKeys.SEARCH_MAX_RECORDS, 60 )); assertResponse("Base search", responses, 0, 60, 60, 60); } public void testDummyNode() { new DummyNode(Configuration.newMemoryBased()); } private void assertResponse(String message, ResponseCollection responses, int startIndex, int maxRecords, int hitCount, int recordCount) { DocumentResponse docs = null; for (Response response: responses) { if (response instanceof DocumentResponse) { docs = (DocumentResponse)response; } } if (docs == null) { fail("No DocumentResponse in " + responses); } assertEquals(message + ". startIndex should be correct", startIndex, docs.getStartIndex()); assertEquals(message + ". maxRecords should be correct", maxRecords, docs.getMaxRecords()); assertEquals(message + ". hitCount should be correct", hitCount, docs.getHitCount()); assertEquals(message + ". recordCount should be correct", recordCount, docs.getRecords().size()); int id = startIndex; for (DocumentResponse.Record record: docs.getRecords()) { assertEquals(message + ". Record ID should be correct ", "index_" + id++, record.getId()); } } private ResponseCollection search(boolean sequential, int maxPagesize, int guiPagesize, Request request) throws IOException { SearchNode pager = getPager(sequential, maxPagesize, guiPagesize); ResponseCollection responses = new ResponseCollection(); pager.search(request, responses); return responses; } private SearchNode getPager(boolean sequential, int maxPagesize, int guiPagesize) throws IOException { Configuration conf = Configuration.newMemoryBased( PagingSearchNode.CONF_SEQUENTIAL, sequential, PagingSearchNode.CONF_MAXPAGESIZE, maxPagesize, PagingSearchNode.CONF_GUIPAGESIZE, guiPagesize, SearchNodeFactory.CONF_NODE_CLASS, DummyNode.class); return new PagingSearchNode(conf); } public static class DummyNode implements SearchNode { public DummyNode(Configuration conf) { } @Override public void search(Request request, ResponseCollection responses) throws RemoteException { int start = request.getInt(DocumentKeys.SEARCH_START_INDEX, 0); int maxRecords = request.getInt(DocumentKeys.SEARCH_MAX_RECORDS, 20); DocumentResponse docs = new DocumentResponse( request.getString(DocumentKeys.SEARCH_FILTER, null), request.getString(DocumentKeys.SEARCH_QUERY, null), request.getInt(DocumentKeys.SEARCH_START_INDEX, 0), maxRecords, request.getString(DocumentKeys.SEARCH_SORTKEY, null), request.getBoolean(DocumentKeys.SEARCH_REVERSE, false), request.getStrings(DocumentKeys.SEARCH_RESULT_FIELDS, new String[0]), 0L, // searchTime maxRecords); for (int i = start ; i < start + maxRecords ; i++) { DocumentResponse.Record record = new DocumentResponse.Record( "index_" + i, "dummy", 0.001f + i, Integer.toString(i)); record.addField(new DocumentResponse.Field("recordID", "index_" + i, false)); record.addField(new DocumentResponse.Field("recordBase", "dummy", false)); docs.addRecord(record); } responses.add(docs); } @Override public void warmup(String request) { } @Override public void open(String location) throws RemoteException { } @Override public void close() throws RemoteException { } @Override public int getFreeSlots() { return Integer.MAX_VALUE; } } }
Testing: More (non-passing) unit tests for PagingSearchNode
Core/src/test/java/dk/statsbiblioteket/summa/search/PagingSearchNodeTest.java
Testing: More (non-passing) unit tests for PagingSearchNode
Java
apache-2.0
55a6d53fb58fef5e264a5fbe31663c2b7d93e49c
0
phax/ph-oton,phax/ph-oton,phax/ph-oton
/* * Copyright (C) 2014-2021 Philip Helger (www.helger.com) * philip[at]helger[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.helger.html.hc.html.forms; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.OverridingMethodsMustInvokeSuper; import javax.annotation.concurrent.NotThreadSafe; import com.helger.commons.CGlobal; import com.helger.commons.ValueEnforcer; import com.helger.commons.mime.IMimeType; import com.helger.commons.state.ETriState; import com.helger.commons.string.StringHelper; import com.helger.commons.string.ToStringGenerator; import com.helger.commons.url.ISimpleURL; import com.helger.html.CHTMLAttributeValues; import com.helger.html.CHTMLAttributes; import com.helger.html.EHTMLElement; import com.helger.html.hc.IHCConversionSettingsToNode; import com.helger.html.hc.html.HC_Action; import com.helger.html.hc.html.HC_Target; import com.helger.html.js.IHasJSCode; import com.helger.html.js.IHasJSCodeWithSettings; import com.helger.xml.microdom.IMicroElement; @NotThreadSafe public abstract class AbstractHCInput <IMPLTYPE extends AbstractHCInput <IMPLTYPE>> extends AbstractHCControl <IMPLTYPE> implements IHCInput <IMPLTYPE> { /** By default no auto complete setting is active */ public static final ETriState DEFAULT_AUTO_COMPLETE = ETriState.UNDEFINED; /** Not checked by default */ public static final boolean DEFAULT_CHECKED = false; /** Default value */ public static final boolean DEFAULT_FORMNOVALIDATE = false; /** By default multi select is disabled */ public static final boolean DEFAULT_MULTIPLE = false; private EHCInputType m_eType; private String m_sAccept; private String m_sAlt; private ETriState m_eAutoComplete = DEFAULT_AUTO_COMPLETE; private boolean m_bChecked = DEFAULT_CHECKED; private String m_sDirName; // disabled is inherited private String m_sForm; private final HC_Action m_aFormAction = new HC_Action (); private IMimeType m_aFormEncType; private EHCFormMethod m_eFormMethod; private boolean m_bFormNoValidate = DEFAULT_FORMNOVALIDATE; private HC_Target m_aFormTarget; private int m_nHeight = CGlobal.ILLEGAL_UINT; // TODO inputmode private String m_sList; private String m_sMaxValue; private int m_nMaxLength = CGlobal.ILLEGAL_UINT; private String m_sMinValue; private int m_nMinLength = CGlobal.ILLEGAL_UINT; private boolean m_bMultiple = DEFAULT_MULTIPLE; // name is inherited private String m_sPattern; private String m_sPlaceholder; // readonly is inherited // required is inherited private int m_nSize = CGlobal.ILLEGAL_UINT; private ISimpleURL m_aSrc; private String m_sStep; private String m_sValue; private int m_nWidth = CGlobal.ILLEGAL_UINT; /** * Default ctor */ public AbstractHCInput () { super (EHTMLElement.INPUT); } /** * Default ctor * * @param eType * Type of input. May not be <code>null</code>. */ public AbstractHCInput (@Nonnull final EHCInputType eType) { this (); setType (eType); } @Nullable public final EHCInputType getType () { return m_eType; } @Nonnull public final IMPLTYPE setType (@Nullable final EHCInputType eType) { m_eType = eType; return thisAsT (); } @Nullable public final String getAccept () { return m_sAccept; } @Nonnull public final IMPLTYPE setAccept (@Nullable final String sAccept) { m_sAccept = sAccept; return thisAsT (); } @Nonnull public final IMPLTYPE setAccept (@Nullable final IMimeType aAccept) { return setAccept (aAccept == null ? null : aAccept.getAsString ()); } @Nullable public final String getAlt () { return m_sAlt; } @Nonnull public final IMPLTYPE setAlt (@Nullable final String sAlt) { m_sAlt = sAlt; return thisAsT (); } public final boolean isAutoCompleteOn () { return m_eAutoComplete.isTrue (); } public final boolean isAutoCompleteOff () { return m_eAutoComplete.isFalse (); } public final boolean isAutoCompleteUndefined () { return m_eAutoComplete.isUndefined (); } @Nonnull public final IMPLTYPE setAutoComplete (@Nonnull final ETriState eAutoComplete) { m_eAutoComplete = ValueEnforcer.notNull (eAutoComplete, "AutoComplete"); return thisAsT (); } public final boolean isChecked () { return m_bChecked; } @Nonnull public final IMPLTYPE setChecked (final boolean bChecked) { m_bChecked = bChecked; return thisAsT (); } @Nullable public final String getDirName () { return m_sDirName; } @Nonnull public final IMPLTYPE setDirName (@Nullable final String sDirName) { m_sDirName = sDirName; return thisAsT (); } @Nullable public final String getForm () { return m_sForm; } @Nonnull public final IMPLTYPE setForm (@Nullable final String sForm) { m_sForm = sForm; return thisAsT (); } @Nullable public final ISimpleURL getFormActionURL () { return m_aFormAction.getActionURL (); } @Nullable public final IHasJSCode getFormActionJS () { return m_aFormAction.getActionJS (); } @Nonnull public final IMPLTYPE setFormAction (@Nullable final ISimpleURL aAction) { m_aFormAction.setAction (aAction); return thisAsT (); } @Nonnull public final IMPLTYPE setFormAction (@Nullable final IHasJSCodeWithSettings aAction) { m_aFormAction.setAction (aAction); return thisAsT (); } @Nullable public final IMimeType getFormEncType () { return m_aFormEncType; } @Nonnull public final IMPLTYPE setFormEncType (@Nullable final IMimeType aFormEncType) { m_aFormEncType = aFormEncType; return thisAsT (); } @Nullable public final EHCFormMethod getFormMethod () { return m_eFormMethod; } @Nonnull public final IMPLTYPE setFormMethod (@Nullable final EHCFormMethod eFormMethod) { m_eFormMethod = eFormMethod; return thisAsT (); } public final boolean isFormNoValidate () { return m_bFormNoValidate; } @Nonnull public final IMPLTYPE setFormNoValidate (final boolean bFormNoValidate) { m_bFormNoValidate = bFormNoValidate; return thisAsT (); } @Nullable public final HC_Target getFormTarget () { return m_aFormTarget; } @Nonnull public final IMPLTYPE setFormTarget (@Nullable final HC_Target aFormTarget) { m_aFormTarget = aFormTarget; return thisAsT (); } public final int getHeight () { return m_nHeight; } @Nonnull public final IMPLTYPE setHeight (final int nHeight) { m_nHeight = nHeight; return thisAsT (); } @Nullable public final String getList () { return m_sList; } @Nonnull public final IMPLTYPE setList (@Nullable final String sList) { m_sList = sList; return thisAsT (); } @Nullable public final String getMaxValue () { return m_sMaxValue; } @Nonnull public final IMPLTYPE setMaxValue (@Nullable final String sMaxValue) { m_sMaxValue = sMaxValue; return thisAsT (); } public final int getMaxLength () { return m_nMaxLength; } @Nonnull public final IMPLTYPE setMaxLength (final int nMaxLength) { m_nMaxLength = nMaxLength; return thisAsT (); } @Nullable public final String getMinValue () { return m_sMinValue; } @Nonnull public final IMPLTYPE setMinValue (@Nullable final String sMinValue) { m_sMinValue = sMinValue; return thisAsT (); } public final int getMinLength () { return m_nMinLength; } @Nonnull public final IMPLTYPE setMinLength (final int nMinLength) { m_nMinLength = nMinLength; return thisAsT (); } public final boolean isMultiple () { return m_bMultiple; } @Nonnull public final IMPLTYPE setMultiple (final boolean bMultiple) { m_bMultiple = bMultiple; return thisAsT (); } @Nullable public final String getPattern () { return m_sPattern; } @Nonnull public final IMPLTYPE setPattern (@Nullable final String sPattern) { m_sPattern = sPattern; return thisAsT (); } @Nullable public final String getPlaceholder () { return m_sPlaceholder; } @Nonnull public final IMPLTYPE setPlaceholder (@Nullable final String sPlaceholder) { m_sPlaceholder = sPlaceholder; return thisAsT (); } public final int getSize () { return m_nSize; } @Nonnull public final IMPLTYPE setSize (final int nSize) { m_nSize = nSize; return thisAsT (); } @Nullable public final ISimpleURL getSrc () { return m_aSrc; } @Nonnull public final IMPLTYPE setSrc (@Nullable final ISimpleURL aSrc) { m_aSrc = aSrc; return thisAsT (); } @Nullable public final String getStep () { return m_sStep; } @Nonnull public final IMPLTYPE setStep (@Nullable final String sStep) { m_sStep = sStep; return thisAsT (); } /** * @return The field value, maybe <code>null</code> */ @Nullable public final String getValue () { return m_sValue; } @Nonnull public final IMPLTYPE setValue (@Nullable final String sValue) { m_sValue = sValue; return thisAsT (); } public final int getWidth () { return m_nWidth; } @Nonnull public final IMPLTYPE setWidth (final int nWidth) { m_nWidth = nWidth; return thisAsT (); } @Override public String getPlainText () { return StringHelper.getNotNull (getValue ()); } @Override @OverridingMethodsMustInvokeSuper protected void fillMicroElement (final IMicroElement aElement, final IHCConversionSettingsToNode aConversionSettings) { super.fillMicroElement (aElement, aConversionSettings); if (m_eType != null) aElement.setAttribute (CHTMLAttributes.TYPE, m_eType); if (StringHelper.hasText (m_sAccept)) aElement.setAttribute (CHTMLAttributes.ACCEPT, m_sAccept); if (StringHelper.hasText (m_sAlt)) aElement.setAttribute (CHTMLAttributes.ALT, m_sAlt); if (m_eAutoComplete.isDefined ()) aElement.setAttribute (CHTMLAttributes.AUTOCOMPLETE, m_eAutoComplete.isTrue () ? CHTMLAttributeValues.ON : CHTMLAttributeValues.OFF); if (m_bChecked) aElement.setAttribute (CHTMLAttributes.CHECKED, CHTMLAttributeValues.CHECKED); if (StringHelper.hasText (m_sDirName)) aElement.setAttribute (CHTMLAttributes.DIRNAME, m_sDirName); if (StringHelper.hasText (m_sForm)) aElement.setAttribute (CHTMLAttributes.FORM, m_sForm); m_aFormAction.applyProperties (CHTMLAttributes.FORMACTION, aElement, aConversionSettings.getJSWriterSettings (), aConversionSettings.getCharset ()); if (m_aFormEncType != null) aElement.setAttribute (CHTMLAttributes.FORMENCTYPE, m_aFormEncType.getAsString ()); if (m_eFormMethod != null) aElement.setAttribute (CHTMLAttributes.FORMMETHOD, m_eFormMethod); if (m_bFormNoValidate) aElement.setAttribute (CHTMLAttributes.FORMNOVALIDATE, CHTMLAttributeValues.FORMNOVALIDATE); if (m_aFormTarget != null) aElement.setAttribute (CHTMLAttributes.FORMTARGET, m_aFormTarget); if (m_nHeight > 0) aElement.setAttribute (CHTMLAttributes.HEIGHT, m_nHeight); if (StringHelper.hasText (m_sList)) aElement.setAttribute (CHTMLAttributes.LIST, m_sList); if (StringHelper.hasText (m_sMaxValue)) aElement.setAttribute (CHTMLAttributes.MAX, m_sMaxValue); if (m_nMaxLength > 0) aElement.setAttribute (CHTMLAttributes.MAXLENGTH, m_nMaxLength); if (StringHelper.hasText (m_sMinValue)) aElement.setAttribute (CHTMLAttributes.MIN, m_sMinValue); if (m_nMinLength > 0) aElement.setAttribute (CHTMLAttributes.MINLENGTH, m_nMinLength); if (m_bMultiple) aElement.setAttribute (CHTMLAttributes.MULTIPLE, CHTMLAttributeValues.MULTIPLE); if (StringHelper.hasText (m_sPattern)) aElement.setAttribute (CHTMLAttributes.PATTERN, m_sPattern); if (StringHelper.hasText (m_sPlaceholder)) aElement.setAttribute (CHTMLAttributes.PLACEHOLDER, m_sPlaceholder); if (m_nSize > 0) aElement.setAttribute (CHTMLAttributes.SIZE, m_nSize); if (m_aSrc != null) aElement.setAttribute (CHTMLAttributes.SRC, m_aSrc.getAsStringWithEncodedParameters (aConversionSettings.getCharset ())); if (StringHelper.hasText (m_sStep)) aElement.setAttribute (CHTMLAttributes.STEP, m_sStep); if (m_sValue != null) aElement.setAttribute (CHTMLAttributes.VALUE, m_sValue); if (m_nWidth > 0) aElement.setAttribute (CHTMLAttributes.WIDTH, m_nWidth); } @Override public String toString () { return ToStringGenerator.getDerived (super.toString ()) .appendIfNotNull ("type", m_eType) .appendIfNotNull ("accept", m_sAccept) .appendIfNotNull ("alt", m_sAlt) .append ("autoComplete", m_eAutoComplete) .append ("checked", m_bChecked) .appendIfNotNull ("dirname", m_sDirName) .appendIfNotNull ("form", m_sForm) .append ("formaction", m_aFormAction) .appendIfNotNull ("formenctype", m_aFormEncType) .appendIfNotNull ("formmethod", m_eFormMethod) .append ("formnovalidate", m_bFormNoValidate) .appendIfNotNull ("formtarget", m_aFormTarget) .append ("height", m_nHeight) .appendIfNotNull ("list", m_sList) .appendIfNotNull ("maxValue", m_sMaxValue) .append ("maxLength", m_nMaxLength) .appendIfNotNull ("minValue", m_sMinValue) .append ("minLength", m_nMinLength) .append ("multiple", m_bMultiple) .appendIfNotNull ("pattern", m_sPattern) .appendIfNotNull ("placeholder", m_sPlaceholder) .append ("size", m_nSize) .appendIfNotNull ("src", m_aSrc) .appendIfNotNull ("step", m_sStep) .appendIfNotNull ("value", m_sValue) .append ("width", m_nWidth) .getToString (); } }
ph-oton-html/src/main/java/com/helger/html/hc/html/forms/AbstractHCInput.java
/* * Copyright (C) 2014-2021 Philip Helger (www.helger.com) * philip[at]helger[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.helger.html.hc.html.forms; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.OverridingMethodsMustInvokeSuper; import javax.annotation.concurrent.NotThreadSafe; import com.helger.commons.CGlobal; import com.helger.commons.ValueEnforcer; import com.helger.commons.mime.IMimeType; import com.helger.commons.state.ETriState; import com.helger.commons.string.StringHelper; import com.helger.commons.string.ToStringGenerator; import com.helger.commons.url.ISimpleURL; import com.helger.html.CHTMLAttributeValues; import com.helger.html.CHTMLAttributes; import com.helger.html.EHTMLElement; import com.helger.html.hc.IHCConversionSettingsToNode; import com.helger.html.hc.html.HC_Action; import com.helger.html.hc.html.HC_Target; import com.helger.html.js.IHasJSCode; import com.helger.html.js.IHasJSCodeWithSettings; import com.helger.xml.microdom.IMicroElement; @NotThreadSafe public abstract class AbstractHCInput <IMPLTYPE extends AbstractHCInput <IMPLTYPE>> extends AbstractHCControl <IMPLTYPE> implements IHCInput <IMPLTYPE> { /** By default no auto complete setting is active */ public static final ETriState DEFAULT_AUTO_COMPLETE = ETriState.UNDEFINED; /** Not checked by default */ public static final boolean DEFAULT_CHECKED = false; /** Default value */ public static final boolean DEFAULT_FORMNOVALIDATE = false; /** By default multi select is disabled */ public static final boolean DEFAULT_MULTIPLE = false; private EHCInputType m_eType; private String m_sAccept; private String m_sAlt; private ETriState m_eAutoComplete = DEFAULT_AUTO_COMPLETE; private boolean m_bChecked = DEFAULT_CHECKED; private String m_sDirName; // disabled is inherited private String m_sForm; private final HC_Action m_aFormAction = new HC_Action (); private IMimeType m_aFormEncType; private EHCFormMethod m_eFormMethod; private boolean m_bFormNoValidate = DEFAULT_FORMNOVALIDATE; private HC_Target m_aFormTarget; private int m_nHeight = CGlobal.ILLEGAL_UINT; // TODO inputmode private String m_sList; private String m_sMaxValue; private int m_nMaxLength = CGlobal.ILLEGAL_UINT; private String m_sMinValue; private int m_nMinLength = CGlobal.ILLEGAL_UINT; private boolean m_bMultiple = DEFAULT_MULTIPLE; // name is inherited private String m_sPattern; private String m_sPlaceholder; // readonly is inherited // required is inherited private int m_nSize = CGlobal.ILLEGAL_UINT; private ISimpleURL m_aSrc; private String m_sStep; private String m_sValue; private int m_nWidth = CGlobal.ILLEGAL_UINT; /** * Default ctor */ public AbstractHCInput () { super (EHTMLElement.INPUT); } /** * Default ctor * * @param eType * Type of input. May not be <code>null</code>. */ public AbstractHCInput (@Nonnull final EHCInputType eType) { this (); setType (eType); } @Nullable public final EHCInputType getType () { return m_eType; } @Nonnull public final IMPLTYPE setType (@Nonnull final EHCInputType eType) { m_eType = ValueEnforcer.notNull (eType, "Type"); return thisAsT (); } @Nullable public final String getAccept () { return m_sAccept; } @Nonnull public final IMPLTYPE setAccept (@Nullable final String sAccept) { m_sAccept = sAccept; return thisAsT (); } @Nonnull public final IMPLTYPE setAccept (@Nullable final IMimeType aAccept) { return setAccept (aAccept == null ? null : aAccept.getAsString ()); } @Nullable public final String getAlt () { return m_sAlt; } @Nonnull public final IMPLTYPE setAlt (@Nullable final String sAlt) { m_sAlt = sAlt; return thisAsT (); } public final boolean isAutoCompleteOn () { return m_eAutoComplete.isTrue (); } public final boolean isAutoCompleteOff () { return m_eAutoComplete.isFalse (); } public final boolean isAutoCompleteUndefined () { return m_eAutoComplete.isUndefined (); } @Nonnull public final IMPLTYPE setAutoComplete (@Nonnull final ETriState eAutoComplete) { m_eAutoComplete = ValueEnforcer.notNull (eAutoComplete, "AutoComplete"); return thisAsT (); } public final boolean isChecked () { return m_bChecked; } @Nonnull public final IMPLTYPE setChecked (final boolean bChecked) { m_bChecked = bChecked; return thisAsT (); } @Nullable public final String getDirName () { return m_sDirName; } @Nonnull public final IMPLTYPE setDirName (@Nullable final String sDirName) { m_sDirName = sDirName; return thisAsT (); } @Nullable public final String getForm () { return m_sForm; } @Nonnull public final IMPLTYPE setForm (@Nullable final String sForm) { m_sForm = sForm; return thisAsT (); } @Nullable public final ISimpleURL getFormActionURL () { return m_aFormAction.getActionURL (); } @Nullable public final IHasJSCode getFormActionJS () { return m_aFormAction.getActionJS (); } @Nonnull public final IMPLTYPE setFormAction (@Nullable final ISimpleURL aAction) { m_aFormAction.setAction (aAction); return thisAsT (); } @Nonnull public final IMPLTYPE setFormAction (@Nullable final IHasJSCodeWithSettings aAction) { m_aFormAction.setAction (aAction); return thisAsT (); } @Nullable public final IMimeType getFormEncType () { return m_aFormEncType; } @Nonnull public final IMPLTYPE setFormEncType (@Nullable final IMimeType aFormEncType) { m_aFormEncType = aFormEncType; return thisAsT (); } @Nullable public final EHCFormMethod getFormMethod () { return m_eFormMethod; } @Nonnull public final IMPLTYPE setFormMethod (@Nullable final EHCFormMethod eFormMethod) { m_eFormMethod = eFormMethod; return thisAsT (); } public final boolean isFormNoValidate () { return m_bFormNoValidate; } @Nonnull public final IMPLTYPE setFormNoValidate (final boolean bFormNoValidate) { m_bFormNoValidate = bFormNoValidate; return thisAsT (); } @Nullable public final HC_Target getFormTarget () { return m_aFormTarget; } @Nonnull public final IMPLTYPE setFormTarget (@Nullable final HC_Target aFormTarget) { m_aFormTarget = aFormTarget; return thisAsT (); } public final int getHeight () { return m_nHeight; } @Nonnull public final IMPLTYPE setHeight (final int nHeight) { m_nHeight = nHeight; return thisAsT (); } @Nullable public final String getList () { return m_sList; } @Nonnull public final IMPLTYPE setList (@Nullable final String sList) { m_sList = sList; return thisAsT (); } @Nullable public final String getMaxValue () { return m_sMaxValue; } @Nonnull public final IMPLTYPE setMaxValue (@Nullable final String sMaxValue) { m_sMaxValue = sMaxValue; return thisAsT (); } public final int getMaxLength () { return m_nMaxLength; } @Nonnull public final IMPLTYPE setMaxLength (final int nMaxLength) { m_nMaxLength = nMaxLength; return thisAsT (); } @Nullable public final String getMinValue () { return m_sMinValue; } @Nonnull public final IMPLTYPE setMinValue (@Nullable final String sMinValue) { m_sMinValue = sMinValue; return thisAsT (); } public final int getMinLength () { return m_nMinLength; } @Nonnull public final IMPLTYPE setMinLength (final int nMinLength) { m_nMinLength = nMinLength; return thisAsT (); } public final boolean isMultiple () { return m_bMultiple; } @Nonnull public final IMPLTYPE setMultiple (final boolean bMultiple) { m_bMultiple = bMultiple; return thisAsT (); } @Nullable public final String getPattern () { return m_sPattern; } @Nonnull public final IMPLTYPE setPattern (@Nullable final String sPattern) { m_sPattern = sPattern; return thisAsT (); } @Nullable public final String getPlaceholder () { return m_sPlaceholder; } @Nonnull public final IMPLTYPE setPlaceholder (@Nullable final String sPlaceholder) { m_sPlaceholder = sPlaceholder; return thisAsT (); } public final int getSize () { return m_nSize; } @Nonnull public final IMPLTYPE setSize (final int nSize) { m_nSize = nSize; return thisAsT (); } @Nullable public final ISimpleURL getSrc () { return m_aSrc; } @Nonnull public final IMPLTYPE setSrc (@Nullable final ISimpleURL aSrc) { m_aSrc = aSrc; return thisAsT (); } @Nullable public final String getStep () { return m_sStep; } @Nonnull public final IMPLTYPE setStep (@Nullable final String sStep) { m_sStep = sStep; return thisAsT (); } /** * @return The field value, maybe <code>null</code> */ @Nullable public final String getValue () { return m_sValue; } @Nonnull public final IMPLTYPE setValue (@Nullable final String sValue) { m_sValue = sValue; return thisAsT (); } public final int getWidth () { return m_nWidth; } @Nonnull public final IMPLTYPE setWidth (final int nWidth) { m_nWidth = nWidth; return thisAsT (); } @Override public String getPlainText () { return StringHelper.getNotNull (getValue ()); } @Override @OverridingMethodsMustInvokeSuper protected void fillMicroElement (final IMicroElement aElement, final IHCConversionSettingsToNode aConversionSettings) { super.fillMicroElement (aElement, aConversionSettings); if (m_eType != null) aElement.setAttribute (CHTMLAttributes.TYPE, m_eType); if (StringHelper.hasText (m_sAccept)) aElement.setAttribute (CHTMLAttributes.ACCEPT, m_sAccept); if (StringHelper.hasText (m_sAlt)) aElement.setAttribute (CHTMLAttributes.ALT, m_sAlt); if (m_eAutoComplete.isDefined ()) aElement.setAttribute (CHTMLAttributes.AUTOCOMPLETE, m_eAutoComplete.isTrue () ? CHTMLAttributeValues.ON : CHTMLAttributeValues.OFF); if (m_bChecked) aElement.setAttribute (CHTMLAttributes.CHECKED, CHTMLAttributeValues.CHECKED); if (StringHelper.hasText (m_sDirName)) aElement.setAttribute (CHTMLAttributes.DIRNAME, m_sDirName); if (StringHelper.hasText (m_sForm)) aElement.setAttribute (CHTMLAttributes.FORM, m_sForm); m_aFormAction.applyProperties (CHTMLAttributes.FORMACTION, aElement, aConversionSettings.getJSWriterSettings (), aConversionSettings.getCharset ()); if (m_aFormEncType != null) aElement.setAttribute (CHTMLAttributes.FORMENCTYPE, m_aFormEncType.getAsString ()); if (m_eFormMethod != null) aElement.setAttribute (CHTMLAttributes.FORMMETHOD, m_eFormMethod); if (m_bFormNoValidate) aElement.setAttribute (CHTMLAttributes.FORMNOVALIDATE, CHTMLAttributeValues.FORMNOVALIDATE); if (m_aFormTarget != null) aElement.setAttribute (CHTMLAttributes.FORMTARGET, m_aFormTarget); if (m_nHeight > 0) aElement.setAttribute (CHTMLAttributes.HEIGHT, m_nHeight); if (StringHelper.hasText (m_sList)) aElement.setAttribute (CHTMLAttributes.LIST, m_sList); if (StringHelper.hasText (m_sMaxValue)) aElement.setAttribute (CHTMLAttributes.MAX, m_sMaxValue); if (m_nMaxLength > 0) aElement.setAttribute (CHTMLAttributes.MAXLENGTH, m_nMaxLength); if (StringHelper.hasText (m_sMinValue)) aElement.setAttribute (CHTMLAttributes.MIN, m_sMinValue); if (m_nMinLength > 0) aElement.setAttribute (CHTMLAttributes.MINLENGTH, m_nMinLength); if (m_bMultiple) aElement.setAttribute (CHTMLAttributes.MULTIPLE, CHTMLAttributeValues.MULTIPLE); if (StringHelper.hasText (m_sPattern)) aElement.setAttribute (CHTMLAttributes.PATTERN, m_sPattern); if (StringHelper.hasText (m_sPlaceholder)) aElement.setAttribute (CHTMLAttributes.PLACEHOLDER, m_sPlaceholder); if (m_nSize > 0) aElement.setAttribute (CHTMLAttributes.SIZE, m_nSize); if (m_aSrc != null) aElement.setAttribute (CHTMLAttributes.SRC, m_aSrc.getAsStringWithEncodedParameters (aConversionSettings.getCharset ())); if (StringHelper.hasText (m_sStep)) aElement.setAttribute (CHTMLAttributes.STEP, m_sStep); if (m_sValue != null) aElement.setAttribute (CHTMLAttributes.VALUE, m_sValue); if (m_nWidth > 0) aElement.setAttribute (CHTMLAttributes.WIDTH, m_nWidth); } @Override public String toString () { return ToStringGenerator.getDerived (super.toString ()) .appendIfNotNull ("type", m_eType) .appendIfNotNull ("accept", m_sAccept) .appendIfNotNull ("alt", m_sAlt) .append ("autoComplete", m_eAutoComplete) .append ("checked", m_bChecked) .appendIfNotNull ("dirname", m_sDirName) .appendIfNotNull ("form", m_sForm) .append ("formaction", m_aFormAction) .appendIfNotNull ("formenctype", m_aFormEncType) .appendIfNotNull ("formmethod", m_eFormMethod) .append ("formnovalidate", m_bFormNoValidate) .appendIfNotNull ("formtarget", m_aFormTarget) .append ("height", m_nHeight) .appendIfNotNull ("list", m_sList) .appendIfNotNull ("maxValue", m_sMaxValue) .append ("maxLength", m_nMaxLength) .appendIfNotNull ("minValue", m_sMinValue) .append ("minLength", m_nMinLength) .append ("multiple", m_bMultiple) .appendIfNotNull ("pattern", m_sPattern) .appendIfNotNull ("placeholder", m_sPlaceholder) .append ("size", m_nSize) .appendIfNotNull ("src", m_aSrc) .appendIfNotNull ("step", m_sStep) .appendIfNotNull ("value", m_sValue) .append ("width", m_nWidth) .getToString (); } }
May set a null type
ph-oton-html/src/main/java/com/helger/html/hc/html/forms/AbstractHCInput.java
May set a null type
Java
apache-2.0
542c0f5cd8581f2a1d9debb0a2b01f47199e9814
0
MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim
package verification.platu.stategraph; import java.io.*; import java.util.*; import lpn.parser.LhpnFile; import lpn.parser.Transition; import verification.platu.TimingAnalysis.TimingState; import verification.platu.common.PlatuObj; import verification.platu.lpn.DualHashMap; import verification.platu.lpn.LPN; import verification.platu.lpn.LpnTranList; import verification.platu.lpn.VarSet; /** * State * @author Administrator */ public class State extends PlatuObj { public static int[] counts = new int[15]; protected int[] marking; protected int[] vector; protected boolean[] tranVector; // indicator vector to record whether each transition is enabled or not. private int hashVal = 0; private LhpnFile lpn = null; private int index; private boolean localEnabledOnly; protected boolean failure = false; // The TimingState that extends this state with a zone. Null if untimed. protected TimingState timeExtension; @Override public String toString() { // String ret=Arrays.toString(marking)+""+ // Arrays.toString(vector); // return "["+ret.replace("[", "{").replace("]", "}")+"]"; return this.print(); } public State(final LhpnFile lpn, int[] new_marking, int[] new_vector, boolean[] new_isTranEnabled) { this.lpn = lpn; this.marking = new_marking; this.vector = new_vector; this.tranVector = new_isTranEnabled; if (marking == null || vector == null || tranVector == null) { new NullPointerException().printStackTrace(); } //Arrays.sort(this.marking); this.index = 0; localEnabledOnly = false; counts[0]++; } public State(State other) { if (other == null) { new NullPointerException().printStackTrace(); } this.lpn = other.lpn; this.marking = new int[other.marking.length]; System.arraycopy(other.marking, 0, this.marking, 0, other.marking.length); this.vector = new int[other.vector.length]; System.arraycopy(other.vector, 0, this.vector, 0, other.vector.length); this.tranVector = new boolean[other.tranVector.length]; System.arraycopy(other.tranVector, 0, this.tranVector, 0, other.tranVector.length); // this.hashVal = other.hashVal; this.hashVal = 0; this.index = other.index; this.localEnabledOnly = other.localEnabledOnly; counts[0]++; } // TODO: (temp) Two Unused constructors, State() and State(Object otherState) // public State() { // this.marking = new int[0]; // this.vector = new int[0];//EMPTY_VECTOR.clone(); // this.hashVal = 0; // this.index = 0; // localEnabledOnly = false; // counts[0]++; // } //static PrintStream out = System.out; // public State(Object otherState) { // State other = (State) otherState; // if (other == null) { // new NullPointerException().printStackTrace(); // } // // this.lpnModel = other.lpnModel; // this.marking = new int[other.marking.length]; // System.arraycopy(other.marking, 0, this.marking, 0, other.marking.length); // // // this.vector = other.getVector().clone(); // this.vector = new int[other.vector.length]; // System.arraycopy(other.vector, 0, this.vector, 0, other.vector.length); // // this.hashVal = other.hashVal; // this.index = other.index; // this.localEnabledOnly = other.localEnabledOnly; // counts[0]++; // } public void setLpn(final LhpnFile thisLpn) { this.lpn = thisLpn; } public LhpnFile getLpn() { return this.lpn; } public void setLabel(String lbl) { } public String getLabel() { return null; } /** * This method returns the boolean array representing the status (enabled/disabled) of each transition in an LPN. * @return */ public boolean[] getTranVector() { return tranVector; } public void setIndex(int newIndex) { this.index = newIndex; } public int getIndex() { return this.index; } public boolean hasNonLocalEnabled() { return this.localEnabledOnly; } public void hasNonLocalEnabled(boolean nonLocalEnabled) { this.localEnabledOnly = nonLocalEnabled; } public boolean isFailure() { return false;// getType() != getType().NORMAL || getType() != // getType().TERMINAL; } public static long tSum = 0; @Override public State clone() { counts[6]++; State s = new State(this); return s; } public String print() { DualHashMap<String, Integer> VarIndexMap = this.lpn.getVarIndexMap(); String message = "Marking: ["; for (int i : marking) { message += i + ","; } message += "]\n" + "Vector: ["; for (int i = 0; i < vector.length; i++) { message += VarIndexMap.getKey(i) + "=>" + vector[i]+", "; } message += "]\n" + "Transition Vector: ["; for (int i = 0; i < tranVector.length; i++) { message += tranVector[i] + ","; } message += "]\n"; return message; } @Override public int hashCode() { if(hashVal == 0){ final int prime = 31; int result = 1; result = prime * result + ((lpn == null) ? 0 : lpn.getLabel().hashCode()); result = prime * result + Arrays.hashCode(marking); result = prime * result + Arrays.hashCode(vector); result = prime * result + Arrays.hashCode(tranVector); hashVal = result; } return hashVal; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; State other = (State) obj; if (lpn == null) { if (other.lpn != null) return false; } else if (!lpn.equals(other.lpn)) return false; if (!Arrays.equals(marking, other.marking)) return false; if (!Arrays.equals(vector, other.vector)) return false; if (!Arrays.equals(tranVector, other.tranVector)) return false; return true; } public void print(DualHashMap<String, Integer> VarIndexMap) { System.out.print("Marking: ["); for (int i : marking) { System.out.print(i + ","); } System.out.println("]"); System.out.print("Vector: ["); for (int i = 0; i < vector.length; i++) { System.out.print(VarIndexMap.getKey(i) + "=>" + vector[i]+", "); } System.out.println("]"); System.out.print("Transition vector: ["); for (boolean bool : tranVector) { System.out.print(bool + ","); } System.out.println("]"); } /** * @return the marking */ public int[] getMarking() { return marking; } public void setMarking(int[] newMarking) { marking = newMarking; } /** * @return the vector */ public int[] getVector() { // new Exception("StateVector getVector(): "+s).printStackTrace(); return vector; } public HashMap<String, Integer> getOutVector(VarSet outputs, DualHashMap<String, Integer> VarIndexMap) { HashMap<String, Integer> outVec = new HashMap<String, Integer>(); for(int i = 0; i < vector.length; i++) { String var = VarIndexMap.getKey(i); if(outputs.contains(var) == true) outVec.put(var, vector[i]); } return outVec; } public State getLocalState() { //VarSet lpnOutputs = this.lpnModel.getOutputs(); //VarSet lpnInternals = this.lpnModel.getInternals(); Set<String> lpnOutputs = this.lpn.getAllOutputs().keySet(); Set<String> lpnInternals = this.lpn.getAllInternals().keySet(); DualHashMap<String,Integer> varIndexMap = this.lpn.getVarIndexMap(); int[] outVec = new int[this.vector.length]; /* * Create a copy of the vector of mState such that the values of inputs are set to 0 * and the values for outputs/internal variables remain the same. */ for(int i = 0; i < this.vector.length; i++) { String curVar = varIndexMap.getKey(i); if(lpnOutputs.contains(curVar) ==true || lpnInternals.contains(curVar)==true) outVec[i] = this.vector[i]; else outVec[i] = 0; } // TODO: (??) Need to create outTranVector as well? return new State(this.lpn, this.marking, outVec, this.tranVector); } /** * @return the enabledSet */ public int[] getEnabledSet() { return null;// enabledSet; } public LpnTranList getEnabledTransitions() { LpnTranList enabledTrans = new LpnTranList(); for (int i=0; i<tranVector.length; i++) { if (tranVector[i]) { enabledTrans.add(this.lpn.getTransition(i)); } } return enabledTrans; } public String getEnabledSetString() { String ret = ""; // for (int i : enabledSet) { // ret += i + ", "; // } return ret; } /** * Return a new state if the newVector leads to a new state from this state; otherwise return null. * @param newVector * @param VarIndexMap * @return */ public State update(StateGraph SG,HashMap<String, Integer> newVector, DualHashMap<String, Integer> VarIndexMap) { int[] newStateVector = new int[this.vector.length]; boolean newState = false; for(int index = 0; index < vector.length; index++) { String var = VarIndexMap.getKey(index); int this_val = this.vector[index]; Integer newVal = newVector.get(var); if(newVal != null) { if(this_val != newVal) { newState = true; newStateVector[index] = newVal; } else newStateVector[index] = this.vector[index]; } else newStateVector[index] = this.vector[index]; } boolean[] newEnabledTranVector = SG.updateEnabledTranVector(this.getTranVector(), this.marking, newStateVector, null); if(newState == true) return new State(this.lpn, this.marking, newStateVector, newEnabledTranVector); return null; } /** * Return a new state if the newVector leads to a new state from this state; otherwise return null. * States considered here include a vector indicating enabled/disabled state of each transition. * @param newVector * @param VarIndexMap * @return */ public State update(HashMap<String, Integer> newVector, DualHashMap<String, Integer> VarIndexMap, boolean[] newTranVector) { int[] newStateVector = new int[this.vector.length]; boolean newState = false; for(int index = 0; index < vector.length; index++) { String var = VarIndexMap.getKey(index); int this_val = this.vector[index]; Integer newVal = newVector.get(var); if(newVal != null) { if(this_val != newVal) { newState = true; newStateVector[index] = newVal; } else newStateVector[index] = this.vector[index]; } else newStateVector[index] = this.vector[index]; } if (!this.tranVector.equals(newTranVector)) newState = true; if(newState == true) return new State(this.lpn, this.marking, newStateVector, newTranVector); return null; } static public void printUsageStats() { System.out.printf("%-20s %11s\n", "State", counts[0]); System.out.printf("\t%-20s %11s\n", "State", counts[10]); // System.out.printf("\t%-20s %11s\n", "State", counts[11]); // System.out.printf("\t%-20s %11s\n", "merge", counts[1]); System.out.printf("\t%-20s %11s\n", "update", counts[2]); // System.out.printf("\t%-20s %11s\n", "compose", counts[3]); System.out.printf("\t%-20s %11s\n", "equals", counts[4]); // System.out.printf("\t%-20s %11s\n", "conjunction", counts[5]); System.out.printf("\t%-20s %11s\n", "clone", counts[6]); System.out.printf("\t%-20s %11s\n", "hashCode", counts[7]); // System.out.printf("\t%-20s %11s\n", "resembles", counts[8]); // System.out.printf("\t%-20s %11s\n", "digest", counts[9]); } //TODO: (original) try database serialization public File serialize(String filename) throws FileNotFoundException, IOException { File f = new File(filename); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f)); os.writeObject(this); os.close(); return f; } public static State deserialize(String filename) throws FileNotFoundException, IOException, ClassNotFoundException { File f = new File(filename); ObjectInputStream os = new ObjectInputStream(new FileInputStream(f)); State zone = (State) os.readObject(); os.close(); return zone; } public static State deserialize(File f) throws FileNotFoundException, IOException, ClassNotFoundException { ObjectInputStream os = new ObjectInputStream(new FileInputStream(f)); State zone = (State) os.readObject(); os.close(); return zone; } public boolean failure(){ return this.failure; } public void setFailure(){ this.failure = true; } public void print(LhpnFile lpn) { System.out.print("Marking: ["); // for (int i : marking) { // System.out.print(i + ","); // } for (int i=0; i < marking.length; i++) { System.out.print(lpn.getPlaceList().clone()[i] + "=" + marking[i] + ", "); } System.out.println("]"); System.out.print("Vector: ["); for (int i = 0; i < vector.length; i++) { System.out.print(lpn.getVarIndexMap().getKey(i) + "=>" + vector[i]+", "); } System.out.println("]"); System.out.print("Transition vector: ["); for (boolean bool : tranVector) { System.out.print(bool + ","); } System.out.println("]"); } /** * Getter for the TimingState that extends this state. * @return * The TimingState that extends this state if it has been set. Null, otherwise. */ public TimingState getTimeExtension(){ return timeExtension; } /** * Setter for the TimingState that extends this state. * @param s * The TimingState that exteds this state. */ public void setTimeExtension(TimingState s){ timeExtension = s; } }
gui/src/verification/platu/stategraph/State.java
package verification.platu.stategraph; import java.io.*; import java.util.*; import lpn.parser.LhpnFile; import lpn.parser.Transition; import verification.platu.common.PlatuObj; import verification.platu.lpn.DualHashMap; import verification.platu.lpn.LPN; import verification.platu.lpn.LpnTranList; import verification.platu.lpn.VarSet; /** * State * @author Administrator */ public class State extends PlatuObj { public static int[] counts = new int[15]; protected int[] marking; protected int[] vector; protected boolean[] tranVector; // indicator vector to record whether each transition is enabled or not. private int hashVal = 0; private LhpnFile lpn = null; private int index; private boolean localEnabledOnly; protected boolean failure = false; @Override public String toString() { // String ret=Arrays.toString(marking)+""+ // Arrays.toString(vector); // return "["+ret.replace("[", "{").replace("]", "}")+"]"; return this.print(); } public State(final LhpnFile lpn, int[] new_marking, int[] new_vector, boolean[] new_isTranEnabled) { this.lpn = lpn; this.marking = new_marking; this.vector = new_vector; this.tranVector = new_isTranEnabled; if (marking == null || vector == null || tranVector == null) { new NullPointerException().printStackTrace(); } //Arrays.sort(this.marking); this.index = 0; localEnabledOnly = false; counts[0]++; } public State(State other) { if (other == null) { new NullPointerException().printStackTrace(); } this.lpn = other.lpn; this.marking = new int[other.marking.length]; System.arraycopy(other.marking, 0, this.marking, 0, other.marking.length); this.vector = new int[other.vector.length]; System.arraycopy(other.vector, 0, this.vector, 0, other.vector.length); this.tranVector = new boolean[other.tranVector.length]; System.arraycopy(other.tranVector, 0, this.tranVector, 0, other.tranVector.length); // this.hashVal = other.hashVal; this.hashVal = 0; this.index = other.index; this.localEnabledOnly = other.localEnabledOnly; counts[0]++; } // TODO: (temp) Two Unused constructors, State() and State(Object otherState) // public State() { // this.marking = new int[0]; // this.vector = new int[0];//EMPTY_VECTOR.clone(); // this.hashVal = 0; // this.index = 0; // localEnabledOnly = false; // counts[0]++; // } //static PrintStream out = System.out; // public State(Object otherState) { // State other = (State) otherState; // if (other == null) { // new NullPointerException().printStackTrace(); // } // // this.lpnModel = other.lpnModel; // this.marking = new int[other.marking.length]; // System.arraycopy(other.marking, 0, this.marking, 0, other.marking.length); // // // this.vector = other.getVector().clone(); // this.vector = new int[other.vector.length]; // System.arraycopy(other.vector, 0, this.vector, 0, other.vector.length); // // this.hashVal = other.hashVal; // this.index = other.index; // this.localEnabledOnly = other.localEnabledOnly; // counts[0]++; // } public void setLpn(final LhpnFile thisLpn) { this.lpn = thisLpn; } public LhpnFile getLpn() { return this.lpn; } public void setLabel(String lbl) { } public String getLabel() { return null; } /** * This method returns the boolean array representing the status (enabled/disabled) of each transition in an LPN. * @return */ public boolean[] getTranVector() { return tranVector; } public void setIndex(int newIndex) { this.index = newIndex; } public int getIndex() { return this.index; } public boolean hasNonLocalEnabled() { return this.localEnabledOnly; } public void hasNonLocalEnabled(boolean nonLocalEnabled) { this.localEnabledOnly = nonLocalEnabled; } public boolean isFailure() { return false;// getType() != getType().NORMAL || getType() != // getType().TERMINAL; } public static long tSum = 0; @Override public State clone() { counts[6]++; State s = new State(this); return s; } public String print() { DualHashMap<String, Integer> VarIndexMap = this.lpn.getVarIndexMap(); String message = "Marking: ["; for (int i : marking) { message += i + ","; } message += "]\n" + "Vector: ["; for (int i = 0; i < vector.length; i++) { message += VarIndexMap.getKey(i) + "=>" + vector[i]+", "; } message += "]\n" + "Transition Vector: ["; for (int i = 0; i < tranVector.length; i++) { message += tranVector[i] + ","; } message += "]\n"; return message; } @Override public int hashCode() { if(hashVal == 0){ final int prime = 31; int result = 1; result = prime * result + ((lpn == null) ? 0 : lpn.getLabel().hashCode()); result = prime * result + Arrays.hashCode(marking); result = prime * result + Arrays.hashCode(vector); result = prime * result + Arrays.hashCode(tranVector); hashVal = result; } return hashVal; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; State other = (State) obj; if (lpn == null) { if (other.lpn != null) return false; } else if (!lpn.equals(other.lpn)) return false; if (!Arrays.equals(marking, other.marking)) return false; if (!Arrays.equals(vector, other.vector)) return false; if (!Arrays.equals(tranVector, other.tranVector)) return false; return true; } public void print(DualHashMap<String, Integer> VarIndexMap) { System.out.print("Marking: ["); for (int i : marking) { System.out.print(i + ","); } System.out.println("]"); System.out.print("Vector: ["); for (int i = 0; i < vector.length; i++) { System.out.print(VarIndexMap.getKey(i) + "=>" + vector[i]+", "); } System.out.println("]"); System.out.print("Transition vector: ["); for (boolean bool : tranVector) { System.out.print(bool + ","); } System.out.println("]"); } /** * @return the marking */ public int[] getMarking() { return marking; } public void setMarking(int[] newMarking) { marking = newMarking; } /** * @return the vector */ public int[] getVector() { // new Exception("StateVector getVector(): "+s).printStackTrace(); return vector; } public HashMap<String, Integer> getOutVector(VarSet outputs, DualHashMap<String, Integer> VarIndexMap) { HashMap<String, Integer> outVec = new HashMap<String, Integer>(); for(int i = 0; i < vector.length; i++) { String var = VarIndexMap.getKey(i); if(outputs.contains(var) == true) outVec.put(var, vector[i]); } return outVec; } public State getLocalState() { //VarSet lpnOutputs = this.lpnModel.getOutputs(); //VarSet lpnInternals = this.lpnModel.getInternals(); Set<String> lpnOutputs = this.lpn.getAllOutputs().keySet(); Set<String> lpnInternals = this.lpn.getAllInternals().keySet(); DualHashMap<String,Integer> varIndexMap = this.lpn.getVarIndexMap(); int[] outVec = new int[this.vector.length]; /* * Create a copy of the vector of mState such that the values of inputs are set to 0 * and the values for outputs/internal variables remain the same. */ for(int i = 0; i < this.vector.length; i++) { String curVar = varIndexMap.getKey(i); if(lpnOutputs.contains(curVar) ==true || lpnInternals.contains(curVar)==true) outVec[i] = this.vector[i]; else outVec[i] = 0; } // TODO: (??) Need to create outTranVector as well? return new State(this.lpn, this.marking, outVec, this.tranVector); } /** * @return the enabledSet */ public int[] getEnabledSet() { return null;// enabledSet; } public LpnTranList getEnabledTransitions() { LpnTranList enabledTrans = new LpnTranList(); for (int i=0; i<tranVector.length; i++) { if (tranVector[i]) { enabledTrans.add(this.lpn.getTransition(i)); } } return enabledTrans; } public String getEnabledSetString() { String ret = ""; // for (int i : enabledSet) { // ret += i + ", "; // } return ret; } /** * Return a new state if the newVector leads to a new state from this state; otherwise return null. * @param newVector * @param VarIndexMap * @return */ public State update(StateGraph SG,HashMap<String, Integer> newVector, DualHashMap<String, Integer> VarIndexMap) { int[] newStateVector = new int[this.vector.length]; boolean newState = false; for(int index = 0; index < vector.length; index++) { String var = VarIndexMap.getKey(index); int this_val = this.vector[index]; Integer newVal = newVector.get(var); if(newVal != null) { if(this_val != newVal) { newState = true; newStateVector[index] = newVal; } else newStateVector[index] = this.vector[index]; } else newStateVector[index] = this.vector[index]; } boolean[] newEnabledTranVector = SG.updateEnabledTranVector(this.getTranVector(), this.marking, newStateVector, null); if(newState == true) return new State(this.lpn, this.marking, newStateVector, newEnabledTranVector); return null; } /** * Return a new state if the newVector leads to a new state from this state; otherwise return null. * States considered here include a vector indicating enabled/disabled state of each transition. * @param newVector * @param VarIndexMap * @return */ public State update(HashMap<String, Integer> newVector, DualHashMap<String, Integer> VarIndexMap, boolean[] newTranVector) { int[] newStateVector = new int[this.vector.length]; boolean newState = false; for(int index = 0; index < vector.length; index++) { String var = VarIndexMap.getKey(index); int this_val = this.vector[index]; Integer newVal = newVector.get(var); if(newVal != null) { if(this_val != newVal) { newState = true; newStateVector[index] = newVal; } else newStateVector[index] = this.vector[index]; } else newStateVector[index] = this.vector[index]; } if (!this.tranVector.equals(newTranVector)) newState = true; if(newState == true) return new State(this.lpn, this.marking, newStateVector, newTranVector); return null; } static public void printUsageStats() { System.out.printf("%-20s %11s\n", "State", counts[0]); System.out.printf("\t%-20s %11s\n", "State", counts[10]); // System.out.printf("\t%-20s %11s\n", "State", counts[11]); // System.out.printf("\t%-20s %11s\n", "merge", counts[1]); System.out.printf("\t%-20s %11s\n", "update", counts[2]); // System.out.printf("\t%-20s %11s\n", "compose", counts[3]); System.out.printf("\t%-20s %11s\n", "equals", counts[4]); // System.out.printf("\t%-20s %11s\n", "conjunction", counts[5]); System.out.printf("\t%-20s %11s\n", "clone", counts[6]); System.out.printf("\t%-20s %11s\n", "hashCode", counts[7]); // System.out.printf("\t%-20s %11s\n", "resembles", counts[8]); // System.out.printf("\t%-20s %11s\n", "digest", counts[9]); } //TODO: (original) try database serialization public File serialize(String filename) throws FileNotFoundException, IOException { File f = new File(filename); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f)); os.writeObject(this); os.close(); return f; } public static State deserialize(String filename) throws FileNotFoundException, IOException, ClassNotFoundException { File f = new File(filename); ObjectInputStream os = new ObjectInputStream(new FileInputStream(f)); State zone = (State) os.readObject(); os.close(); return zone; } public static State deserialize(File f) throws FileNotFoundException, IOException, ClassNotFoundException { ObjectInputStream os = new ObjectInputStream(new FileInputStream(f)); State zone = (State) os.readObject(); os.close(); return zone; } public boolean failure(){ return this.failure; } public void setFailure(){ this.failure = true; } public void print(LhpnFile lpn) { System.out.print("Marking: ["); // for (int i : marking) { // System.out.print(i + ","); // } for (int i=0; i < marking.length; i++) { System.out.print(lpn.getPlaceList().clone()[i] + "=" + marking[i] + ", "); } System.out.println("]"); System.out.print("Vector: ["); for (int i = 0; i < vector.length; i++) { System.out.print(lpn.getVarIndexMap().getKey(i) + "=>" + vector[i]+", "); } System.out.println("]"); System.out.print("Transition vector: ["); for (boolean bool : tranVector) { System.out.print(bool + ","); } System.out.println("]"); } }
Added 'TimingState timeExtension' member variable with a getter and setter.
gui/src/verification/platu/stategraph/State.java
Added 'TimingState timeExtension' member variable with a getter and setter.
Java
apache-2.0
da293606eaafeafd9e28b62b4403e1a44af9aca9
0
gregwhitaker/async-showdown
package com.github.gregwhitaker.asyncshowdown; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import java.util.Arrays; import java.util.Deque; import java.util.LinkedList; import java.util.Map; import java.util.Random; import java.util.concurrent.Callable; public class HelloHandler implements HttpHandler { private static Random RANDOM = new Random(System.currentTimeMillis()); /** * Asynchronously waits a random random number of milliseconds, within the specified minimum and maximum, before * returning a 200 HTTP response with the body containing the string "Hello World!" * * @param exchange undertow exchange * @throws Exception */ @Override public void handleRequest(HttpServerExchange exchange) throws Exception { // Dispatches the current request to a worker thread if it is on one of Undertow's main IO threads if (exchange.isInIoThread()) { exchange.dispatch(this); return; } final Map<String, Deque<String>> queryParams = exchange.getQueryParameters(); Long minSleep = Long.parseLong(queryParams.getOrDefault("minSleepMs", new LinkedList<>(Arrays.asList("500"))).getFirst()); Long maxSleep = Long.parseLong(queryParams.getOrDefault("maxSleepMs", new LinkedList<>(Arrays.asList("500"))).getFirst()); HelloGenerator helloGenerator = new HelloGenerator(minSleep, maxSleep); String message = helloGenerator.call(); exchange.setStatusCode(200); exchange.getResponseSender().send(message); exchange.endExchange(); } /** * Task that sleeps for a random amount of time, within a configurable interval, and then returns the string "Hello World!". */ class HelloGenerator implements Callable<String> { private final long duration; public HelloGenerator(final long minSleep, final long maxSleep) { this.duration = minSleep + (long)(RANDOM.nextDouble() * (maxSleep - minSleep)); } @Override public String call() throws Exception { Thread.sleep(duration); return "Hello World!"; } } }
undertow/src/main/java/com/github/gregwhitaker/asyncshowdown/HelloHandler.java
package com.github.gregwhitaker.asyncshowdown; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import java.util.Arrays; import java.util.Deque; import java.util.LinkedList; import java.util.Map; import java.util.Random; import java.util.concurrent.Callable; public class HelloHandler implements HttpHandler { private static Random RANDOM = new Random(System.currentTimeMillis()); /** * Asynchronously waits a random random number of milliseconds, within the specified minimum and maximum, before * returning a 200 HTTP response with the body containing the string "Hello World!" * * @param exchange undertow exchange * @throws Exception */ @Override public void handleRequest(HttpServerExchange exchange) throws Exception { // Dispatches the current request to a worker thread if it is on one of Undertow's main IO threads if (exchange.isInIoThread()) { exchange.dispatch(this); return; } final Map<String, Deque<String>> queryParams = exchange.getQueryParameters(); Long minSleep = Long.parseLong(queryParams.getOrDefault("minSleepMs", new LinkedList<>(Arrays.asList("500"))).getFirst()); Long maxSleep = Long.parseLong(queryParams.getOrDefault("maxSleepMs", new LinkedList<>(Arrays.asList("500"))).getFirst()); HelloGenerator helloGenerator = new HelloGenerator(minSleep, maxSleep); String message = helloGenerator.call(); exchange.setStatusCode(200); exchange.getResponseSender().send(message); } /** * Task that sleeps for a random amount of time, within a configurable interval, and then returns the string "Hello World!". */ class HelloGenerator implements Callable<String> { private final long duration; public HelloGenerator(final long minSleep, final long maxSleep) { this.duration = minSleep + (long)(RANDOM.nextDouble() * (maxSleep - minSleep)); } @Override public String call() throws Exception { Thread.sleep(duration); return "Hello World!"; } } }
Added call to end exchange
undertow/src/main/java/com/github/gregwhitaker/asyncshowdown/HelloHandler.java
Added call to end exchange
Java
apache-2.0
be63fa8a20803614c13e83ced1d2ca88b7bdd661
0
ruspl-afed/dbeaver,liuyuanyuan/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,ruspl-afed/dbeaver
/* * Copyright (C) 2013 Denis Forveille [email protected] * Copyright (C) 2010-2013 Serge Rieder [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jkiss.dbeaver.ext.db2.model; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ext.db2.DB2Constants; import org.jkiss.dbeaver.ext.db2.model.dict.DB2IndexPageSplit; import org.jkiss.dbeaver.ext.db2.model.dict.DB2IndexType; import org.jkiss.dbeaver.ext.db2.model.dict.DB2UniqueRule; import org.jkiss.dbeaver.ext.db2.model.dict.DB2YesNo; import org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer; import org.jkiss.dbeaver.model.impl.DBSObjectCache; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.impl.jdbc.struct.JDBCTableIndex; import org.jkiss.dbeaver.model.meta.Property; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.rdb.DBSIndexType; import org.jkiss.utils.CommonUtils; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.Collection; /** * DB2 Index * * @author Denis Forveille */ public class DB2Index extends JDBCTableIndex<DB2Schema, DB2Table> { private static final Log LOG = LogFactory.getLog(DB2Index.class); // Structure private DB2UniqueRule uniqueRule; private Integer colCount; private Integer uniqueColCount; private DB2IndexType db2IndexType; private Integer pctFree; private Integer indexId; private Integer minPctUsed; private Boolean reverseScans; private Integer tablespaceId; private DB2IndexPageSplit pageSplit; private Boolean compression; private String remarks; // Derived private Timestamp createTime; private Boolean madeUnique; // Stats private Timestamp statsTime; private Long fullKeycard; private Long firstKeycard; private Long first2Keycard; private Long first3Keycard; private Long first4Keycard; private Integer clusterRatio; // ----------------- // Constructors // ----------------- public DB2Index(DBRProgressMonitor monitor, DB2Schema schema, DB2Table table, ResultSet dbResult) { super(schema, table, JDBCUtils.safeGetStringTrimmed(dbResult, "INDNAME"), null, true); this.uniqueRule = CommonUtils.valueOf(DB2UniqueRule.class, JDBCUtils.safeGetString(dbResult, "UNIQUERULE")); this.colCount = JDBCUtils.safeGetInteger(dbResult, "COLCOUNT"); this.uniqueColCount = JDBCUtils.safeGetInteger(dbResult, "UNIQUE_COLCOUNT"); this.pctFree = JDBCUtils.safeGetInteger(dbResult, "PCTFREE"); this.indexId = JDBCUtils.safeGetInteger(dbResult, "IID"); this.minPctUsed = JDBCUtils.safeGetInteger(dbResult, "MINPCTUSED"); this.reverseScans = JDBCUtils.safeGetBoolean(dbResult, "REVERSE_SCANS", DB2YesNo.Y.name()); this.tablespaceId = JDBCUtils.safeGetInteger(dbResult, "TBSPACEID"); this.compression = JDBCUtils.safeGetBoolean(dbResult, "COMPRESSION", DB2YesNo.Y.name()); this.pageSplit = CommonUtils.valueOf(DB2IndexPageSplit.class, JDBCUtils.safeGetStringTrimmed(dbResult, "PAGESPLIT")); this.remarks = JDBCUtils.safeGetString(dbResult, "REMARKS"); this.createTime = JDBCUtils.safeGetTimestamp(dbResult, "CREATE_TIME"); this.madeUnique = JDBCUtils.safeGetBoolean(dbResult, "MADE_UNIQUE"); this.statsTime = JDBCUtils.safeGetTimestamp(dbResult, "STATS_TIME"); this.fullKeycard = JDBCUtils.safeGetLong(dbResult, "FULLKEYCARD"); this.firstKeycard = JDBCUtils.safeGetLong(dbResult, "FIRSTKEYCARD"); this.first2Keycard = JDBCUtils.safeGetLong(dbResult, "FIRST2KEYCARD"); this.first3Keycard = JDBCUtils.safeGetLong(dbResult, "FIRST3KEYCARD"); this.first4Keycard = JDBCUtils.safeGetLong(dbResult, "FIRST4KEYCARD"); this.clusterRatio = JDBCUtils.safeGetInteger(dbResult, "CLUSTERRATIO"); // DF: Could have been done in constructor. More "readable" to do it here this.db2IndexType = CommonUtils.valueOf(DB2IndexType.class, JDBCUtils.safeGetStringTrimmed(dbResult, "INDEXTYPE")); this.indexType = db2IndexType.getDBSIndexType(); } public DB2Index(DB2Table db2Table, String indexName, DBSIndexType indexType) { super(db2Table.getSchema(), db2Table, indexName, indexType, false); } // ----------------- // Business Contract // ----------------- @Override public boolean isUnique() { return (uniqueRule.isUnique()); } @Override public DB2DataSource getDataSource() { return getTable().getDataSource(); } @Override public String getFullQualifiedName() { return getContainer().getName() + "." + getName(); } // ----------------- // Columns // ----------------- @Override public Collection<DB2IndexColumn> getAttributeReferences(DBRProgressMonitor monitor) { try { return getContainer().getIndexCache().getChildren(monitor, getContainer(), this); } catch (DBException e) { // TODO DF: Don't know what to do with this exception except log it LOG.error("DBException swallowed during getAttributeReferences", e); return null; } } public void addColumn(DB2IndexColumn ixColumn) { DBSObjectCache<DB2Index, DB2IndexColumn> cols = getContainer().getIndexCache().getChildrenCache(this); cols.cacheObject(ixColumn); } // ----------------- // Properties // ----------------- @Override @Property(viewable = true, editable = true, valueTransformer = DBObjectNameCaseTransformer.class, order = 1) public String getName() { return super.getName(); } @Property(viewable = true, editable = false, order = 2) public DB2Schema getIndSchema() { return getContainer(); } @Property(viewable = true, editable = false, order = 5) public DB2UniqueRule getUniqueRule() { return uniqueRule; } @Property(viewable = false, editable = false, order = 10) public Boolean getMadeUnique() { return madeUnique; } @Property(viewable = false, editable = false, order = 11) public Integer getColCount() { return colCount; } @Property(viewable = false, editable = false, order = 12) public Integer getUniqueColCount() { return uniqueColCount; } @Property(viewable = false, editable = false, order = 70) public Integer getIndexId() { return indexId; } @Property(viewable = false, editable = false, order = 71) public Integer getTablespaceId() { return tablespaceId; } @Property(viewable = false, order = 20, editable = false) public Integer getPctFree() { return pctFree; } @Property(viewable = false, order = 21, editable = false) public Integer getMinPctUsed() { return minPctUsed; } @Property(viewable = false, order = 22, editable = false) public Boolean getReverseScans() { return reverseScans; } @Property(viewable = false, order = 23, editable = false) public DB2IndexPageSplit getPageSplit() { return pageSplit; } @Property(viewable = false, order = 24, editable = false) public Boolean getCompression() { return compression; } @Override @Property(viewable = false, editable = false) public String getDescription() { return remarks; } @Property(viewable = false, editable = false, category = DB2Constants.CAT_DATETIME) public Timestamp getCreateTime() { return createTime; } @Property(viewable = false, editable = false, order = 30, category = DB2Constants.CAT_STATS) public Timestamp getStatsTime() { return statsTime; } @Property(viewable = true, editable = false, order = 31, category = DB2Constants.CAT_STATS) public Long getFullKeycard() { return fullKeycard; } @Property(viewable = false, editable = false, order = 32, category = DB2Constants.CAT_STATS) public Long getFirstKeycard() { return firstKeycard; } @Property(viewable = false, editable = false, order = 33, category = DB2Constants.CAT_STATS) public Long getFirst2Keycard() { return first2Keycard; } @Property(viewable = false, editable = false, order = 34, category = DB2Constants.CAT_STATS) public Long getFirst3Keycard() { return first3Keycard; } @Property(viewable = false, editable = false, order = 35, category = DB2Constants.CAT_STATS) public Long getFirst4Keycard() { return first4Keycard; } @Property(viewable = false, editable = false, order = 36, category = DB2Constants.CAT_STATS) public Integer getClusterRatio() { return clusterRatio; } }
plugins/org.jkiss.dbeaver.db2/src/org/jkiss/dbeaver/ext/db2/model/DB2Index.java
/* * Copyright (C) 2013 Denis Forveille [email protected] * Copyright (C) 2010-2013 Serge Rieder [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jkiss.dbeaver.ext.db2.model; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ext.db2.DB2Constants; import org.jkiss.dbeaver.ext.db2.model.dict.DB2IndexPageSplit; import org.jkiss.dbeaver.ext.db2.model.dict.DB2IndexType; import org.jkiss.dbeaver.ext.db2.model.dict.DB2UniqueRule; import org.jkiss.dbeaver.ext.db2.model.dict.DB2YesNo; import org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer; import org.jkiss.dbeaver.model.impl.DBSObjectCache; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.impl.jdbc.struct.JDBCTableIndex; import org.jkiss.dbeaver.model.meta.Property; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.rdb.DBSIndexType; import org.jkiss.utils.CommonUtils; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.Collection; /** * DB2 Index * * @author Denis Forveille */ public class DB2Index extends JDBCTableIndex<DB2Schema, DB2Table> { private static final Log LOG = LogFactory.getLog(DB2Index.class); // Structure private DB2UniqueRule uniqueRule; private Integer colCount; private Integer uniqueColCount; private DB2IndexType db2IndexType; private Integer pctFree; private Integer indexId; private Integer minPctUsed; private Boolean reverseScans; private Integer tablespaceId; private DB2IndexPageSplit pageSplit; private Boolean compression; private String remarks; // Derived private Timestamp createTime; private Boolean madeUnique; // Stats private Timestamp statsTime; private Long fullKeycard; private Long firstKeycard; private Long first2Keycard; private Long first3Keycard; private Long first4Keycard; private Integer clusterRatio; // ----------------- // Constructors // ----------------- public DB2Index(DBRProgressMonitor monitor, DB2Schema schema, DB2Table table, ResultSet dbResult) { super(schema, table, JDBCUtils.safeGetStringTrimmed(dbResult, "INDNAME"), null, true); this.uniqueRule = CommonUtils.valueOf(DB2UniqueRule.class, JDBCUtils.safeGetString(dbResult, "UNIQUERULE")); this.colCount = JDBCUtils.safeGetInteger(dbResult, "COLCOUNT"); this.uniqueColCount = JDBCUtils.safeGetInteger(dbResult, "UNIQUE_COLCOUNT"); this.pctFree = JDBCUtils.safeGetInteger(dbResult, "PCTFREE"); this.indexId = JDBCUtils.safeGetInteger(dbResult, "IID"); this.minPctUsed = JDBCUtils.safeGetInteger(dbResult, "MINPCTUSED"); this.reverseScans = JDBCUtils.safeGetBoolean(dbResult, "REVERSE_SCANS", DB2YesNo.Y.name()); this.tablespaceId = JDBCUtils.safeGetInteger(dbResult, "TBSPACEID"); this.compression = JDBCUtils.safeGetBoolean(dbResult, "COMPRESSION", DB2YesNo.Y.name()); this.pageSplit = CommonUtils.valueOf(DB2IndexPageSplit.class, JDBCUtils.safeGetStringTrimmed(dbResult, "PAGESPLIT")); this.remarks = JDBCUtils.safeGetString(dbResult, "REMARKS"); this.createTime = JDBCUtils.safeGetTimestamp(dbResult, "CREATE_TIME"); this.madeUnique = JDBCUtils.safeGetBoolean(dbResult, "MADE_UNIQUE"); this.statsTime = JDBCUtils.safeGetTimestamp(dbResult, "STATS_TIME"); this.fullKeycard = JDBCUtils.safeGetLong(dbResult, "FULLKEYCARD"); this.firstKeycard = JDBCUtils.safeGetLong(dbResult, "FIRSTKEYCARD"); this.first2Keycard = JDBCUtils.safeGetLong(dbResult, "FIRST2KEYCARD"); this.first3Keycard = JDBCUtils.safeGetLong(dbResult, "FIRST3KEYCARD"); this.first4Keycard = JDBCUtils.safeGetLong(dbResult, "FIRST4KEYCARD"); this.clusterRatio = JDBCUtils.safeGetInteger(dbResult, "CLUSTERRATIO"); // DF: Could have been done in constructor. More "readable" to do it here this.db2IndexType = CommonUtils.valueOf(DB2IndexType.class, JDBCUtils.safeGetStringTrimmed(dbResult, "INDEXTYPE")); this.indexType = db2IndexType.getDBSIndexType(); } public DB2Index(DB2Table db2Table, String indexName, DBSIndexType indexType) { super(db2Table.getSchema(), db2Table, indexName, indexType, false); } // ----------------- // Business Contract // ----------------- @Override public boolean isUnique() { return (uniqueRule.isUnique()); } @Override public DB2DataSource getDataSource() { return getTable().getDataSource(); } @Override public String getFullQualifiedName() { return getContainer().getName() + "." + getName(); } // ----------------- // Columns // ----------------- @Override public Collection<DB2IndexColumn> getAttributeReferences(DBRProgressMonitor monitor) { try { return getContainer().getIndexCache().getChildren(monitor, getContainer(), this); } catch (DBException e) { // TODO DF: Don't know what to do with this exception except log it LOG.error("DBException swallowed during getAttributeReferences", e); return null; } } public void addColumn(DB2IndexColumn ixColumn) { DBSObjectCache<DB2Index, DB2IndexColumn> cols = getContainer().getIndexCache().getChildrenCache(this); cols.cacheObject(ixColumn); } // ----------------- // Properties // ----------------- @Override @Property(viewable = true, editable = true, valueTransformer = DBObjectNameCaseTransformer.class, order = 1) public String getName() { return super.getName(); } @Property(viewable = true, editable = false, order = 2) public DB2Schema getIndSchema() { return getContainer(); } @Property(viewable = true, editable = false, order = 5) public DB2UniqueRule getUniqueRule() { return uniqueRule; } @Property(viewable = false, editable = false, order = 10) public Boolean getMadeUnique() { return madeUnique; } @Property(viewable = false, editable = false, order = 11) public Integer getColCount() { return colCount; } @Property(viewable = false, editable = false, order = 12) public Integer getUniqueColCount() { return uniqueColCount; } @Property(viewable = false, editable = false, order = 70) public Integer getIndexId() { return indexId; } @Property(viewable = false, editable = false, order = 71) public Integer getTablespaceId() { return tablespaceId; } @Property(viewable = true, order = 20, editable = false) public Integer getPctFree() { return pctFree; } @Property(viewable = true, order = 21, editable = false) public Integer getMinPctUsed() { return minPctUsed; } @Property(viewable = true, order = 22, editable = false) public Boolean getReverseScans() { return reverseScans; } @Property(viewable = false, order = 23, editable = false) public DB2IndexPageSplit getPageSplit() { return pageSplit; } @Property(viewable = false, order = 24, editable = false) public Boolean getCompression() { return compression; } @Override @Property(viewable = false, editable = false) public String getDescription() { return remarks; } @Property(viewable = false, editable = false, category = DB2Constants.CAT_DATETIME) public Timestamp getCreateTime() { return createTime; } @Property(viewable = false, editable = false, order = 30, category = DB2Constants.CAT_STATS) public Timestamp getStatsTime() { return statsTime; } @Property(viewable = false, editable = false, order = 31, category = DB2Constants.CAT_STATS) public Long getFullKeycard() { return fullKeycard; } @Property(viewable = false, editable = false, order = 32, category = DB2Constants.CAT_STATS) public Long getFirstKeycard() { return firstKeycard; } @Property(viewable = false, editable = false, order = 33, category = DB2Constants.CAT_STATS) public Long getFirst2Keycard() { return first2Keycard; } @Property(viewable = false, editable = false, order = 34, category = DB2Constants.CAT_STATS) public Long getFirst3Keycard() { return first3Keycard; } @Property(viewable = false, editable = false, order = 35, category = DB2Constants.CAT_STATS) public Long getFirst4Keycard() { return first4Keycard; } @Property(viewable = false, editable = false, order = 36, category = DB2Constants.CAT_STATS) public Integer getClusterRatio() { return clusterRatio; } }
DB2: Various display improvements
plugins/org.jkiss.dbeaver.db2/src/org/jkiss/dbeaver/ext/db2/model/DB2Index.java
DB2: Various display improvements
Java
apache-2.0
f66c44f76a4030e3fd252f037bd7f49fd42cdc2b
0
efsavage/ajah
/* * Copyright 2011-2014 Eric F. Savage, [email protected] * * 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.ajah.geo.iso; import com.ajah.geo.Continent; import com.ajah.geo.Country; import com.ajah.util.IdentifiableEnum; import lombok.Getter; /** * This is the * <a href="http://www.iso.org/iso/english_country_names_and_code_elements" >ISO * -3166</a> implementation of the Country interface, which should be enough for * most uses of Country. * * It is true that this does duplicate data that already exists in Java's Locale * mechanisms, but I don't like the idea of a country being added or removed in * a future version breaking my application. * * @author Eric F. Savage <[email protected]> * */ public enum ISOCountry implements Country, IdentifiableEnum<String> { /** Andorra */ AD("ad", "AND", "Andorra", Continent.EUROPE), /** United Arab Emirates */ AE("ae", "ARE", "United Arab Emirates", Continent.ASIA), /** Afghanistan */ AF("af", "AFG", "Afghanistan", Continent.ASIA), /** Antigua and Barbuda */ AG("ag", "ATG", "Antigua and Barbuda", Continent.NORTH_AMERICA), /** Anguilla */ AI("ai", "AIA", "Anguilla", Continent.NORTH_AMERICA), /** Albania */ AL("al", "ALB", "Albania", Continent.EUROPE), /** Armenia */ AM("am", "ARM", "Armenia", Continent.ASIA), /** Netherlands Antilles */ AN("an", "ANT", "Netherlands Antilles", Continent.SOUTH_AMERICA), /** Angola */ AO("ao", "AGO", "Angola", Continent.AFRICA), /** Antarctica */ AQ("aq", "ATA", "Antarctica", Continent.ANTARTICTICA), /** Argentina */ AR("ar", "ARG", "Argentina", Continent.SOUTH_AMERICA), /** American Samoa */ AS("as", "ASM", "American Samoa", Continent.OCEANIA), /** Austria */ AT("at", "AUT", "Austria", Continent.EUROPE), /** Australia */ AU("au", "AUS", "Australia", Continent.OCEANIA), /** Aruba */ AW("aw", "ABW", "Aruba", Continent.SOUTH_AMERICA), /** &Aring;land Islands */ AX("ax", "ALA", "Åland Islands", Continent.EUROPE), /** Azerbaijan */ AZ("az", "AZE", "Azerbaijan", Continent.ASIA), /** Bosnia and Herzegovina */ BA("ba", "BIH", "Bosnia and Herzegovina", Continent.EUROPE), /** Barbados */ BB("bb", "BRB", "Barbados", Continent.NORTH_AMERICA), /** Bangladesh */ BD("bd", "BGD", "Bangladesh", Continent.ASIA), /** Belgium */ BE("be", "BEL", "Belgium", Continent.EUROPE), /** Burkina Faso */ BF("bf", "BFA", "Burkina Faso", Continent.AFRICA), /** Bulgaria */ BG("bg", "BGR", "Bulgaria", Continent.EUROPE), /** Bahrain */ BH("bh", "BHR", "Bahrain", Continent.ASIA), /** Burundi */ BI("bi", "BDI", "Burundi", Continent.AFRICA), /** Benin */ BJ("bj", "BEN", "Benin", Continent.AFRICA), /** Saint Barth&eacute;lemy */ BL("bl", "BLM", "Saint Barthélemy", Continent.NORTH_AMERICA), /** Bermuda */ BM("bm", "BMU", "Bermuda", Continent.NORTH_AMERICA), /** Brunei */ BN("bn", "BRN", "Brunei", Continent.ASIA), /** Bolivia */ BO("bo", "BOL", "Bolivia", Continent.SOUTH_AMERICA), /** Brazil */ BR("br", "BRA", "Brazil", Continent.SOUTH_AMERICA), /** Bahamas */ BS("bs", "BHS", "Bahamas", Continent.NORTH_AMERICA), /** Bhutan */ BT("bt", "BTN", "Bhutan", Continent.ASIA), /** Bouvet Island */ BV("bv", "BVT", "Bouvet Island", Continent.ANTARTICTICA), /** Botswana */ BW("bw", "BWA", "Botswana", Continent.AFRICA), /** Belarus */ BY("by", "BLR", "Belarus", Continent.EUROPE), /** Belize */ BZ("bz", "BLZ", "Belize", Continent.NORTH_AMERICA), /** Canada */ CA("ca", "CAN", "Canada", Continent.NORTH_AMERICA), /** Cocos Islands */ CC("cc", "CCK", "Cocos Islands", Continent.ASIA), /** The Democratic Republic Of Congo */ CD("cd", "COD", "The Democratic Republic Of Congo", Continent.AFRICA), /** Central African Republic */ CF("cf", "CAF", "Central African Republic", Continent.AFRICA), /** Congo */ CG("cg", "COG", "Congo", Continent.AFRICA), /** Switzerland */ CH("ch", "CHE", "Switzerland", Continent.EUROPE), /** C&ocirc;te d'Ivoire */ CI("ci", "CIV", "Côte d'Ivoire", Continent.AFRICA), /** Cook Islands */ CK("ck", "COK", "Cook Islands", Continent.OCEANIA), /** Chile */ CL("cl", "CHL", "Chile", Continent.SOUTH_AMERICA), /** Cameroon */ CM("cm", "CMR", "Cameroon", Continent.AFRICA), /** China */ CN("cn", "CHN", "China", Continent.ASIA), /** Colombia */ CO("co", "COL", "Colombia", Continent.SOUTH_AMERICA), /** Costa Rica */ CR("cr", "CRI", "Costa Rica", Continent.NORTH_AMERICA), /** Serbia and Montenegro */ CS("cs", "SCG", "Serbia and Montenegro", Continent.EUROPE), /** Cuba */ CU("cu", "CUB", "Cuba", Continent.NORTH_AMERICA), /** Cape Verde */ CV("cv", "CPV", "Cape Verde", Continent.AFRICA), /** Christmas Island */ CX("cx", "CXR", "Christmas Island", Continent.ASIA), /** Cyprus */ CY("cy", "CYP", "Cyprus", Continent.EUROPE), /** Czech Republic */ CZ("cz", "CZE", "Czech Republic", Continent.EUROPE), /** Germany */ DE("de", "DEU", "Germany", Continent.EUROPE), /** Djibouti */ DJ("dj", "DJI", "Djibouti", Continent.AFRICA), /** Denmark */ DK("dk", "DNK", "Denmark", Continent.EUROPE), /** Dominica */ DM("dm", "DMA", "Dominica", Continent.NORTH_AMERICA), /** Dominican Republic */ DO("do", "DOM", "Dominican Republic", Continent.NORTH_AMERICA), /** Algeria */ DZ("dz", "DZA", "Algeria", Continent.AFRICA), /** Ecuador */ EC("ec", "ECU", "Ecuador", Continent.SOUTH_AMERICA), /** Estonia */ EE("ee", "EST", "Estonia", Continent.EUROPE), /** Egypt */ EG("eg", "EGY", "Egypt", Continent.AFRICA), /** Western Sahara */ EH("eh", "ESH", "Western Sahara", Continent.AFRICA), /** Eritrea */ ER("er", "ERI", "Eritrea", Continent.AFRICA), /** Spain */ ES("es", "ESP", "Spain", Continent.EUROPE), /** Ethiopia */ ET("et", "ETH", "Ethiopia", Continent.AFRICA), /** * European Union * * <strong>NOT STANDARD</strong> */ EU("eu", "EUR", "European Union", Continent.EUROPE), /** Finland */ FI("fi", "FIN", "Finland", Continent.EUROPE), /** Fiji */ FJ("fj", "FJI", "Fiji", Continent.OCEANIA), /** Falkland Islands */ FK("fk", "FLK", "Falkland Islands", Continent.SOUTH_AMERICA), /** Micronesia */ FM("fm", "FSM", "Micronesia", Continent.OCEANIA), /** Faroe Islands */ FO("fo", "FRO", "Faroe Islands", Continent.EUROPE), /** France */ FR("fr", "FRA", "France", Continent.EUROPE), /** Gabon */ GA("ga", "GAB", "Gabon", Continent.AFRICA), /** United Kingdom */ GB("gb", "GBR", "United Kingdom", Continent.EUROPE), /** Channel Islands (subdivision of United Kingdom) */ GB_CHA("gb-cha", "GB-CHA", "Channel Islands", GB), /** England (subdivision of United Kingdom) */ GB_ENG("gb-eng", "GB-ENG", "England", GB), /** Isle of Man (subdivision of United Kingdom) */ GB_IOM("gb-iom", "GB-IOM", "Isle of Man", GB), /** Northern Ireland (subdivision of United Kingdom) */ GB_NIR("gb-nir", "GB-NIR", "Northern Ireland", GB), /** Scotland (subdivision of United Kingdom) */ GB_SCT("gb-sct", "GB-SCT", "Scotland", GB), /** Wales (subdivision of United Kingdom) */ GB_WLS("gb-wls", "GB-WLS", "Wales", GB), /** Grenada */ GD("gd", "GRD", "Grenada", Continent.NORTH_AMERICA), /** Georgia */ GE("ge", "GEO", "Georgia", Continent.ASIA), /** French Guiana */ GF("gf", "GUF", "French Guiana", Continent.SOUTH_AMERICA), /** Guernsey */ GG("gg", "GGY", "Guernsey", Continent.EUROPE), /** Ghana */ GH("gh", "GHA", "Ghana", Continent.AFRICA), /** Gibraltar */ GI("gi", "GIB", "Gibraltar", Continent.EUROPE), /** Greenland */ GL("gl", "GRL", "Greenland", Continent.NORTH_AMERICA), /** Gambia */ GM("gm", "GMB", "Gambia", Continent.AFRICA), /** Guinea */ GN("gn", "GIN", "Guinea", Continent.AFRICA), /** Guadeloupe */ GP("gp", "GLP", "Guadeloupe", Continent.NORTH_AMERICA), /** Equatorial Guinea */ GQ("gq", "GNQ", "Equatorial Guinea", Continent.AFRICA), /** Greece */ GR("gr", "GRC", "Greece", Continent.EUROPE), /** South Georgia And The South Sandwich Islands */ GS("gs", "SGS", "South Georgia And The South Sandwich Islands", Continent.ANTARTICTICA), /** Guatemala */ GT("gt", "GTM", "Guatemala", Continent.NORTH_AMERICA), /** Guam */ GU("gu", "GUM", "Guam", Continent.OCEANIA), /** Guinea-Bissau */ GW("gw", "GNB", "Guinea-Bissau", Continent.AFRICA), /** Guyana */ GY("gy", "GUY", "Guyana", Continent.SOUTH_AMERICA), /** Hong Kong */ HK("hk", "HKG", "Hong Kong", Continent.ASIA), /** Heard Island And McDonald Islands */ HM("hm", "HMD", "Heard Island And McDonald Islands", Continent.ANTARTICTICA), /** Honduras */ HN("hn", "HND", "Honduras", Continent.NORTH_AMERICA), /** Croatia */ HR("hr", "HRV", "Croatia", Continent.EUROPE), /** Haiti */ HT("ht", "HTI", "Haiti", Continent.NORTH_AMERICA), /** Hungary */ HU("hu", "HUN", "Hungary", Continent.EUROPE), /** Indonesia */ ID("id", "IDN", "Indonesia", Continent.ASIA), /** Ireland */ IE("ie", "IRL", "Ireland", Continent.EUROPE), /** Israel */ IL("il", "ISR", "Israel", Continent.ASIA), /** Isle Of Man */ IM("im", "IMN", "Isle Of Man", Continent.EUROPE), /** India */ IN("in", "IND", "India", Continent.ASIA), /** British Indian Ocean Territory */ IO("io", "IOT", "British Indian Ocean Territory", Continent.ASIA), /** Iraq */ IQ("iq", "IRQ", "Iraq", Continent.ASIA), /** Iran */ IR("ir", "IRN", "Iran", Continent.ASIA), /** Iceland */ IS("is", "ISL", "Iceland", Continent.EUROPE), /** Italy */ IT("it", "ITA", "Italy", Continent.EUROPE), /** Jersey */ JE("je", "JEY", "Jersey", Continent.EUROPE), /** Jamaica */ JM("jm", "JAM", "Jamaica", Continent.NORTH_AMERICA), /** Jordan */ JO("jo", "JOR", "Jordan", Continent.ASIA), /** Japan */ JP("jp", "JPN", "Japan", Continent.ASIA), /** Kenya */ KE("ke", "KEN", "Kenya", Continent.AFRICA), /** Kyrgyzstan */ KG("kg", "KGZ", "Kyrgyzstan", Continent.ASIA), /** Cambodia */ KH("kh", "KHM", "Cambodia", Continent.ASIA), /** Kiribati */ KI("ki", "KIR", "Kiribati", Continent.OCEANIA), /** Comoros */ KM("km", "COM", "Comoros", Continent.AFRICA), /** Saint Kitts And Nevis */ KN("kn", "KNA", "Saint Kitts And Nevis", Continent.NORTH_AMERICA), /** North Korea */ KP("kp", "PRK", "North Korea", Continent.ASIA), /** South Korea */ KR("kr", "KOR", "South Korea", Continent.ASIA), /** Kuwait */ KW("kw", "KWT", "Kuwait", Continent.ASIA), /** Cayman Islands */ KY("ky", "CYM", "Cayman Islands", Continent.NORTH_AMERICA), /** Kazakhstan */ KZ("kz", "KAZ", "Kazakhstan", Continent.ASIA), /** Laos */ LA("la", "LAO", "Laos", Continent.ASIA), /** Lebanon */ LB("lb", "LBN", "Lebanon", Continent.ASIA), /** Saint Lucia */ LC("lc", "LCA", "Saint Lucia", Continent.NORTH_AMERICA), /** Liechtenstein */ LI("li", "LIE", "Liechtenstein", Continent.EUROPE), /** Sri Lanka */ LK("lk", "LKA", "Sri Lanka", Continent.ASIA), /** Liberia */ LR("lr", "LBR", "Liberia", Continent.AFRICA), /** Lesotho */ LS("ls", "LSO", "Lesotho", Continent.AFRICA), /** Lithuania */ LT("lt", "LTU", "Lithuania", Continent.EUROPE), /** Luxembourg */ LU("lu", "LUX", "Luxembourg", Continent.EUROPE), /** Latvia */ LV("lv", "LVA", "Latvia", Continent.EUROPE), /** Libya */ LY("ly", "LBY", "Libya", Continent.AFRICA), /** Morocco */ MA("ma", "MAR", "Morocco", Continent.AFRICA), /** Monaco */ MC("mc", "MCO", "Monaco", Continent.EUROPE), /** Moldova */ MD("md", "MDA", "Moldova", Continent.EUROPE), /** Montenegro */ ME("me", "MNE", "Montenegro", Continent.EUROPE), /** Saint Martin */ MF("mf", "MAF", "Saint Martin", Continent.NORTH_AMERICA), /** Madagascar */ MG("mg", "MDG", "Madagascar", Continent.AFRICA), /** Marshall Islands */ MH("mh", "MHL", "Marshall Islands", Continent.OCEANIA), /** Macedonia */ MK("mk", "MKD", "Macedonia", Continent.EUROPE), /** Mali */ ML("ml", "MLI", "Mali", Continent.AFRICA), /** Myanmar */ MM("mm", "MMR", "Myanmar", Continent.ASIA), /** Mongolia */ MN("mn", "MNG", "Mongolia", Continent.ASIA), /** Macao */ MO("mo", "MAC", "Macao", Continent.ASIA), /** Northern Mariana Islands */ MP("mp", "MNP", "Northern Mariana Islands", Continent.OCEANIA), /** Martinique */ MQ("mq", "MTQ", "Martinique", Continent.NORTH_AMERICA), /** Mauritania */ MR("mr", "MRT", "Mauritania", Continent.AFRICA), /** Montserrat */ MS("ms", "MSR", "Montserrat", Continent.NORTH_AMERICA), /** Malta */ MT("mt", "MLT", "Malta", Continent.EUROPE), /** Mauritius */ MU("mu", "MUS", "Mauritius", Continent.AFRICA), /** Maldives */ MV("mv", "MDV", "Maldives", Continent.ASIA), /** Malawi */ MW("mw", "MWI", "Malawi", Continent.AFRICA), /** Mexico */ MX("mx", "MEX", "Mexico", Continent.NORTH_AMERICA), /** Malaysia */ MY("my", "MYS", "Malaysia", Continent.ASIA), /** Mozambique */ MZ("mz", "MOZ", "Mozambique", Continent.AFRICA), /** Namibia */ NA("na", "NAM", "Namibia", Continent.AFRICA), /** New Caledonia */ NC("nc", "NCL", "New Caledonia", Continent.OCEANIA), /** Niger */ NE("ne", "NER", "Niger", Continent.AFRICA), /** Norfolk Island */ NF("nf", "NFK", "Norfolk Island", Continent.OCEANIA), /** Nigeria */ NG("ng", "NGA", "Nigeria", Continent.AFRICA), /** Nicaragua */ NI("ni", "NIC", "Nicaragua", Continent.NORTH_AMERICA), /** Netherlands */ NL("nl", "NLD", "Netherlands", Continent.EUROPE), /** Norway */ NO("no", "NOR", "Norway", Continent.EUROPE), /** Nepal */ NP("np", "NPL", "Nepal", Continent.ASIA), /** Nauru */ NR("nr", "NRU", "Nauru", Continent.OCEANIA), /** Niue */ NU("nu", "NIU", "Niue", Continent.OCEANIA), /** New Zealand */ NZ("nz", "NZL", "New Zealand", Continent.OCEANIA), /** Oman */ OM("om", "OMN", "Oman", Continent.ASIA), /** Panama */ PA("pa", "PAN", "Panama", Continent.NORTH_AMERICA), /** Peru */ PE("pe", "PER", "Peru", Continent.SOUTH_AMERICA), /** French Polynesia */ PF("pf", "PYF", "French Polynesia", Continent.OCEANIA), /** Papua New Guinea */ PG("pg", "PNG", "Papua New Guinea", Continent.OCEANIA), /** Philippines */ PH("ph", "PHL", "Philippines", Continent.ASIA), /** Pakistan */ PK("pk", "PAK", "Pakistan", Continent.ASIA), /** Poland */ PL("pl", "POL", "Poland", Continent.EUROPE), /** Saint Pierre And Miquelon */ PM("pm", "SPM", "Saint Pierre And Miquelon", Continent.NORTH_AMERICA), /** Pitcairn */ PN("pn", "PCN", "Pitcairn", Continent.OCEANIA), /** Puerto Rico */ PR("pr", "PRI", "Puerto Rico", Continent.NORTH_AMERICA), /** Palestine */ PS("ps", "PSE", "Palestine", Continent.ASIA), /** Portugal */ PT("pt", "PRT", "Portugal", Continent.EUROPE), /** Palau */ PW("pw", "PLW", "Palau", Continent.OCEANIA), /** Paraguay */ PY("py", "PRY", "Paraguay", Continent.SOUTH_AMERICA), /** Qatar */ QA("qa", "QAT", "Qatar", Continent.ASIA), /** Reunion */ RE("re", "REU", "Reunion", Continent.AFRICA), /** Romania */ RO("ro", "ROU", "Romania", Continent.EUROPE), /** Serbia */ RS("rs", "SRB", "Serbia", Continent.EUROPE), /** Russia */ RU("ru", "RUS", "Russia", Continent.ASIA, "Russian Federation"), /** Rwanda */ RW("rw", "RWA", "Rwanda", Continent.AFRICA), /** Saudi Arabia */ SA("sa", "SAU", "Saudi Arabia", Continent.ASIA), /** Solomon Islands */ SB("sb", "SLB", "Solomon Islands", Continent.OCEANIA), /** Seychelles */ SC("sc", "SYC", "Seychelles", Continent.AFRICA), /** Sudan */ SD("sd", "SDN", "Sudan", Continent.AFRICA), /** Sweden */ SE("se", "SWE", "Sweden", Continent.EUROPE), /** Singapore */ SG("sg", "SGP", "Singapore", Continent.ASIA), /** Saint Helena */ SH("sh", "SHN", "Saint Helena", Continent.AFRICA), /** Slovenia */ SI("si", "SVN", "Slovenia", Continent.EUROPE), /** Svalbard And Jan Mayen */ SJ("sj", "SJM", "Svalbard And Jan Mayen", Continent.EUROPE), /** Slovakia */ SK("sk", "SVK", "Slovakia", Continent.EUROPE), /** Sierra Leone */ SL("sl", "SLE", "Sierra Leone", Continent.AFRICA), /** San Marino */ SM("sm", "SMR", "San Marino", Continent.EUROPE), /** Senegal */ SN("sn", "SEN", "Senegal", Continent.AFRICA), /** Somalia */ SO("so", "SOM", "Somalia", Continent.AFRICA), /** Suriname */ SR("sr", "SUR", "Suriname", Continent.SOUTH_AMERICA), /** Sao Tome And Principe */ ST("st", "STP", "Sao Tome And Principe", Continent.AFRICA), /** El Salvador */ SV("sv", "SLV", "El Salvador", Continent.NORTH_AMERICA), /** Syria */ SY("sy", "SYR", "Syria", Continent.ASIA), /** Swaziland */ SZ("sz", "SWZ", "Swaziland", Continent.AFRICA), /** Turks And Caicos Islands */ TC("tc", "TCA", "Turks And Caicos Islands", Continent.NORTH_AMERICA), /** Chad */ TD("td", "TCD", "Chad", Continent.AFRICA), /** French Southern Territories */ TF("tf", "ATF", "French Southern Territories", Continent.ANTARTICTICA), /** Togo */ TG("tg", "TGO", "Togo", Continent.AFRICA), /** Thailand */ TH("th", "THA", "Thailand", Continent.ASIA), /** Tajikistan */ TJ("tj", "TJK", "Tajikistan", Continent.ASIA), /** Tokelau */ TK("tk", "TKL", "Tokelau", Continent.OCEANIA), /** Timor-Leste */ TL("tl", "TLS", "Timor-Leste", Continent.ASIA), /** Turkmenistan */ TM("tm", "TKM", "Turkmenistan", Continent.ASIA), /** Tunisia */ TN("tn", "TUN", "Tunisia", Continent.AFRICA), /** Tonga */ TO("to", "TON", "Tonga", Continent.OCEANIA), /** Turkey */ TR("tr", "TUR", "Turkey", Continent.ASIA), /** Trinidad and Tobago */ TT("tt", "TTO", "Trinidad and Tobago", Continent.NORTH_AMERICA), /** Tuvalu */ TV("tv", "TUV", "Tuvalu", Continent.OCEANIA), /** Taiwan */ TW("tw", "TWN", "Taiwan", Continent.ASIA), /** Tanzania */ TZ("tz", "TZA", "Tanzania", Continent.AFRICA), /** Ukraine */ UA("ua", "UKR", "Ukraine", Continent.EUROPE), /** Uganda */ UG("ug", "UGA", "Uganda", Continent.AFRICA), /** United States Minor Outlying Islands */ UM("um", "UMI", "United States Minor Outlying Islands", Continent.NORTH_AMERICA), /** United States */ US("us", "USA", "United States", Continent.NORTH_AMERICA), /** Uruguay */ UY("uy", "URY", "Uruguay", Continent.SOUTH_AMERICA), /** Uzbekistan */ UZ("uz", "UZB", "Uzbekistan", Continent.ASIA), /** Vatican */ VA("va", "VAT", "Vatican", Continent.ASIA), /** Saint Vincent And The Grenadines */ VC("vc", "VCT", "Saint Vincent And The Grenadines", Continent.NORTH_AMERICA), /** Venezuela */ VE("ve", "VEN", "Venezuela", Continent.SOUTH_AMERICA), /** British Virgin Islands */ VG("vg", "VGB", "British Virgin Islands", Continent.NORTH_AMERICA), /** U.S. Virgin Islands */ VI("vi", "VIR", "U.S. Virgin Islands", Continent.NORTH_AMERICA), /** Vietnam */ VN("vn", "VNM", "Vietnam", Continent.ASIA, "Viet Nam", "Socialist Republic of Vietnam", "SRV"), /** Vanuatu */ VU("vu", "VUT", "Vanuatu", Continent.OCEANIA), /** Wallis And Futuna */ WF("wf", "WLF", "Wallis And Futuna", Continent.OCEANIA), /** Samoa */ WS("ws", "WSM", "Samoa", Continent.OCEANIA), /** Yemen */ YE("ye", "YEM", "Yemen", Continent.ASIA), /** Mayotte */ YT("yt", "MYT", "Mayotte", Continent.AFRICA), /** South Africa */ ZA("za", "ZAF", "South Africa", Continent.AFRICA), /** Zambia */ ZM("zm", "ZMB", "Zambia", Continent.AFRICA), /** Zimbabwe */ ZW("zw", "ZWE", "Zimbabwe", Continent.AFRICA); /** * Finds a PlayerType that matches the id on id, name, or name(). * * @param string * Value to match against id, name, or name() * @return Matching PlayerType, or null. */ public static ISOCountry get(final String string) { for (final ISOCountry country : values()) { if (country.getId().equals(string) || country.getCode().equals(string) || country.name().equals(string) || country.getName().equals(string)) { return country; } if (country.aliases != null) { for (String alias : country.aliases) { if (alias.equals(string)) { return country; } } } } return null; } private final String id; private final String abbr2; private final String abbr3; private final String name; private final Continent continent;; private final ISOCountry parent; @Getter private final String[] aliases; private ISOCountry(final String id, final String abbr3, final String name, final Continent continent, final String... aliases) { this.id = id; this.abbr2 = id.toUpperCase(); this.abbr3 = abbr3; this.name = name; this.parent = null; this.aliases = aliases; this.continent = continent; } private ISOCountry(final String id, final String abbr3, final String name, final ISOCountry parent) { this.id = id; this.abbr2 = id.toUpperCase(); this.abbr3 = abbr3; this.name = name; this.parent = parent; this.aliases = null; this.continent = parent.getContinent(); } /** * The public abbreviation of the country. Alias for * {@link ISOCountry#getAbbr2}. * * @see com.ajah.geo.iso.ISOCountry#getAbbr2() * * Example: The abbreviation of the United States would be "US". * * @return The public abbreviation of the country. Should never be null or * empty. */ @Override public String getAbbr() { return getAbbr2(); } /** * The ISO 2-letter code for this country. * * Example: The abbreviation of the United States would be "US". * * @return The ISO 2-letter code for the country. Should never be null or * empty. */ public String getAbbr2() { return this.abbr2; } /** * The ISO 3-letter code for this country. * * Example: The abbreviation of the United States would be "USA". * * @return The ISO 3-letter code for the country. Should never be null or * empty. */ public String getAbbr3() { return this.abbr3; } /** * @see com.ajah.util.IdentifiableEnum#getCode() */ @Override public String getCode() { return getAbbr3(); } /** * The lowercase version of the ISO 2-letter code for this country. * * Example: The ID of the United States would be "us". * * @return The lowercase version of the ISO 2-letter code for the country. * Should never be null or empty. */ @Override public String getId() { return this.id; } /** * The ISO "short" name of the country. * * @see com.ajah.geo.Country#getName() * @return the ISO Short name of the country. Should never be null or empty. */ @Override public String getName() { return this.name; } /** * Returns the parent of this country (making it a subdivision). * * @return the parent Country, if applicable, otherwise null. */ public ISOCountry getParent() { return this.parent; } /** * Returns the continent of this country. If a country is in more than one * continent, returns the one most strongly associated with it, * geographically. * * @return the continent the country is in. */ public Continent getContinent() { return this.continent; } @Override public void setId(final String id) { throw new UnsupportedOperationException(); } }
ajah-geo/src/main/java/com/ajah/geo/iso/ISOCountry.java
/* * Copyright 2011-2014 Eric F. Savage, [email protected] * * 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.ajah.geo.iso; import com.ajah.geo.Country; import com.ajah.util.IdentifiableEnum; import lombok.Getter; /** * This is the <a * href="http://www.iso.org/iso/english_country_names_and_code_elements" >ISO * -3166</a> implementation of the Country interface, which should be enough for * most uses of Country. * * It is true that this does duplicate data that already exists in Java's Locale * mechanisms, but I don't like the idea of a country being added or removed in * a future version breaking my application. * * @author Eric F. Savage <[email protected]> * */ public enum ISOCountry implements Country, IdentifiableEnum<String> { /** Andorra */ AD("ad", "AND", "Andorra"), /** United Arab Emirates */ AE("ae", "ARE", "United Arab Emirates"), /** Afghanistan */ AF("af", "AFG", "Afghanistan"), /** Antigua and Barbuda */ AG("ag", "ATG", "Antigua and Barbuda"), /** Anguilla */ AI("ai", "AIA", "Anguilla"), /** Albania */ AL("al", "ALB", "Albania"), /** Armenia */ AM("am", "ARM", "Armenia"), /** Netherlands Antilles */ AN("an", "ANT", "Netherlands Antilles"), /** Angola */ AO("ao", "AGO", "Angola"), /** Antarctica */ AQ("aq", "ATA", "Antarctica"), /** Argentina */ AR("ar", "ARG", "Argentina"), /** American Samoa */ AS("as", "ASM", "American Samoa"), /** Austria */ AT("at", "AUT", "Austria"), /** Australia */ AU("au", "AUS", "Australia"), /** Aruba */ AW("aw", "ABW", "Aruba"), /** &Aring;land Islands */ AX("ax", "ALA", "Åland Islands"), /** Azerbaijan */ AZ("az", "AZE", "Azerbaijan"), /** Bosnia and Herzegovina */ BA("ba", "BIH", "Bosnia and Herzegovina"), /** Barbados */ BB("bb", "BRB", "Barbados"), /** Bangladesh */ BD("bd", "BGD", "Bangladesh"), /** Belgium */ BE("be", "BEL", "Belgium"), /** Burkina Faso */ BF("bf", "BFA", "Burkina Faso"), /** Bulgaria */ BG("bg", "BGR", "Bulgaria"), /** Bahrain */ BH("bh", "BHR", "Bahrain"), /** Burundi */ BI("bi", "BDI", "Burundi"), /** Benin */ BJ("bj", "BEN", "Benin"), /** Saint Barth&eacute;lemy */ BL("bl", "BLM", "Saint Barthélemy"), /** Bermuda */ BM("bm", "BMU", "Bermuda"), /** Brunei */ BN("bn", "BRN", "Brunei"), /** Bolivia */ BO("bo", "BOL", "Bolivia"), /** Brazil */ BR("br", "BRA", "Brazil"), /** Bahamas */ BS("bs", "BHS", "Bahamas"), /** Bhutan */ BT("bt", "BTN", "Bhutan"), /** Bouvet Island */ BV("bv", "BVT", "Bouvet Island"), /** Botswana */ BW("bw", "BWA", "Botswana"), /** Belarus */ BY("by", "BLR", "Belarus"), /** Belize */ BZ("bz", "BLZ", "Belize"), /** Canada */ CA("ca", "CAN", "Canada"), /** Cocos Islands */ CC("cc", "CCK", "Cocos Islands"), /** The Democratic Republic Of Congo */ CD("cd", "COD", "The Democratic Republic Of Congo"), /** Central African Republic */ CF("cf", "CAF", "Central African Republic"), /** Congo */ CG("cg", "COG", "Congo"), /** Switzerland */ CH("ch", "CHE", "Switzerland"), /** C&ocirc;te d'Ivoire */ CI("ci", "CIV", "Côte d'Ivoire"), /** Cook Islands */ CK("ck", "COK", "Cook Islands"), /** Chile */ CL("cl", "CHL", "Chile"), /** Cameroon */ CM("cm", "CMR", "Cameroon"), /** China */ CN("cn", "CHN", "China"), /** Colombia */ CO("co", "COL", "Colombia"), /** Costa Rica */ CR("cr", "CRI", "Costa Rica"), /** Serbia and Montenegro */ CS("cs", "SCG", "Serbia and Montenegro"), /** Cuba */ CU("cu", "CUB", "Cuba"), /** Cape Verde */ CV("cv", "CPV", "Cape Verde"), /** Christmas Island */ CX("cx", "CXR", "Christmas Island"), /** Cyprus */ CY("cy", "CYP", "Cyprus"), /** Czech Republic */ CZ("cz", "CZE", "Czech Republic"), /** Germany */ DE("de", "DEU", "Germany"), /** Djibouti */ DJ("dj", "DJI", "Djibouti"), /** Denmark */ DK("dk", "DNK", "Denmark"), /** Dominica */ DM("dm", "DMA", "Dominica"), /** Dominican Republic */ DO("do", "DOM", "Dominican Republic"), /** Algeria */ DZ("dz", "DZA", "Algeria"), /** Ecuador */ EC("ec", "ECU", "Ecuador"), /** Estonia */ EE("ee", "EST", "Estonia"), /** Egypt */ EG("eg", "EGY", "Egypt"), /** Western Sahara */ EH("eh", "ESH", "Western Sahara"), /** Eritrea */ ER("er", "ERI", "Eritrea"), /** Spain */ ES("es", "ESP", "Spain"), /** Ethiopia */ ET("et", "ETH", "Ethiopia"), /** * European Union * * <strong>NOT STANDARD</strong> */ EU("eu", "EUR", "European Union"), /** Finland */ FI("fi", "FIN", "Finland"), /** Fiji */ FJ("fj", "FJI", "Fiji"), /** Falkland Islands */ FK("fk", "FLK", "Falkland Islands"), /** Micronesia */ FM("fm", "FSM", "Micronesia"), /** Faroe Islands */ FO("fo", "FRO", "Faroe Islands"), /** France */ FR("fr", "FRA", "France"), /** Gabon */ GA("ga", "GAB", "Gabon"), /** United Kingdom */ GB("gb", "GBR", "United Kingdom"), /** Channel Islands (subdivision of United Kingdom) */ GB_CHA("gb-cha", "GB-CHA", "Channel Islands", GB), /** England (subdivision of United Kingdom) */ GB_ENG("gb-eng", "GB-ENG", "England", GB), /** Isle of Man (subdivision of United Kingdom) */ GB_IOM("gb-iom", "GB-IOM", "Isle of Man", GB), /** Northern Ireland (subdivision of United Kingdom) */ GB_NIR("gb-nir", "GB-NIR", "Northern Ireland", GB), /** Scotland (subdivision of United Kingdom) */ GB_SCT("gb-sct", "GB-SCT", "Scotland", GB), /** Wales (subdivision of United Kingdom) */ GB_WLS("gb-wls", "GB-WLS", "Wales", GB), /** Grenada */ GD("gd", "GRD", "Grenada"), /** Georgia */ GE("ge", "GEO", "Georgia"), /** French Guiana */ GF("gf", "GUF", "French Guiana"), /** Guernsey */ GG("gg", "GGY", "Guernsey"), /** Ghana */ GH("gh", "GHA", "Ghana"), /** Gibraltar */ GI("gi", "GIB", "Gibraltar"), /** Greenland */ GL("gl", "GRL", "Greenland"), /** Gambia */ GM("gm", "GMB", "Gambia"), /** Guinea */ GN("gn", "GIN", "Guinea"), /** Guadeloupe */ GP("gp", "GLP", "Guadeloupe"), /** Equatorial Guinea */ GQ("gq", "GNQ", "Equatorial Guinea"), /** Greece */ GR("gr", "GRC", "Greece"), /** South Georgia And The South Sandwich Islands */ GS("gs", "SGS", "South Georgia And The South Sandwich Islands"), /** Guatemala */ GT("gt", "GTM", "Guatemala"), /** Guam */ GU("gu", "GUM", "Guam"), /** Guinea-Bissau */ GW("gw", "GNB", "Guinea-Bissau"), /** Guyana */ GY("gy", "GUY", "Guyana"), /** Hong Kong */ HK("hk", "HKG", "Hong Kong"), /** Heard Island And McDonald Islands */ HM("hm", "HMD", "Heard Island And McDonald Islands"), /** Honduras */ HN("hn", "HND", "Honduras"), /** Croatia */ HR("hr", "HRV", "Croatia"), /** Haiti */ HT("ht", "HTI", "Haiti"), /** Hungary */ HU("hu", "HUN", "Hungary"), /** Indonesia */ ID("id", "IDN", "Indonesia"), /** Ireland */ IE("ie", "IRL", "Ireland"), /** Israel */ IL("il", "ISR", "Israel"), /** Isle Of Man */ IM("im", "IMN", "Isle Of Man"), /** India */ IN("in", "IND", "India"), /** British Indian Ocean Territory */ IO("io", "IOT", "British Indian Ocean Territory"), /** Iraq */ IQ("iq", "IRQ", "Iraq"), /** Iran */ IR("ir", "IRN", "Iran"), /** Iceland */ IS("is", "ISL", "Iceland"), /** Italy */ IT("it", "ITA", "Italy"), /** Jersey */ JE("je", "JEY", "Jersey"), /** Jamaica */ JM("jm", "JAM", "Jamaica"), /** Jordan */ JO("jo", "JOR", "Jordan"), /** Japan */ JP("jp", "JPN", "Japan"), /** Kenya */ KE("ke", "KEN", "Kenya"), /** Kyrgyzstan */ KG("kg", "KGZ", "Kyrgyzstan"), /** Cambodia */ KH("kh", "KHM", "Cambodia"), /** Kiribati */ KI("ki", "KIR", "Kiribati"), /** Comoros */ KM("km", "COM", "Comoros"), /** Saint Kitts And Nevis */ KN("kn", "KNA", "Saint Kitts And Nevis"), /** North Korea */ KP("kp", "PRK", "North Korea"), /** South Korea */ KR("kr", "KOR", "South Korea"), /** Kuwait */ KW("kw", "KWT", "Kuwait"), /** Cayman Islands */ KY("ky", "CYM", "Cayman Islands"), /** Kazakhstan */ KZ("kz", "KAZ", "Kazakhstan"), /** Laos */ LA("la", "LAO", "Laos"), /** Lebanon */ LB("lb", "LBN", "Lebanon"), /** Saint Lucia */ LC("lc", "LCA", "Saint Lucia"), /** Liechtenstein */ LI("li", "LIE", "Liechtenstein"), /** Sri Lanka */ LK("lk", "LKA", "Sri Lanka"), /** Liberia */ LR("lr", "LBR", "Liberia"), /** Lesotho */ LS("ls", "LSO", "Lesotho"), /** Lithuania */ LT("lt", "LTU", "Lithuania"), /** Luxembourg */ LU("lu", "LUX", "Luxembourg"), /** Latvia */ LV("lv", "LVA", "Latvia"), /** Libya */ LY("ly", "LBY", "Libya"), /** Morocco */ MA("ma", "MAR", "Morocco"), /** Monaco */ MC("mc", "MCO", "Monaco"), /** Moldova */ MD("md", "MDA", "Moldova"), /** Montenegro */ ME("me", "MNE", "Montenegro"), /** Saint Martin */ MF("mf", "MAF", "Saint Martin"), /** Madagascar */ MG("mg", "MDG", "Madagascar"), /** Marshall Islands */ MH("mh", "MHL", "Marshall Islands"), /** Macedonia */ MK("mk", "MKD", "Macedonia"), /** Mali */ ML("ml", "MLI", "Mali"), /** Myanmar */ MM("mm", "MMR", "Myanmar"), /** Mongolia */ MN("mn", "MNG", "Mongolia"), /** Macao */ MO("mo", "MAC", "Macao"), /** Northern Mariana Islands */ MP("mp", "MNP", "Northern Mariana Islands"), /** Martinique */ MQ("mq", "MTQ", "Martinique"), /** Mauritania */ MR("mr", "MRT", "Mauritania"), /** Montserrat */ MS("ms", "MSR", "Montserrat"), /** Malta */ MT("mt", "MLT", "Malta"), /** Mauritius */ MU("mu", "MUS", "Mauritius"), /** Maldives */ MV("mv", "MDV", "Maldives"), /** Malawi */ MW("mw", "MWI", "Malawi"), /** Mexico */ MX("mx", "MEX", "Mexico"), /** Malaysia */ MY("my", "MYS", "Malaysia"), /** Mozambique */ MZ("mz", "MOZ", "Mozambique"), /** Namibia */ NA("na", "NAM", "Namibia"), /** New Caledonia */ NC("nc", "NCL", "New Caledonia"), /** Niger */ NE("ne", "NER", "Niger"), /** Norfolk Island */ NF("nf", "NFK", "Norfolk Island"), /** Nigeria */ NG("ng", "NGA", "Nigeria"), /** Nicaragua */ NI("ni", "NIC", "Nicaragua"), /** Netherlands */ NL("nl", "NLD", "Netherlands"), /** Norway */ NO("no", "NOR", "Norway"), /** Nepal */ NP("np", "NPL", "Nepal"), /** Nauru */ NR("nr", "NRU", "Nauru"), /** Niue */ NU("nu", "NIU", "Niue"), /** New Zealand */ NZ("nz", "NZL", "New Zealand"), /** Oman */ OM("om", "OMN", "Oman"), /** Panama */ PA("pa", "PAN", "Panama"), /** Peru */ PE("pe", "PER", "Peru"), /** French Polynesia */ PF("pf", "PYF", "French Polynesia"), /** Papua New Guinea */ PG("pg", "PNG", "Papua New Guinea"), /** Philippines */ PH("ph", "PHL", "Philippines"), /** Pakistan */ PK("pk", "PAK", "Pakistan"), /** Poland */ PL("pl", "POL", "Poland"), /** Saint Pierre And Miquelon */ PM("pm", "SPM", "Saint Pierre And Miquelon"), /** Pitcairn */ PN("pn", "PCN", "Pitcairn"), /** Puerto Rico */ PR("pr", "PRI", "Puerto Rico"), /** Palestine */ PS("ps", "PSE", "Palestine"), /** Portugal */ PT("pt", "PRT", "Portugal"), /** Palau */ PW("pw", "PLW", "Palau"), /** Paraguay */ PY("py", "PRY", "Paraguay"), /** Qatar */ QA("qa", "QAT", "Qatar"), /** Reunion */ RE("re", "REU", "Reunion"), /** Romania */ RO("ro", "ROU", "Romania"), /** Serbia */ RS("rs", "SRB", "Serbia"), /** Russia */ RU("ru", "RUS", "Russia", "Russian Federation"), /** Rwanda */ RW("rw", "RWA", "Rwanda"), /** Saudi Arabia */ SA("sa", "SAU", "Saudi Arabia"), /** Solomon Islands */ SB("sb", "SLB", "Solomon Islands"), /** Seychelles */ SC("sc", "SYC", "Seychelles"), /** Sudan */ SD("sd", "SDN", "Sudan"), /** Sweden */ SE("se", "SWE", "Sweden"), /** Singapore */ SG("sg", "SGP", "Singapore"), /** Saint Helena */ SH("sh", "SHN", "Saint Helena"), /** Slovenia */ SI("si", "SVN", "Slovenia"), /** Svalbard And Jan Mayen */ SJ("sj", "SJM", "Svalbard And Jan Mayen"), /** Slovakia */ SK("sk", "SVK", "Slovakia"), /** Sierra Leone */ SL("sl", "SLE", "Sierra Leone"), /** San Marino */ SM("sm", "SMR", "San Marino"), /** Senegal */ SN("sn", "SEN", "Senegal"), /** Somalia */ SO("so", "SOM", "Somalia"), /** Suriname */ SR("sr", "SUR", "Suriname"), /** Sao Tome And Principe */ ST("st", "STP", "Sao Tome And Principe"), /** El Salvador */ SV("sv", "SLV", "El Salvador"), /** Syria */ SY("sy", "SYR", "Syria"), /** Swaziland */ SZ("sz", "SWZ", "Swaziland"), /** Turks And Caicos Islands */ TC("tc", "TCA", "Turks And Caicos Islands"), /** Chad */ TD("td", "TCD", "Chad"), /** French Southern Territories */ TF("tf", "ATF", "French Southern Territories"), /** Togo */ TG("tg", "TGO", "Togo"), /** Thailand */ TH("th", "THA", "Thailand"), /** Tajikistan */ TJ("tj", "TJK", "Tajikistan"), /** Tokelau */ TK("tk", "TKL", "Tokelau"), /** Timor-Leste */ TL("tl", "TLS", "Timor-Leste"), /** Turkmenistan */ TM("tm", "TKM", "Turkmenistan"), /** Tunisia */ TN("tn", "TUN", "Tunisia"), /** Tonga */ TO("to", "TON", "Tonga"), /** Turkey */ TR("tr", "TUR", "Turkey"), /** Trinidad and Tobago */ TT("tt", "TTO", "Trinidad and Tobago"), /** Tuvalu */ TV("tv", "TUV", "Tuvalu"), /** Taiwan */ TW("tw", "TWN", "Taiwan"), /** Tanzania */ TZ("tz", "TZA", "Tanzania"), /** Ukraine */ UA("ua", "UKR", "Ukraine"), /** Uganda */ UG("ug", "UGA", "Uganda"), /** United States Minor Outlying Islands */ UM("um", "UMI", "United States Minor Outlying Islands"), /** United States */ US("us", "USA", "United States"), /** Uruguay */ UY("uy", "URY", "Uruguay"), /** Uzbekistan */ UZ("uz", "UZB", "Uzbekistan"), /** Vatican */ VA("va", "VAT", "Vatican"), /** Saint Vincent And The Grenadines */ VC("vc", "VCT", "Saint Vincent And The Grenadines"), /** Venezuela */ VE("ve", "VEN", "Venezuela"), /** British Virgin Islands */ VG("vg", "VGB", "British Virgin Islands"), /** U.S. Virgin Islands */ VI("vi", "VIR", "U.S. Virgin Islands"), /** Vietnam */ VN("vn", "VNM", "Vietnam", "Viet Nam", "Socialist Republic of Vietnam", "SRV"), /** Vanuatu */ VU("vu", "VUT", "Vanuatu"), /** Wallis And Futuna */ WF("wf", "WLF", "Wallis And Futuna"), /** Samoa */ WS("ws", "WSM", "Samoa"), /** Yemen */ YE("ye", "YEM", "Yemen"), /** Mayotte */ YT("yt", "MYT", "Mayotte"), /** South Africa */ ZA("za", "ZAF", "South Africa"), /** Zambia */ ZM("zm", "ZMB", "Zambia"), /** Zimbabwe */ ZW("zw", "ZWE", "Zimbabwe"); /** * Finds a PlayerType that matches the id on id, name, or name(). * * @param string * Value to match against id, name, or name() * @return Matching PlayerType, or null. */ public static ISOCountry get(final String string) { for (final ISOCountry country : values()) { if (country.getId().equals(string) || country.getCode().equals(string) || country.name().equals(string) || country.getName().equals(string)) { return country; } if (country.aliases != null) { for (String alias : country.aliases) { if (alias.equals(string)) { return country; } } } } return null; } private final String id; private final String abbr2; private final String abbr3; private final String name; private final ISOCountry parent; @Getter private final String[] aliases; private ISOCountry(final String id, final String abbr3, final String name, final String... aliases) { this.id = id; this.abbr2 = id.toUpperCase(); this.abbr3 = abbr3; this.name = name; this.parent = null; this.aliases = aliases; } private ISOCountry(final String id, final String abbr3, final String name, final ISOCountry parent) { this.id = id; this.abbr2 = id.toUpperCase(); this.abbr3 = abbr3; this.name = name; this.parent = parent; this.aliases = null; } /** * The public abbreviation of the country. Alias for * {@link ISOCountry#getAbbr2}. * * @see com.ajah.geo.iso.ISOCountry#getAbbr2() * * Example: The abbreviation of the United States would be "US". * * @return The public abbreviation of the country. Should never be null or * empty. */ @Override public String getAbbr() { return getAbbr2(); } /** * The ISO 2-letter code for this country. * * Example: The abbreviation of the United States would be "US". * * @return The ISO 2-letter code for the country. Should never be null or * empty. */ public String getAbbr2() { return this.abbr2; } /** * The ISO 3-letter code for this country. * * Example: The abbreviation of the United States would be "USA". * * @return The ISO 3-letter code for the country. Should never be null or * empty. */ public String getAbbr3() { return this.abbr3; } /** * @see com.ajah.util.IdentifiableEnum#getCode() */ @Override public String getCode() { return getAbbr3(); } /** * The lowercase version of the ISO 2-letter code for this country. * * Example: The ID of the United States would be "us". * * @return The lowercase version of the ISO 2-letter code for the country. * Should never be null or empty. */ @Override public String getId() { return this.id; } /** * The ISO "short" name of the country. * * @see com.ajah.geo.Country#getName() * @return the ISO Short name of the country. Should never be null or empty. */ @Override public String getName() { return this.name; } /** * Returns the parent of this country (making it a subdivision). * * @return the parent Country, if applicable, otherwise null. */ public ISOCountry getParent() { return this.parent; } @Override public void setId(final String id) { throw new UnsupportedOperationException(); } }
Add continents
ajah-geo/src/main/java/com/ajah/geo/iso/ISOCountry.java
Add continents
Java
apache-2.0
40c8eb7dba94d1e144bf57cfd59ea43031109ddf
0
x-meta/x-meta
/* * Copyright 2007-2008 The X-Meta.org. * * Licensed to the X-Meta under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The X-Meta 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.xmeta.util; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import ognl.Ognl; import ognl.OgnlException; import org.xmeta.ActionContext; import org.xmeta.Thing; import org.xmeta.World; import org.xmeta.ui.session.Session; import org.xmeta.ui.session.SessionManager; /** * 字符串工具类。 * * @author <a href="mailto:[email protected]">zyx</a> * */ public class UtilString { /** * 解析使用Groovy方式定义的字符串数组,如["cb", "cb"] as String[]。 */ public static String[] getGroovyStringArray(String str){ if(str.startsWith("[") && str.endsWith("as String[]")){ str= str.substring(1, str.lastIndexOf("]", str.length() - 3)); } String strs[] = str.split("[,]"); for(int i=0; i<strs.length; i++){ strs[i] = strs[i].trim(); if(strs[i].startsWith("\"") && strs[i].endsWith("\"")){ strs[i] = strs[i].substring(1, strs[i].length() - 1); } } return strs; } /** * 返回字符串是否相等,如果属性值为null也返回false。 * * @param thing * @param attributeName * @param value * @return */ public static boolean eq(Thing thing, String attributeName, String value){ String attrValue = thing.getString(attributeName); if(attrValue != null && attrValue.equals(value)){ return true; } return false; } /** * 返回指定的事物的属性是否为空,如果是字符串那么null和""都返回true。 * * @param thing * @param attributeName * @return */ public static boolean isNull(Thing thing, String attributeName){ Object value = thing.getAttribute(attributeName); if(value == null || (value instanceof String && "".equals(value))){ return true; } return false; } /** * 分割字符串的方法非String实现,稍微快一些。 * * @param str * @param ch * @return */ public static String[] split(String str, char ch){ char[] chs = str.toCharArray(); String[] strs = new String[10]; int strIndex = 0; int index1 = 0; int index2 = 0; while(index2 < chs.length){ if(chs[index2] == ch){ strs[strIndex] = new String(chs, index1, index2 - index1); index1 = index2+1; strIndex++; if(strIndex >= strs.length){ String[] nstrs = new String[strs.length + 10]; System.arraycopy(strs, 0, nstrs, 0, strs.length); strs = nstrs; } } index2++; } if(index1 <= index2){ strs[strIndex] = new String(chs, index1, index2 - index1); strIndex++; if(strIndex >= strs.length){ String[] nstrs = new String[strs.length + 10]; System.arraycopy(strs, 0, nstrs, 0, strs.length); strs = nstrs; } } String fstrs[] = new String[strIndex]; System.arraycopy(strs, 0, fstrs, 0, strIndex); return fstrs; } /** * 判断描述者列表字符串中是否包含描述者。 * * @param descriptors 描述者列表 * @param descritpor 描述者 * @return 是否包含 */ public static boolean haveDescriptor(String descriptors, String descriptor){ if(descriptors == null){ return false; }else{ String[] descs = descriptors.split("[,]"); for(String desc : descs){ if(desc.equals(descriptor)){ return true; } } return false; } } /** * 插入一个指定字符串至源字符串中,源字符串中用,号隔开的。 * * @param source 源字符串 * @param forInsert 需要插入的字符串 * @param index 位置 * @return 新的字符串 */ public static String insert(String source, String forInsert, int index){ if(forInsert == null || "".equals(forInsert)){ return source; } if(source != null && !"".equals(source)){ String srouces[] = source.split("[,]"); source = ""; int i = 0; boolean added = false; for(String src : srouces){ if(index == i){ source = source + "," + forInsert; added = true; } if(!src.equals(forInsert)){ source = source + "," + src; } i++; } if(!added){ source = source + "," + forInsert; } if(source.startsWith(",")){ source = source.substring(1, source.length()); } return source; }else{ return forInsert; } } public static Object createObjectFromParams(String params, String thingPath, ActionContext actionContext){ if(params == null || "".equals(params)){ return null; } Map<String, String> values = UtilString.getParams(params); return createObjectFromParams(values, thingPath, actionContext); } public static Object createObjectFromParams(Map<String, ?> values, String thingPath, ActionContext actionContext){ Thing thing = World.getInstance().getThing(thingPath); if(thing != null){ Thing vthing = new Thing(thingPath); vthing.getAttributes().putAll(values); return vthing.doAction("create", actionContext); }else{ return null; } } public static boolean isNotNull(String str){ return str != null && !"".equals(str); } public static boolean isNull(String str){ return str == null || "".equals(str); } public static String capFirst(String str){ if(str == null || str.length() == 0){ return str; } if(str.length() == 1){ return str.toUpperCase(); } return str.substring(0, 1).toUpperCase() + str.substring(1, str.length()); } /** * 让字符串的第一个字母小写。 * * @param str * @return */ public static String uncapFirst(String str){ if(str == null || str.length() == 0){ return str; } if(str.length() == 1){ return str.toLowerCase(); } return str.substring(0, 1).toLowerCase() + str.substring(1, str.length()); } public static void debug(ActionContext context, Object obj){ System.out.println(context); System.out.println(obj); System.out.println(context.get("parent")); } public static String[] getStringArray(String strArray){ if(strArray == null){ return null; }else{ String ints[] = strArray.split("[,]"); String[] is = new String[ints.length]; for(int i=0; i<ints.length; i++){ is[i] = ints[i].trim(); } return is; } } public static int[] toIntArray(String intArray){ if(intArray == null || "".equals(intArray)){ return null; }else{ String ints[] = intArray.split("[,]"); int[] is = new int[ints.length]; for(int i=0; i<ints.length; i++){ is[i] = Integer.parseInt(ints[i].trim()); } return is; } } /** * 解码参数字符串,分隔符默认为&,默认编码utf-8,过滤引号。 * * @param str 参数字符串 * @return */ public static Map<String, String> getParams(String str){ return getParams(str, "&", "utf-8", true); } /** * 解码参数字符串,默认编码utf-8,过滤引号。 * * @param str 参数字符串 * @param splitStr 分隔符 * @return */ public static Map<String, String> getParams(String str, String splitStr){ return getParams(str, splitStr, "utf-8", true); } /** * 解码参数字符串,过滤引号。 * * @param str 参数字符串 * @param splitStr 分隔符 * @param encoding 编码 * @return */ public static Map<String, String> getParams(String str, String splitStr, String encoding){ return getParams(str, splitStr, encoding, true); } /** * 解码参数字符串。 * * @param str 参数字符串 * @param splitStr 分隔符 * @param encoding 编码 * @param trimQuotate 是否过滤参数值包围的引号 * @return */ public static Map<String, String> getParams(String str, String splitStr, String encoding, boolean trimQuotate){ if(str == null || "".equals(str)){ return Collections.emptyMap(); } Map<String, String> paras = new HashMap<String, String>(); String[] ps = str.split("[" + splitStr + "]"); for(int i=0; i<ps.length; i++){ int index = ps[i].indexOf("="); if(index != -1 && index != 0 && index != ps[i].length()){ String name = ps[i].substring(0, index); String value = ps[i].substring(index + 1, ps[i].length()); try { value = URLDecoder.decode(value, encoding); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } if(trimQuotate){ if(value.startsWith("\"") || value.startsWith("'")){ value = value.substring(1, value.length()); } if(value.endsWith("\"") || value.endsWith("'")){ value = value.substring(0, value.length() - 1); } } paras.put(name.trim(), value); } } return paras; } public static int getInt(String str){ try{ return Integer.parseInt(str); }catch(Exception e){ // e.printStackTrace(); return 0; } } /** * 从事物取指定的属性的字符串值,然后从actionContext中取可能的值。 * * @param thing * @param attribute * @param actionContext * @return */ public static String getString(Thing thing, String attribute, ActionContext actionContext){ String value = thing.getString(attribute); return getString(value, actionContext); } /** * 从制定的字符串值中读取字符串。<p/> * * 如果字符串值为"号开头,那么返回"号包围的字符串值,如果是以res:开头那么从资源文件中读取,如果以上条件都不符合那么从 * actionContext或binding中读取。<p/> * * 如果是读取资源,那么字符串的格式为:res:<resourceName>:<varName>:<defaultValue>。 * * @param value 字符串值 * @param actionContext 动作上下文 * * @return 字符串 */ public static String getString(String value, ActionContext actionContext){ if(value == null) return ""; if(value.startsWith("res:")){ Session session = SessionManager.getSession(null); UtilResource resource = session.getI18nResource(); String resStrs[] = value.split("[:]"); String defaultValue = ""; if(resStrs.length >= 4){ defaultValue = resStrs[3]; } String svalue = resource.get(resStrs[1], resStrs[2], defaultValue); if(svalue == null){ return defaultValue; }else{ return svalue; } }else if(value.startsWith("label:")){ String thingPath = value.substring(6, value.length()); Thing labelThing = World.getInstance().getThing(thingPath); if(labelThing == null){ return thingPath; }else{ return World.getInstance().getThing(thingPath).getMetadata().getLabel(); } }else if(value.startsWith("desc:")){ String thingPath = value.substring(5, value.length()); Thing labelThing = World.getInstance().getThing(thingPath); if(labelThing == null){ return thingPath; }else{ return World.getInstance().getThing(thingPath).getMetadata().getDescription(); } }else if(value.startsWith("attr:")){ String thingPath = value.substring(5, value.length()); Object obj = World.getInstance().get(thingPath); if(obj != null){ return String.valueOf(obj); }else{ return thingPath; } } String v = value; boolean constant = false; if(v.startsWith("\"")){ //按常量处理 constant = true; //去第一个" v = v.substring(1, v.length()); } if(v.endsWith("\"")){ //去最后一个" v = v.substring(0, v.length() - 1); } if(constant){ return v; }else{ String obj = null; if(actionContext != null){ try { obj = (String) Ognl.getValue(v, actionContext); } catch (Exception e) { obj = (String) actionContext.get(v); } } if(obj != null){ return obj; }else{ return value; } } } public static String toUnicode(String theString, boolean escapeSpace) { if(theString == null) return ""; int len = theString.length(); int bufLen = len * 2; if (bufLen < 0) { bufLen = Integer.MAX_VALUE; } StringBuffer outBuffer = new StringBuffer(bufLen); for(int x=0; x<len; x++) { char aChar = theString.charAt(x); // Handle common case first, selecting largest block that // avoids the specials below if ((aChar > 61) && (aChar < 127)) { if (aChar == '\\') { outBuffer.append('\\'); outBuffer.append('\\'); continue; } outBuffer.append(aChar); continue; } switch(aChar) { case ' ': if (x == 0 || escapeSpace) outBuffer.append('\\'); outBuffer.append(' '); break; case '\t':outBuffer.append('\\'); outBuffer.append('t'); break; case '\n':outBuffer.append('\\'); outBuffer.append('n'); break; case '\r':outBuffer.append('\\'); outBuffer.append('r'); break; case '\f':outBuffer.append('\\'); outBuffer.append('f'); break; case '=': // Fall through case ':': // Fall through case '#': // Fall through case '!': outBuffer.append('\\'); outBuffer.append(aChar); break; default: if ((aChar < 0x0020) || (aChar > 0x007e)) { outBuffer.append('\\'); outBuffer.append('u'); outBuffer.append(toHex((aChar >> 12) & 0xF)); outBuffer.append(toHex((aChar >> 8) & 0xF)); outBuffer.append(toHex((aChar >> 4) & 0xF)); outBuffer.append(toHex( aChar & 0xF)); } else { outBuffer.append(aChar); } } } return outBuffer.toString(); } public static char toHex(int nibble) { return hexDigit[(nibble & 0xF)]; } public static String toHexString(byte[] bytes) { char[] buf = new char[bytes.length * 2]; int radix = 1 << 4; int mask = radix - 1; for (int i = 0; i < bytes.length; i++) { buf[2 * i] = hexDigit[(bytes[i] >>> 4) & mask]; buf[2 * i + 1] = hexDigit[bytes[i] & mask]; } return new String(buf); } /** * 将"00 01 02"形式的字符串转成byte[] * * @param hex * @return */ public static byte[] hexStringToByteArray(String hex) { if (hex == null) { return null; } int stringLength = hex.length(); if (stringLength % 2 != 0) { throw new IllegalArgumentException("Hex String must have even number of characters!"); } byte[] result = new byte[stringLength / 2]; int j = 0; for (int i = 0; i < result.length; i++) { char hi = Character.toLowerCase(hex.charAt(j++)); char lo = Character.toLowerCase(hex.charAt(j++)); result[i] = (byte) ((Character.digit(hi, 16) << 4) | Character.digit(lo, 16)); } return result; } /** A table of hex digits */ private static final char[] hexDigit = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' }; }
org.xmeta.engine/src/main/java/org/xmeta/util/UtilString.java
/* * Copyright 2007-2008 The X-Meta.org. * * Licensed to the X-Meta under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The X-Meta 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.xmeta.util; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import ognl.Ognl; import ognl.OgnlException; import org.xmeta.ActionContext; import org.xmeta.Thing; import org.xmeta.World; import org.xmeta.ui.session.Session; import org.xmeta.ui.session.SessionManager; /** * 字符串工具类。 * * @author <a href="mailto:[email protected]">zyx</a> * */ public class UtilString { /** * 解析使用Groovy方式定义的字符串数组,如["cb", "cb"] as String[]。 */ public static String[] getGroovyStringArray(String str){ if(str.startsWith("[") && str.endsWith("as String[]")){ str= str.substring(1, str.lastIndexOf("]", str.length() - 3)); } String strs[] = str.split("[,]"); for(int i=0; i<strs.length; i++){ strs[i] = strs[i].trim(); if(strs[i].startsWith("\"") && strs[i].endsWith("\"")){ strs[i] = strs[i].substring(1, strs[i].length() - 1); } } return strs; } /** * 返回字符串是否相等,如果属性值为null也返回false。 * * @param thing * @param attributeName * @param value * @return */ public static boolean eq(Thing thing, String attributeName, String value){ String attrValue = thing.getString(attributeName); if(attrValue != null && attrValue.equals(value)){ return true; } return false; } /** * 返回指定的事物的属性是否为空,如果是字符串那么null和""都返回true。 * * @param thing * @param attributeName * @return */ public static boolean isNull(Thing thing, String attributeName){ Object value = thing.getAttribute(attributeName); if(value == null || (value instanceof String && "".equals(value))){ return true; } return false; } /** * 分割字符串的方法非String实现,稍微快一些。 * * @param str * @param ch * @return */ public static String[] split(String str, char ch){ char[] chs = str.toCharArray(); String[] strs = new String[10]; int strIndex = 0; int index1 = 0; int index2 = 0; while(index2 < chs.length){ if(chs[index2] == ch){ strs[strIndex] = new String(chs, index1, index2 - index1); index1 = index2+1; strIndex++; if(strIndex >= strs.length){ String[] nstrs = new String[strs.length + 10]; System.arraycopy(strs, 0, nstrs, 0, strs.length); strs = nstrs; } } index2++; } if(index1 <= index2){ strs[strIndex] = new String(chs, index1, index2 - index1); strIndex++; if(strIndex >= strs.length){ String[] nstrs = new String[strs.length + 10]; System.arraycopy(strs, 0, nstrs, 0, strs.length); strs = nstrs; } } String fstrs[] = new String[strIndex]; System.arraycopy(strs, 0, fstrs, 0, strIndex); return fstrs; } /** * 判断描述者列表字符串中是否包含描述者。 * * @param descriptors 描述者列表 * @param descritpor 描述者 * @return 是否包含 */ public static boolean haveDescriptor(String descriptors, String descriptor){ if(descriptors == null){ return false; }else{ String[] descs = descriptors.split("[,]"); for(String desc : descs){ if(desc.equals(descriptor)){ return true; } } return false; } } /** * 插入一个指定字符串至源字符串中,源字符串中用,号隔开的。 * * @param source 源字符串 * @param forInsert 需要插入的字符串 * @param index 位置 * @return 新的字符串 */ public static String insert(String source, String forInsert, int index){ if(forInsert == null || "".equals(forInsert)){ return source; } if(source != null && !"".equals(source)){ String srouces[] = source.split("[,]"); source = ""; int i = 0; boolean added = false; for(String src : srouces){ if(index == i){ source = source + "," + forInsert; added = true; } if(!src.equals(forInsert)){ source = source + "," + src; } i++; } if(!added){ source = source + "," + forInsert; } if(source.startsWith(",")){ source = source.substring(1, source.length()); } return source; }else{ return forInsert; } } public static Object createObjectFromParams(String params, String thingPath, ActionContext actionContext){ if(params == null || "".equals(params)){ return null; } Map<String, String> values = UtilString.getParams(params); return createObjectFromParams(values, thingPath, actionContext); } public static Object createObjectFromParams(Map<String, ?> values, String thingPath, ActionContext actionContext){ Thing thing = World.getInstance().getThing(thingPath); if(thing != null){ Thing vthing = new Thing(thingPath); vthing.getAttributes().putAll(values); return vthing.doAction("create", actionContext); }else{ return null; } } public static boolean isNotNull(String str){ return str != null && !"".equals(str); } public static boolean isNull(String str){ return str == null || "".equals(str); } public static String capFirst(String str){ if(str == null || str.length() == 0){ return str; } if(str.length() == 1){ return str.toUpperCase(); } return str.substring(0, 1).toUpperCase() + str.substring(1, str.length()); } /** * 让字符串的第一个字母小写。 * * @param str * @return */ public static String uncapFirst(String str){ if(str == null || str.length() == 0){ return str; } if(str.length() == 1){ return str.toLowerCase(); } return str.substring(0, 1).toLowerCase() + str.substring(1, str.length()); } public static void debug(ActionContext context, Object obj){ System.out.println(context); System.out.println(obj); System.out.println(context.get("parent")); } public static String[] getStringArray(String strArray){ if(strArray == null){ return null; }else{ String ints[] = strArray.split("[,]"); String[] is = new String[ints.length]; for(int i=0; i<ints.length; i++){ is[i] = ints[i].trim(); } return is; } } public static int[] toIntArray(String intArray){ if(intArray == null || "".equals(intArray)){ return null; }else{ String ints[] = intArray.split("[,]"); int[] is = new int[ints.length]; for(int i=0; i<ints.length; i++){ is[i] = Integer.parseInt(ints[i].trim()); } return is; } } /** * 解码参数字符串,分隔符默认为&,默认编码utf-8,过滤引号。 * * @param str 参数字符串 * @return */ public static Map<String, String> getParams(String str){ return getParams(str, "&", "utf-8", true); } /** * 解码参数字符串,默认编码utf-8,过滤引号。 * * @param str 参数字符串 * @param splitStr 分隔符 * @return */ public static Map<String, String> getParams(String str, String splitStr){ return getParams(str, splitStr, "utf-8", true); } /** * 解码参数字符串,过滤引号。 * * @param str 参数字符串 * @param splitStr 分隔符 * @param encoding 编码 * @return */ public static Map<String, String> getParams(String str, String splitStr, String encoding){ return getParams(str, splitStr, encoding, true); } /** * 解码参数字符串。 * * @param str 参数字符串 * @param splitStr 分隔符 * @param encoding 编码 * @param trimQuotate 是否过滤参数值包围的引号 * @return */ public static Map<String, String> getParams(String str, String splitStr, String encoding, boolean trimQuotate){ if(str == null || "".equals(str)){ return Collections.emptyMap(); } Map<String, String> paras = new HashMap<String, String>(); String[] ps = str.split("[" + splitStr + "]"); for(int i=0; i<ps.length; i++){ int index = ps[i].indexOf("="); if(index != -1 && index != 0 && index != ps[i].length()){ String name = ps[i].substring(0, index); String value = ps[i].substring(index + 1, ps[i].length()); try { value = URLDecoder.decode(value, encoding); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } if(trimQuotate){ if(value.startsWith("\"") || value.startsWith("'")){ value = value.substring(1, value.length()); } if(value.endsWith("\"") || value.endsWith("'")){ value = value.substring(0, value.length() - 1); } } paras.put(name.trim(), value); } } return paras; } public static int getInt(String str){ try{ return Integer.parseInt(str); }catch(Exception e){ // e.printStackTrace(); return 0; } } /** * 从事物取指定的属性的字符串值,然后从actionContext中取可能的值。 * * @param thing * @param attribute * @param actionContext * @return */ public static String getString(Thing thing, String attribute, ActionContext actionContext){ String value = thing.getString(attribute); return getString(value, actionContext); } /** * 从制定的字符串值中读取字符串。<p/> * * 如果字符串值为"号开头,那么返回"号包围的字符串值,如果是以res:开头那么从资源文件中读取,如果以上条件都不符合那么从 * actionContext或binding中读取。<p/> * * 如果是读取资源,那么字符串的格式为:res:<resourceName>:<varName>:<defaultValue>。 * * @param value 字符串值 * @param actionContext 动作上下文 * * @return 字符串 */ public static String getString(String value, ActionContext actionContext){ if(value == null) return ""; if(value.startsWith("res:")){ Session session = SessionManager.getSession(null); UtilResource resource = session.getI18nResource(); String resStrs[] = value.split("[:]"); String defaultValue = ""; if(resStrs.length >= 4){ defaultValue = resStrs[3]; } String svalue = resource.get(resStrs[1], resStrs[2], defaultValue); if(svalue == null){ return defaultValue; }else{ return svalue; } }else if(value.startsWith("label:")){ String thingPath = value.substring(6, value.length()); Thing labelThing = World.getInstance().getThing(thingPath); if(labelThing == null){ return thingPath; }else{ return World.getInstance().getThing(thingPath).getMetadata().getLabel(); } }else if(value.startsWith("desc:")){ String thingPath = value.substring(5, value.length()); Thing labelThing = World.getInstance().getThing(thingPath); if(labelThing == null){ return thingPath; }else{ return World.getInstance().getThing(thingPath).getMetadata().getDescription(); } }else if(value.startsWith("attr:")){ String thingPath = value.substring(5, value.length()); Object obj = World.getInstance().get(thingPath); if(obj != null){ return String.valueOf(obj); }else{ return thingPath; } } String v = value; boolean constant = false; if(v.startsWith("\"")){ //按常量处理 constant = true; //去第一个" v = v.substring(1, v.length()); } if(v.endsWith("\"")){ //去最后一个" v = v.substring(0, v.length() - 1); } if(constant){ return v; }else{ String obj = null; if(actionContext != null){ try { obj = (String) Ognl.getValue(v, actionContext); } catch (OgnlException e) { obj = (String) actionContext.get(v); } } if(obj != null){ return obj; }else{ return value; } } } public static String toUnicode(String theString, boolean escapeSpace) { if(theString == null) return ""; int len = theString.length(); int bufLen = len * 2; if (bufLen < 0) { bufLen = Integer.MAX_VALUE; } StringBuffer outBuffer = new StringBuffer(bufLen); for(int x=0; x<len; x++) { char aChar = theString.charAt(x); // Handle common case first, selecting largest block that // avoids the specials below if ((aChar > 61) && (aChar < 127)) { if (aChar == '\\') { outBuffer.append('\\'); outBuffer.append('\\'); continue; } outBuffer.append(aChar); continue; } switch(aChar) { case ' ': if (x == 0 || escapeSpace) outBuffer.append('\\'); outBuffer.append(' '); break; case '\t':outBuffer.append('\\'); outBuffer.append('t'); break; case '\n':outBuffer.append('\\'); outBuffer.append('n'); break; case '\r':outBuffer.append('\\'); outBuffer.append('r'); break; case '\f':outBuffer.append('\\'); outBuffer.append('f'); break; case '=': // Fall through case ':': // Fall through case '#': // Fall through case '!': outBuffer.append('\\'); outBuffer.append(aChar); break; default: if ((aChar < 0x0020) || (aChar > 0x007e)) { outBuffer.append('\\'); outBuffer.append('u'); outBuffer.append(toHex((aChar >> 12) & 0xF)); outBuffer.append(toHex((aChar >> 8) & 0xF)); outBuffer.append(toHex((aChar >> 4) & 0xF)); outBuffer.append(toHex( aChar & 0xF)); } else { outBuffer.append(aChar); } } } return outBuffer.toString(); } public static char toHex(int nibble) { return hexDigit[(nibble & 0xF)]; } public static String toHexString(byte[] bytes) { char[] buf = new char[bytes.length * 2]; int radix = 1 << 4; int mask = radix - 1; for (int i = 0; i < bytes.length; i++) { buf[2 * i] = hexDigit[(bytes[i] >>> 4) & mask]; buf[2 * i + 1] = hexDigit[bytes[i] & mask]; } return new String(buf); } /** * 将"00 01 02"形式的字符串转成byte[] * * @param hex * @return */ public static byte[] hexStringToByteArray(String hex) { if (hex == null) { return null; } int stringLength = hex.length(); if (stringLength % 2 != 0) { throw new IllegalArgumentException("Hex String must have even number of characters!"); } byte[] result = new byte[stringLength / 2]; int j = 0; for (int i = 0; i < result.length; i++) { char hi = Character.toLowerCase(hex.charAt(j++)); char lo = Character.toLowerCase(hex.charAt(j++)); result[i] = (byte) ((Character.digit(hi, 16) << 4) | Character.digit(lo, 16)); } return result; } /** A table of hex digits */ private static final char[] hexDigit = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' }; }
修改了UtilString中异常OgnlException改为Exception,隔断更多异常
org.xmeta.engine/src/main/java/org/xmeta/util/UtilString.java
修改了UtilString中异常OgnlException改为Exception,隔断更多异常
Java
apache-2.0
256af8c7d6fa3f9522264cc4fe59098f8f2c7026
0
fhieber/incubator-joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,gwenniger/joshua,lukeorland/joshua,thammegowda/incubator-joshua,gwenniger/joshua,lukeorland/joshua,fhieber/incubator-joshua,lukeorland/joshua,lukeorland/joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,gwenniger/joshua,gwenniger/joshua,fhieber/incubator-joshua,gwenniger/joshua,lukeorland/joshua,thammegowda/incubator-joshua,kpu/joshua,lukeorland/joshua,thammegowda/incubator-joshua,kpu/joshua,kpu/joshua,gwenniger/joshua,lukeorland/joshua,kpu/joshua,kpu/joshua,kpu/joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,lukeorland/joshua,fhieber/incubator-joshua,fhieber/incubator-joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,lukeorland/joshua,thammegowda/incubator-joshua
package joshua.ui.tree_visualizer; import javax.swing.*; import javax.swing.event.*; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.LinkedList; import java.awt.*; import java.awt.event.*; public class DerivationBrowser { private static JFrame chooserFrame; private static JList sourceList; private static JList targetList; private static File sourceFile; private static File targetFile; private static JFileChooser fileChooser; private static JFrame activeFrame; public static final int DEFAULT_WIDTH = 640; public static final int DEFAULT_HEIGHT = 480; public static void main(String [] argv) { initializeJComponents(); drawGraph(); chooserFrame.setVisible(true); return; } private static void initializeJComponents() { // JFrame init chooserFrame = new JFrame("Joshua Derivation Tree Browser"); chooserFrame.setSize(640, 480); chooserFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); chooserFrame.setJMenuBar(createJMenuBar()); chooserFrame.setLayout(new GridLayout(2,1)); sourceList = new JList(new DefaultListModel()); sourceList.setFixedCellWidth(200); sourceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); targetList = new JList(new DefaultListModel()); targetList.setFixedCellWidth(200); targetList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); chooserFrame.getContentPane().add(new JScrollPane(sourceList)); chooserFrame.getContentPane().add(new JScrollPane(targetList)); SentenceListListener sll = new SentenceListListener(sourceList, targetList); sourceList.getSelectionModel().addListSelectionListener(sll); targetList.getSelectionModel().addListSelectionListener(sll); // fileChooser fileChooser = new JFileChooser(); activeFrame = createActiveFrame(); return; } private static JMenuBar createJMenuBar() { JMenuBar mb = new JMenuBar(); JMenu openMenu = new JMenu("Control"); JMenuItem creat = new JMenuItem("New tree viewer window"); JMenuItem src = new JMenuItem("Open source file ..."); JMenuItem tgt = new JMenuItem("Open n-best derivations file ..."); FileChoiceListener fcl = new FileChoiceListener(src, tgt); src.addActionListener(fcl); tgt.addActionListener(fcl); creat.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { activeFrame = createActiveFrame(); return; } }); openMenu.add(creat); openMenu.add(src); openMenu.add(tgt); mb.add(openMenu); return mb; } private static void drawGraph() { for (Component c : activeFrame.getContentPane().getComponents()) activeFrame.getContentPane().remove(c); String src = (String) sourceList.getSelectedValue(); Derivation tgtDer = (Derivation) targetList.getSelectedValue(); if ((src == null) || (tgtDer == null)) { JLabel lbl = new JLabel("No tree to display."); activeFrame.getContentPane().add(lbl); lbl.revalidate(); activeFrame.getContentPane().repaint(); return; } String tgt = tgtDer.complete(); DerivationTree tree = new DerivationTree(tgt.split(DerivationTree.DELIMITER)[1], src); DerivationViewer dv = new DerivationViewer(tree); activeFrame.getContentPane().add(dv); dv.revalidate(); activeFrame.repaint(); activeFrame.getContentPane().repaint(); return; } private static void populateSourceList() { if (sourceFile == null) return; try { DefaultListModel model = (DefaultListModel) sourceList.getModel(); Scanner scanner = new Scanner(sourceFile, "UTF-8"); model.removeAllElements(); while (scanner.hasNextLine()) model.addElement(scanner.nextLine()); } catch (FileNotFoundException e) { } } private static void populateTargetList() { if (targetFile == null) return; DefaultListModel model = (DefaultListModel) targetList.getModel(); model.removeAllElements(); if (sourceList.getSelectedValue() == null) { return; } try { int selectedIndex = sourceList.getSelectedIndex(); Scanner scanner = new Scanner(targetFile, "UTF-8"); int src; while (scanner.hasNextLine()) { String line = scanner.nextLine(); String [] tokens = line.split(DerivationTree.DELIMITER); try { src = Integer.parseInt(tokens[0].trim()); if (src > selectedIndex) return; if (src == selectedIndex) model.addElement(new Derivation(line)); } catch (NumberFormatException e) { // fall through } } } catch (FileNotFoundException e) { } } private static JFrame createActiveFrame() { JFrame ret = new JFrame("Joshua Derivation Tree"); ret.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); ret.setVisible(true); return ret; } public static class FileChoiceListener implements ActionListener { private JMenuItem source; private JMenuItem target; public FileChoiceListener(JMenuItem s, JMenuItem t) { super(); source = s; target = t; } public void actionPerformed(ActionEvent e) { int ret = fileChooser.showOpenDialog(chooserFrame); if (ret == JFileChooser.APPROVE_OPTION) { File chosen = fileChooser.getSelectedFile(); JMenuItem origin = (JMenuItem) e.getSource(); if (origin.equals(source)) { sourceFile = chosen; populateSourceList(); } else { targetFile = chosen; populateTargetList(); } } return; } } public static class SentenceListListener implements ListSelectionListener { private JList source; private JList target; public SentenceListListener(JList s, JList t) { source = s; target = t; } public void valueChanged(ListSelectionEvent e) { if (e.getSource().equals(source.getSelectionModel())) { populateTargetList(); targetList.setSelectedIndex(0); } drawGraph(); return; } } public static class Derivation { private String complete; private String terminals; public Derivation(String c) { complete = c; terminals = extractTerminals(c); } public String complete() { return complete; } public String toString() { return terminals; } private static String extractTerminals(String s) { String tree = s.split(DerivationTree.DELIMITER)[1]; String [] tokens = tree.replaceAll("\\)", "\n)").split("\\s+"); String result = ""; for (String t : tokens) { if (t.startsWith("(") || t.equals(")")) continue; result += " " + t; } return result; } } }
src/joshua/ui/tree_visualizer/DerivationBrowser.java
package joshua.ui.tree_visualizer; import javax.swing.*; import javax.swing.event.*; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.LinkedList; import java.awt.*; import java.awt.event.*; public class DerivationBrowser { private static JFrame frame; private static JPanel graphPanel; private static JPanel chooserPanel; private static JList sourceList; private static JList targetList; private static File sourceFile; private static File targetFile; private static JFileChooser fileChooser; public static void main(String [] argv) { initializeJComponents(); drawGraph(); frame.setVisible(true); return; } private static void initializeJComponents() { // JFrame init frame = new JFrame("Joshua Derivation Tree Browser"); frame.setSize(640, 480); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(createJMenuBar()); frame.setLayout(new BorderLayout()); // chooserPanel chooserPanel = new JPanel(); chooserPanel.setLayout(new GridLayout()); frame.getContentPane().add(chooserPanel, BorderLayout.WEST); sourceList = new JList(new DefaultListModel()); sourceList.setFixedCellWidth(200); sourceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); targetList = new JList(new DefaultListModel()); targetList.setFixedCellWidth(200); targetList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); chooserPanel.add(new JScrollPane(sourceList)); chooserPanel.add(new JScrollPane(targetList)); SentenceListListener sll = new SentenceListListener(sourceList, targetList); sourceList.getSelectionModel().addListSelectionListener(sll); targetList.getSelectionModel().addListSelectionListener(sll); // graphPanel graphPanel = new JPanel(); graphPanel.setLayout(new BorderLayout()); graphPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); frame.getContentPane().add(graphPanel, BorderLayout.CENTER); // fileChooser fileChooser = new JFileChooser(); return; } private static JMenuBar createJMenuBar() { JMenuBar mb = new JMenuBar(); JMenu openMenu = new JMenu("Open"); JMenuItem src = new JMenuItem("Source ..."); JMenuItem tgt = new JMenuItem("Target ..."); FileChoiceListener fcl = new FileChoiceListener(src, tgt); src.addActionListener(fcl); tgt.addActionListener(fcl); openMenu.add(src); openMenu.add(tgt); mb.add(openMenu); return mb; } private static void drawGraph() { for (Component c : graphPanel.getComponents()) graphPanel.remove(c); String src = (String) sourceList.getSelectedValue(); String tgt = (String) targetList.getSelectedValue(); if ((src == null) || (tgt == null)) { graphPanel.add(new JLabel("No tree to display."), BorderLayout.CENTER); graphPanel.revalidate(); graphPanel.repaint(); return; } DerivationTree tree = new DerivationTree(tgt.split(DerivationTree.DELIMITER)[1], src); DerivationViewer dv = new DerivationViewer(tree); graphPanel.add(dv, BorderLayout.CENTER); graphPanel.revalidate(); graphPanel.repaint(); return; } private static void populateSourceList() { if (sourceFile == null) return; try { DefaultListModel model = (DefaultListModel) sourceList.getModel(); Scanner scanner = new Scanner(sourceFile, "UTF-8"); model.removeAllElements(); while (scanner.hasNextLine()) model.addElement(scanner.nextLine()); } catch (FileNotFoundException e) { } } private static void populateTargetList() { if (targetFile == null) return; DefaultListModel model = (DefaultListModel) targetList.getModel(); model.removeAllElements(); if (sourceList.getSelectedValue() == null) { return; } try { int selectedIndex = sourceList.getSelectedIndex(); Scanner scanner = new Scanner(targetFile, "UTF-8"); int src; while (scanner.hasNextLine()) { String line = scanner.nextLine(); String [] tokens = line.split(DerivationTree.DELIMITER); try { src = Integer.parseInt(tokens[0].trim()); if (src > selectedIndex) return; if (src == selectedIndex) model.addElement(line); } catch (NumberFormatException e) { // fall through } } } catch (FileNotFoundException e) { } } public static class FileChoiceListener implements ActionListener { private JMenuItem source; private JMenuItem target; public FileChoiceListener(JMenuItem s, JMenuItem t) { super(); source = s; target = t; } public void actionPerformed(ActionEvent e) { int ret = fileChooser.showOpenDialog(frame); if (ret == JFileChooser.APPROVE_OPTION) { File chosen = fileChooser.getSelectedFile(); JMenuItem origin = (JMenuItem) e.getSource(); if (origin.equals(source)) { sourceFile = chosen; populateSourceList(); } else { targetFile = chosen; populateTargetList(); } } return; } } public static class SentenceListListener implements ListSelectionListener { private JList source; private JList target; public SentenceListListener(JList s, JList t) { source = s; target = t; } public void valueChanged(ListSelectionEvent e) { if (e.getSource().equals(source.getSelectionModel())) { populateTargetList(); } drawGraph(); return; } } }
Updating the derivation-tree browser. git-svn-id: 113d22c177a5f4646d60eedc1d71f196641d30ff@890 0ae5e6b2-d358-4f09-a895-f82f13dd62a4
src/joshua/ui/tree_visualizer/DerivationBrowser.java
Updating the derivation-tree browser.
Java
apache-2.0
abf0cacd2bd994ea995e4f3c190d1864c2e2cb9b
0
samuel22gj/OtterLibrary,samuel22gj/OtterLibrary
package com.otter.otterlibrary; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * OScreen is a toolkit of getting screen information. */ public class OScreen { private static Display getDisplay(Context ctx) { WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); return wm.getDefaultDisplay(); } private static DisplayMetrics getDisplayMetrics(Context ctx) { DisplayMetrics dm = new DisplayMetrics(); getDisplay(ctx).getMetrics(dm); return dm; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private static DisplayMetrics getRealDisplayMetrics(Context ctx) { DisplayMetrics dm = new DisplayMetrics(); getDisplay(ctx).getRealMetrics(dm); return dm; } /** The absolute width of the display in pixels. */ public static int getWidth(Context ctx) { return getDisplayMetrics(ctx).widthPixels; } /** The absolute height of the display in pixels. */ public static int getHeight(Context ctx) { return getDisplayMetrics(ctx).heightPixels; } /** The absolute width of the display in pixels based on the real size */ public static int getRealWidth(Context ctx) { if (Build.VERSION.SDK_INT >= 17) { return getRealDisplayMetrics(ctx).widthPixels; } else if (Build.VERSION.SDK_INT >= 13){ int width = -1; try { Display display = getDisplay(ctx); Method method = Display.class.getMethod("getRawWidth"); width = (Integer) method.invoke(display); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return width; } else { return getWidth(ctx); } } /** The absolute height of the display in pixels based on the real size */ public static int getRealHeight(Context ctx) { if (Build.VERSION.SDK_INT >= 17) { return getRealDisplayMetrics(ctx).heightPixels; } else if (Build.VERSION.SDK_INT >= 13){ int height = -1; try { Display display = getDisplay(ctx); Method method = Display.class.getMethod("getRawHeight"); height = (Integer) method.invoke(display); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return height; } else { return getHeight(ctx); } } /** The logical density of the display. */ public static float getDensity(Context ctx) { return getDisplayMetrics(ctx).density; } /** The screen density expressed as dots-per-inch. */ public static float getDensityDpi(Context ctx) { return getRealDisplayMetrics(ctx).densityDpi; } /** * The rotation of the screen from its "natural" orientation. * * @see android.view.Surface#ROTATION_0 * @see android.view.Surface#ROTATION_90 * @see android.view.Surface#ROTATION_180 * @see android.view.Surface#ROTATION_270 */ public static int getRotation (Context ctx) { return getDisplay(ctx).getRotation(); } }
otterlibrary/src/main/java/com/otter/otterlibrary/OScreen.java
package com.otter.otterlibrary; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * OScreen is a toolkit of getting screen information. */ public class OScreen { private static Display getDisplay(Context ctx) { WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); return wm.getDefaultDisplay(); } private static DisplayMetrics getDisplayMetrics(Context ctx) { DisplayMetrics dm = new DisplayMetrics(); getDisplay(ctx).getMetrics(dm); return dm; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private static DisplayMetrics getRealDisplayMetrics(Context ctx) { DisplayMetrics dm = new DisplayMetrics(); getDisplay(ctx).getRealMetrics(dm); return dm; } /** The absolute width of the display in pixels. */ public static int getWidth(Context ctx) { return getDisplayMetrics(ctx).widthPixels; } /** The absolute height of the display in pixels. */ public static int getHeight(Context ctx) { return getDisplayMetrics(ctx).heightPixels; } /** The absolute width of the display in pixels based on the real size */ public static int getRealWidth(Context ctx) { if (Build.VERSION.SDK_INT >= 17) { return getRealDisplayMetrics(ctx).widthPixels; } else if (Build.VERSION.SDK_INT >= 13){ int width = -1; try { Display display = getDisplay(ctx); Method method = Display.class.getMethod("getRawWidth"); width = (Integer) method.invoke(display); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return width; } else { return getWidth(ctx); } } /** The absolute height of the display in pixels based on the real size */ public static int getRealHeight(Context ctx) { if (Build.VERSION.SDK_INT >= 17) { return getRealDisplayMetrics(ctx).heightPixels; } else if (Build.VERSION.SDK_INT >= 13){ int height = -1; try { Display display = getDisplay(ctx); Method method = Display.class.getMethod("getRawHeight"); height = (Integer) method.invoke(display); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return height; } else { return getHeight(ctx); } } /** The logical density of the display. */ public static float getDensity(Context ctx) { return getDisplayMetrics(ctx).density; } /** The screen density expressed as dots-per-inch. */ public static float getDensityDpi(Context ctx) { return getRealDisplayMetrics(ctx).densityDpi; } /** * Returns the rotation of the screen from its "natural" orientation. * * @see android.view.Surface#ROTATION_0 * @see android.view.Surface#ROTATION_90 * @see android.view.Surface#ROTATION_180 * @see android.view.Surface#ROTATION_270 */ public static int getRotation (Context ctx) { return getDisplay(ctx).getRotation(); } }
[Screen] Modify getRotation() javadoc
otterlibrary/src/main/java/com/otter/otterlibrary/OScreen.java
[Screen] Modify getRotation() javadoc
Java
apache-2.0
60561fcb08ee73f4eea0624a02737371e034ec67
0
michael-rapp/AndroidMaterialPreferences
package de.mrapp.android.preference; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.widget.EditText; import de.mrapp.android.dialog.MaterialDialogBuilder; public class EditTextPreference extends AbstractDialogPreference { public static class SavedState extends BaseSavedState { public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; public String text; public SavedState(Parcel source) { super(source); text = source.readString(); } public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(text); } }; private EditText editText; private String text; private void initialize() { setPositiveButtonText(android.R.string.ok); setNegativeButtonText(android.R.string.cancel); } public EditTextPreference(final Context context) { super(context); initialize(); } public EditTextPreference(final Context context, final AttributeSet attributeSet) { super(context, attributeSet); initialize(); } public EditTextPreference(final Context context, final AttributeSet attributeSet, final int defStyleAttr) { super(context, attributeSet, defStyleAttr); initialize(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public EditTextPreference(final Context context, final AttributeSet attributeSet, final int defStyleAttr, final int defStyleRes) { super(context, attributeSet, defStyleAttr, defStyleRes); initialize(); } public String getText() { return text; } public void setText(String text) { boolean hasDisabledDependents = shouldDisableDependents(); this.text = text; persistString(text); boolean isDisabelingDependents = shouldDisableDependents(); if (isDisabelingDependents != hasDisabledDependents) { notifyDependencyChange(isDisabelingDependents); } } @Override public boolean shouldDisableDependents() { return TextUtils.isEmpty(getText()) || super.shouldDisableDependents(); } @Override protected void onPrepareDialog(MaterialDialogBuilder dialogBuilder) { editText = (EditText) View.inflate(getContext(), R.layout.edit_text, null); editText.setText(getText()); dialogBuilder.setView(editText); } @Override protected void onDialogClosed(boolean positiveResult) { if (positiveResult) { String newValue = editText.getText().toString(); if (callChangeListener(newValue)) { setText(newValue); } } editText = null; } @Override protected boolean needInputMethod() { return true; } @Override protected Object onGetDefaultValue(TypedArray typedArray, int index) { return typedArray.getString(index); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setText(restoreValue ? getPersistedString(getText()) : (String) defaultValue); } @Override protected Parcelable onSaveInstanceState() { Parcelable parcelable = super.onSaveInstanceState(); if (!isPersistent()) { SavedState savedState = new SavedState(parcelable); savedState.text = getText(); return savedState; } return parcelable; } @Override protected void onRestoreInstanceState(Parcelable state) { if (state != null && state instanceof SavedState) { SavedState savedState = (SavedState) state; setText(savedState.text); super.onRestoreInstanceState(savedState.getSuperState()); } else { super.onRestoreInstanceState(state); } } }
src/de/mrapp/android/preference/EditTextPreference.java
package de.mrapp.android.preference; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.widget.EditText; import de.mrapp.android.dialog.MaterialDialogBuilder; public class EditTextPreference extends AbstractDialogPreference { public static class SavedState extends BaseSavedState { public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; private String text; public SavedState(Parcel source) { super(source); text = source.readString(); } public SavedState(Parcelable superState, String text) { super(superState); this.text = text; } public final String getText() { return text; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(text); } }; private EditText editText; private String text; private void initialize() { setPositiveButtonText(android.R.string.ok); setNegativeButtonText(android.R.string.cancel); } public EditTextPreference(final Context context) { super(context); initialize(); } public EditTextPreference(final Context context, final AttributeSet attributeSet) { super(context, attributeSet); initialize(); } public EditTextPreference(final Context context, final AttributeSet attributeSet, final int defStyleAttr) { super(context, attributeSet, defStyleAttr); initialize(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public EditTextPreference(final Context context, final AttributeSet attributeSet, final int defStyleAttr, final int defStyleRes) { super(context, attributeSet, defStyleAttr, defStyleRes); initialize(); } public String getText() { return text; } public void setText(String text) { boolean hasDisabledDependents = shouldDisableDependents(); this.text = text; persistString(text); boolean isDisabelingDependents = shouldDisableDependents(); if (isDisabelingDependents != hasDisabledDependents) { notifyDependencyChange(isDisabelingDependents); } } @Override public boolean shouldDisableDependents() { return TextUtils.isEmpty(getText()) || super.shouldDisableDependents(); } @Override protected void onPrepareDialog(MaterialDialogBuilder dialogBuilder) { editText = (EditText) View.inflate(getContext(), R.layout.edit_text, null); editText.setText(getText()); dialogBuilder.setView(editText); } @Override protected void onDialogClosed(boolean positiveResult) { if (positiveResult) { String newValue = editText.getText().toString(); if (callChangeListener(newValue)) { setText(newValue); } } editText = null; } @Override protected boolean needInputMethod() { return true; } @Override protected Object onGetDefaultValue(TypedArray typedArray, int index) { return typedArray.getString(index); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setText(restoreValue ? getPersistedString(getText()) : (String) defaultValue); } @Override protected Parcelable onSaveInstanceState() { Parcelable parcelable = super.onSaveInstanceState(); if (!isPersistent()) { SavedState savedState = new SavedState(parcelable, getText()); return savedState; } return parcelable; } @Override protected void onRestoreInstanceState(Parcelable state) { if (state != null && state instanceof SavedState) { SavedState savedState = (SavedState) state; setText(savedState.getText()); super.onRestoreInstanceState(savedState.getSuperState()); } else { super.onRestoreInstanceState(state); } } }
Changed SavedState constructor.
src/de/mrapp/android/preference/EditTextPreference.java
Changed SavedState constructor.
Java
bsd-2-clause
2eda68cb1df5facc231494ff4b70282fa27a42f2
0
scifio/scifio
// // TiffReader.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan, Eric Kjellman and Brian Loranger. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.*; import javax.xml.parsers.*; import loci.formats.*; import org.w3c.dom.*; import org.xml.sax.SAXException; /** * TiffReader is the file format reader for TIFF files, including OME-TIFF. * * @author Curtis Rueden ctrueden at wisc.edu * @author Melissa Linkert linkert at wisc.edu */ public class TiffReader extends BaseTiffReader { // -- Constructor -- /** Constructs a new Tiff reader. */ public TiffReader() { super("Tagged Image File Format", new String[] {"tif", "tiff"}); } // -- Internal TiffReader API methods -- /** * Allows a class which is delegating parsing responsibility to * <code>TiffReader</code> the ability to affect the <code>sizeZ</code> value * that is inserted into the metadata store. * @param zSize the number of optical sections to use when making a call to * {@link loci.formats.MetadataStore#setPixels(Integer, Integer, Integer, * Integer, Integer, Integer, Boolean, String, Integer, Integer)}. */ protected void setSizeZ(int zSize) { if (sizeZ == null) sizeZ = new int[1]; this.sizeZ[0] = zSize; } // -- Internal BaseTiffReader API methods -- /** Parses standard metadata. */ protected void initStandardMetadata() throws FormatException, IOException { super.initStandardMetadata(); String comment = (String) getMeta("Comment"); status("Checking comment style"); // check for OME-XML in TIFF comment (OME-TIFF format) boolean omeTiff = comment != null && comment.indexOf("ome.xsd") >= 0; put("OME-TIFF", omeTiff ? "yes" : "no"); if (omeTiff) { status("Found OME-TIFF: parsing OME-XML"); // convert string to DOM ByteArrayInputStream is = new ByteArrayInputStream(comment.getBytes()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(is); } catch (ParserConfigurationException exc) { } catch (SAXException exc) { } catch (IOException exc) { } // extract TiffData elements from XML Element[] pixels = null; Element[][] tiffData = null; if (doc != null) { NodeList pixelsList = doc.getElementsByTagName("Pixels"); int numSeries = pixelsList.getLength(); Vector v = new Vector(); pixels = new Element[numSeries]; tiffData = new Element[numSeries][]; for (int i=0; i<numSeries; i++) { pixels[i] = (Element) pixelsList.item(i); NodeList list = pixels[i].getChildNodes(); int size = list.getLength(); v.clear(); for (int j=0; j<size; j++) { Node node = list.item(j); if (!(node instanceof Element)) continue; if ("TiffData".equals(node.getNodeName())) v.add(node); } tiffData[i] = new Element[v.size()]; v.copyInto(tiffData[i]); } } // MAJOR HACK : check for OME-XML in the comment of the second IFD // There is a version of WiscScan which writes OME-XML to every IFD, // but with SizeZ and SizeT equal to 1. String s = (String) TiffTools.getIFDValue(ifds[1], TiffTools.IMAGE_DESCRIPTION); boolean isWiscScan = s != null && s.indexOf("ome.xsd") != -1; // extract SizeZ, SizeC and SizeT from XML block if (tiffData != null) { boolean rgb = false; try { rgb = isRGB(currentId); } catch (IOException exc) { throw new FormatException(exc); } sizeX = new int[tiffData.length]; sizeY = new int[tiffData.length]; sizeZ = new int[tiffData.length]; sizeC = new int[tiffData.length]; sizeT = new int[tiffData.length]; pixelType = new int[tiffData.length]; currentOrder = new String[tiffData.length]; orderCertain = new boolean[tiffData.length]; cLengths = new int[tiffData.length][]; cTypes = new String[tiffData.length][]; Arrays.fill(orderCertain, true); for (int i=0; i<tiffData.length; i++) { sizeX[i] = Integer.parseInt(pixels[i].getAttribute("SizeX")); sizeY[i] = Integer.parseInt(pixels[i].getAttribute("SizeY")); sizeZ[i] = Integer.parseInt(pixels[i].getAttribute("SizeZ")); sizeC[i] = Integer.parseInt(pixels[i].getAttribute("SizeC")); int sc = sizeC[i]; if (rgb) sc /= 3; sizeT[i] = Integer.parseInt(pixels[i].getAttribute("SizeT")); pixelType[i] = FormatTools.pixelTypeFromString( pixels[i].getAttribute("PixelType")); if (pixelType[i] == FormatTools.INT8 || pixelType[i] == FormatTools.INT16 || pixelType[i] == FormatTools.INT32) { pixelType[i]++; } // MAJOR HACK : adjust SizeT to match the number of IFDs, if this // file was written by a buggy version of WiscScan if (isWiscScan) sizeT[i] = numImages; currentOrder[i] = pixels[i].getAttribute("DimensionOrder"); orderCertain[i] = true; boolean[][][] zct = new boolean[sizeZ[i]][sc][sizeT[i]]; for (int j=0; j<tiffData[i].length; j++) { String aIfd = tiffData[i][j].getAttribute("IFD"); String aFirstZ = tiffData[i][j].getAttribute("FirstZ"); String aFirstT = tiffData[i][j].getAttribute("FirstT"); String aFirstC = tiffData[i][j].getAttribute("FirstC"); String aNumPlanes = tiffData[i][j].getAttribute("NumPlanes"); boolean nullIfd = aIfd == null || "".equals(aIfd); boolean nullFirstZ = aFirstZ == null || "".equals(aFirstZ); boolean nullFirstT = aFirstT == null || "".equals(aFirstT); boolean nullFirstC = aFirstC == null || "".equals(aFirstC); boolean nullNumPlanes = aNumPlanes == null || "".equals(aNumPlanes); int ifd = nullIfd ? 0 : Integer.parseInt(aIfd); int firstZ = nullFirstZ ? 0 : Integer.parseInt(aFirstZ); int firstT = nullFirstT ? 0 : Integer.parseInt(aFirstT); int firstC = nullFirstC ? 0 : Integer.parseInt(aFirstC); int numPlanes = nullNumPlanes ? (nullIfd ? numImages : 1) : Integer.parseInt(aNumPlanes); // populate ZCT matrix char d1st = currentOrder[i].charAt(2); char d2nd = currentOrder[i].charAt(3); int z = firstZ, t = firstT, c = firstC; for (int k=0; k<numPlanes; k++) { zct[z][c][t] = true; switch (d1st) { case 'Z': z++; if (z >= sizeZ[i]) { z = 0; switch (d2nd) { case 'T': t++; if (t >= sizeT[i]) { t = 0; c++; } break; case 'C': c++; if (c >= sc) { c = 0; t++; } break; } } break; case 'T': t++; if (t >= sizeT[i]) { t = 0; switch (d2nd) { case 'Z': z++; if (z >= sizeZ[i]) { z = 0; c++; } break; case 'C': c++; if (c >= sc) { c = 0; z++; } break; } } break; case 'C': c++; if (c >= sc) { c = 0; switch (d2nd) { case 'Z': z++; if (z >= sizeZ[i]) { z = 0; t++; } break; case 'T': t++; if (t >= sizeT[i]) { t = 0; z++; } break; } } break; } } } // analyze ZCT matrix to determine best SizeZ, SizeC and SizeT // for now, we only handle certain special cases: boolean success = false; int theZ, theT, theC; // 1) all Z, all T, all C success = true; for (int z=0; z<sizeZ[i] && success; z++) { for (int t=0; t<sizeT[i] && success; t++) { for (int c=0; c<sc && success; c++) { if (!zct[z][c][t]) success = false; } } } if (success) { // NB: sizes are already correct; no corrections necessary continue; } // 2) single Z, all T, all C success = true; theZ = -1; for (int z=0; z<sizeZ[i] && success; z++) { if (zct[z][0][0]) { if (theZ < 0) theZ = z; else success = false; } boolean state = theZ == z; for (int t=0; t<sizeT[i] && success; t++) { for (int c=0; c<sc && success; c++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeZ[i] = 1; continue; } // 3) all Z, single T, all C success = true; theT = -1; for (int t=0; t<sizeT[i] && success; t++) { if (zct[0][0][t]) { if (theT < 0) theT = t; else success = false; } boolean state = theT == t; for (int z=0; z<sizeZ[i] && success; z++) { for (int c=0; c<sc && success; c++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeT[i] = 1; continue; } // 4) all Z, all T, single C success = true; theC = -1; for (int c=0; c<sc && success; c++) { if (zct[0][c][0]) { if (theC < 0) theC = c; else success = false; } boolean state = theC == c; for (int z=0; z<sizeZ[i] && success; z++) { for (int t=0; t<sizeT[i] && success; t++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeC[i] = 1; continue; } // 5) single Z, single T, all C success = true; theZ = -1; theT = -1; for (int z=0; z<sizeZ[i] && success; z++) { for (int t=0; t<sizeT[i] && success; t++) { if (zct[z][0][t]) { if (theZ < 0 && theT < 0) { theZ = z; theT = t; } else success = false; } boolean state = theZ == z && theT == t; for (int c=0; c<sc && success; c++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeZ[i] = sizeT[i] = 1; continue; } // 6) single Z, all T, single C success = true; theZ = -1; theC = -1; for (int z=0; z<sizeZ[i] && success; z++) { for (int c=0; c<sc && success; c++) { if (zct[z][c][0]) { if (theZ < 0 && theC < 0) { theZ = z; theC = c; } else success = false; } boolean state = theZ == z && theC == c; for (int t=0; t<sizeT[i] && success; t++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeZ[i] = sizeC[i] = 1; continue; } // 7) all Z, single T, single C success = true; theT = -1; theC = -1; for (int t=0; t<sizeT[i] && success; t++) { for (int c=0; c<sc && success; c++) { if (zct[0][c][t]) { if (theC < 0 && theT < 0) { theC = c; theT = t; } else success = false; } boolean state = theC == c && theT == t; for (int z=0; z<sizeZ[i] && success; z++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeT[i] = sizeC[i] = 1; continue; } // 8) single Z, single T, single C success = true; theZ = -1; theT = -1; theC = -1; int count = 0; for (int z=0; z<sizeZ[i] && success; z++) { for (int t=0; t<sizeT[i] && success; t++) { for (int c=0; c<sc && success; c++) { if (zct[z][c][t]) { count++; if (count > 1) success = false; } } } } if (success) { sizeZ[i] = sizeT[i] = sizeC[i] = 1; continue; } // no easy way to chop up TiffData mappings into regular ZCT dims throw new FormatException("Unsupported ZCT index mapping"); } } } else if (ifds.length > 1) orderCertain[0] = false; // check for ImageJ-style TIFF comment boolean ij = comment != null && comment.startsWith("ImageJ="); if (ij) { int nl = comment.indexOf("\n"); put("ImageJ", nl < 0 ? comment.substring(7) : comment.substring(7, nl)); metadata.remove("Comment"); } // check for Improvision-style TIFF comment boolean iv = comment != null && comment.startsWith("[Improvision Data]\n"); put("Improvision", iv ? "yes" : "no"); if (iv) { // parse key/value pairs StringTokenizer st = new StringTokenizer(comment, "\n"); while (st.hasMoreTokens()) { String line = st.nextToken(); int equals = line.indexOf("="); if (equals < 0) continue; String key = line.substring(0, equals); String value = line.substring(equals + 1); addMeta(key, value); } metadata.remove("Comment"); } // check for MetaMorph-style TIFF comment boolean metamorph = comment != null && getMeta("Software") != null && ((String) getMeta("Software")).indexOf("MetaMorph") != -1; put("MetaMorph", metamorph ? "yes" : "no"); if (metamorph) { // parse key/value pairs StringTokenizer st = new StringTokenizer(comment, "\n"); while (st.hasMoreTokens()) { String line = st.nextToken(); int colon = line.indexOf(":"); if (colon < 0) { addMeta("Comment", line); continue; } String key = line.substring(0, colon); String value = line.substring(colon + 1); addMeta(key, value); } } } /** Parses OME-XML metadata. */ protected void initMetadataStore() { // check for OME-XML in TIFF comment (OME-TIFF format) // we need an extra check to make sure that any XML we find is indeed // OME-XML (and not some other XML variant) String comment = (String) getMeta("Comment"); if (comment != null && comment.indexOf("ome.xsd") >= 0) { metadata.remove("Comment"); boolean isOMEXML; try { Class omexmlMeta = Class.forName("loci.formats.ome.OMEXMLMetadataStore"); isOMEXML = omexmlMeta.isAssignableFrom(metadataStore.getClass()); } catch (Throwable t) { isOMEXML = false; } if (isOMEXML) { ReflectedUniverse r = new ReflectedUniverse(); try { r.exec("import loci.formats.ome.OMEXMLMetadataStore"); r.setVar("xmlStore", metadataStore); r.setVar("comment", comment); r.exec("xmlStore.createRoot(comment)"); return; } catch (ReflectException exc) { // OME Java probably not available; ignore this error } } } super.initMetadataStore(); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#getSeriesCount(String) */ public int getSeriesCount(String id) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); return currentOrder.length; } // -- Main method -- public static void main(String[] args) throws FormatException, IOException { new TiffReader().testRead(args); } }
loci/formats/in/TiffReader.java
// // TiffReader.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan, Eric Kjellman and Brian Loranger. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.*; import javax.xml.parsers.*; import loci.formats.*; import loci.formats.ome.OMEXMLMetadataStore; import org.w3c.dom.*; import org.xml.sax.SAXException; /** * TiffReader is the file format reader for TIFF files, including OME-TIFF. * * @author Curtis Rueden ctrueden at wisc.edu * @author Melissa Linkert linkert at wisc.edu */ public class TiffReader extends BaseTiffReader { // -- Constructor -- /** Constructs a new Tiff reader. */ public TiffReader() { super("Tagged Image File Format", new String[] {"tif", "tiff"}); } // -- Internal TiffReader API methods -- /** * Allows a class which is delegating parsing responsibility to * <code>TiffReader</code> the ability to affect the <code>sizeZ</code> value * that is inserted into the metadata store. * @param zSize the number of optical sections to use when making a call to * {@link loci.formats.MetadataStore#setPixels(Integer, Integer, Integer, * Integer, Integer, Integer, Boolean, String, Integer, Integer)}. */ protected void setSizeZ(int zSize) { if (sizeZ == null) sizeZ = new int[1]; this.sizeZ[0] = zSize; } // -- Internal BaseTiffReader API methods -- /** Parses standard metadata. */ protected void initStandardMetadata() throws FormatException, IOException { super.initStandardMetadata(); String comment = (String) getMeta("Comment"); status("Checking comment style"); // check for OME-XML in TIFF comment (OME-TIFF format) boolean omeTiff = comment != null && comment.indexOf("ome.xsd") >= 0; put("OME-TIFF", omeTiff ? "yes" : "no"); if (omeTiff) { status("Found OME-TIFF: parsing OME-XML"); // convert string to DOM ByteArrayInputStream is = new ByteArrayInputStream(comment.getBytes()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(is); } catch (ParserConfigurationException exc) { } catch (SAXException exc) { } catch (IOException exc) { } // extract TiffData elements from XML Element[] pixels = null; Element[][] tiffData = null; if (doc != null) { NodeList pixelsList = doc.getElementsByTagName("Pixels"); int numSeries = pixelsList.getLength(); Vector v = new Vector(); pixels = new Element[numSeries]; tiffData = new Element[numSeries][]; for (int i=0; i<numSeries; i++) { pixels[i] = (Element) pixelsList.item(i); NodeList list = pixels[i].getChildNodes(); int size = list.getLength(); v.clear(); for (int j=0; j<size; j++) { Node node = list.item(j); if (!(node instanceof Element)) continue; if ("TiffData".equals(node.getNodeName())) v.add(node); } tiffData[i] = new Element[v.size()]; v.copyInto(tiffData[i]); } } // MAJOR HACK : check for OME-XML in the comment of the second IFD // There is a version of WiscScan which writes OME-XML to every IFD, // but with SizeZ and SizeT equal to 1. String s = (String) TiffTools.getIFDValue(ifds[1], TiffTools.IMAGE_DESCRIPTION); boolean isWiscScan = s != null && s.indexOf("ome.xsd") != -1; // extract SizeZ, SizeC and SizeT from XML block if (tiffData != null) { boolean rgb = false; try { rgb = isRGB(currentId); } catch (IOException exc) { throw new FormatException(exc); } sizeX = new int[tiffData.length]; sizeY = new int[tiffData.length]; sizeZ = new int[tiffData.length]; sizeC = new int[tiffData.length]; sizeT = new int[tiffData.length]; pixelType = new int[tiffData.length]; currentOrder = new String[tiffData.length]; orderCertain = new boolean[tiffData.length]; cLengths = new int[tiffData.length][]; cTypes = new String[tiffData.length][]; Arrays.fill(orderCertain, true); for (int i=0; i<tiffData.length; i++) { sizeX[i] = Integer.parseInt(pixels[i].getAttribute("SizeX")); sizeY[i] = Integer.parseInt(pixels[i].getAttribute("SizeY")); sizeZ[i] = Integer.parseInt(pixels[i].getAttribute("SizeZ")); sizeC[i] = Integer.parseInt(pixels[i].getAttribute("SizeC")); int sc = sizeC[i]; if (rgb) sc /= 3; sizeT[i] = Integer.parseInt(pixels[i].getAttribute("SizeT")); pixelType[i] = FormatTools.pixelTypeFromString( pixels[i].getAttribute("PixelType")); if (pixelType[i] == FormatTools.INT8 || pixelType[i] == FormatTools.INT16 || pixelType[i] == FormatTools.INT32) { pixelType[i]++; } // MAJOR HACK : adjust SizeT to match the number of IFDs, if this // file was written by a buggy version of WiscScan if (isWiscScan) sizeT[i] = numImages; currentOrder[i] = pixels[i].getAttribute("DimensionOrder"); orderCertain[i] = true; boolean[][][] zct = new boolean[sizeZ[i]][sc][sizeT[i]]; for (int j=0; j<tiffData[i].length; j++) { String aIfd = tiffData[i][j].getAttribute("IFD"); String aFirstZ = tiffData[i][j].getAttribute("FirstZ"); String aFirstT = tiffData[i][j].getAttribute("FirstT"); String aFirstC = tiffData[i][j].getAttribute("FirstC"); String aNumPlanes = tiffData[i][j].getAttribute("NumPlanes"); boolean nullIfd = aIfd == null || "".equals(aIfd); boolean nullFirstZ = aFirstZ == null || "".equals(aFirstZ); boolean nullFirstT = aFirstT == null || "".equals(aFirstT); boolean nullFirstC = aFirstC == null || "".equals(aFirstC); boolean nullNumPlanes = aNumPlanes == null || "".equals(aNumPlanes); int ifd = nullIfd ? 0 : Integer.parseInt(aIfd); int firstZ = nullFirstZ ? 0 : Integer.parseInt(aFirstZ); int firstT = nullFirstT ? 0 : Integer.parseInt(aFirstT); int firstC = nullFirstC ? 0 : Integer.parseInt(aFirstC); int numPlanes = nullNumPlanes ? (nullIfd ? numImages : 1) : Integer.parseInt(aNumPlanes); // populate ZCT matrix char d1st = currentOrder[i].charAt(2); char d2nd = currentOrder[i].charAt(3); int z = firstZ, t = firstT, c = firstC; for (int k=0; k<numPlanes; k++) { zct[z][c][t] = true; switch (d1st) { case 'Z': z++; if (z >= sizeZ[i]) { z = 0; switch (d2nd) { case 'T': t++; if (t >= sizeT[i]) { t = 0; c++; } break; case 'C': c++; if (c >= sc) { c = 0; t++; } break; } } break; case 'T': t++; if (t >= sizeT[i]) { t = 0; switch (d2nd) { case 'Z': z++; if (z >= sizeZ[i]) { z = 0; c++; } break; case 'C': c++; if (c >= sc) { c = 0; z++; } break; } } break; case 'C': c++; if (c >= sc) { c = 0; switch (d2nd) { case 'Z': z++; if (z >= sizeZ[i]) { z = 0; t++; } break; case 'T': t++; if (t >= sizeT[i]) { t = 0; z++; } break; } } break; } } } // analyze ZCT matrix to determine best SizeZ, SizeC and SizeT // for now, we only handle certain special cases: boolean success = false; int theZ, theT, theC; // 1) all Z, all T, all C success = true; for (int z=0; z<sizeZ[i] && success; z++) { for (int t=0; t<sizeT[i] && success; t++) { for (int c=0; c<sc && success; c++) { if (!zct[z][c][t]) success = false; } } } if (success) { // NB: sizes are already correct; no corrections necessary continue; } // 2) single Z, all T, all C success = true; theZ = -1; for (int z=0; z<sizeZ[i] && success; z++) { if (zct[z][0][0]) { if (theZ < 0) theZ = z; else success = false; } boolean state = theZ == z; for (int t=0; t<sizeT[i] && success; t++) { for (int c=0; c<sc && success; c++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeZ[i] = 1; continue; } // 3) all Z, single T, all C success = true; theT = -1; for (int t=0; t<sizeT[i] && success; t++) { if (zct[0][0][t]) { if (theT < 0) theT = t; else success = false; } boolean state = theT == t; for (int z=0; z<sizeZ[i] && success; z++) { for (int c=0; c<sc && success; c++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeT[i] = 1; continue; } // 4) all Z, all T, single C success = true; theC = -1; for (int c=0; c<sc && success; c++) { if (zct[0][c][0]) { if (theC < 0) theC = c; else success = false; } boolean state = theC == c; for (int z=0; z<sizeZ[i] && success; z++) { for (int t=0; t<sizeT[i] && success; t++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeC[i] = 1; continue; } // 5) single Z, single T, all C success = true; theZ = -1; theT = -1; for (int z=0; z<sizeZ[i] && success; z++) { for (int t=0; t<sizeT[i] && success; t++) { if (zct[z][0][t]) { if (theZ < 0 && theT < 0) { theZ = z; theT = t; } else success = false; } boolean state = theZ == z && theT == t; for (int c=0; c<sc && success; c++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeZ[i] = sizeT[i] = 1; continue; } // 6) single Z, all T, single C success = true; theZ = -1; theC = -1; for (int z=0; z<sizeZ[i] && success; z++) { for (int c=0; c<sc && success; c++) { if (zct[z][c][0]) { if (theZ < 0 && theC < 0) { theZ = z; theC = c; } else success = false; } boolean state = theZ == z && theC == c; for (int t=0; t<sizeT[i] && success; t++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeZ[i] = sizeC[i] = 1; continue; } // 7) all Z, single T, single C success = true; theT = -1; theC = -1; for (int t=0; t<sizeT[i] && success; t++) { for (int c=0; c<sc && success; c++) { if (zct[0][c][t]) { if (theC < 0 && theT < 0) { theC = c; theT = t; } else success = false; } boolean state = theC == c && theT == t; for (int z=0; z<sizeZ[i] && success; z++) { if (zct[z][c][t] != state) success = false; } } } if (success) { sizeT[i] = sizeC[i] = 1; continue; } // 8) single Z, single T, single C success = true; theZ = -1; theT = -1; theC = -1; int count = 0; for (int z=0; z<sizeZ[i] && success; z++) { for (int t=0; t<sizeT[i] && success; t++) { for (int c=0; c<sc && success; c++) { if (zct[z][c][t]) { count++; if (count > 1) success = false; } } } } if (success) { sizeZ[i] = sizeT[i] = sizeC[i] = 1; continue; } // no easy way to chop up TiffData mappings into regular ZCT dims throw new FormatException("Unsupported ZCT index mapping"); } } } else if (ifds.length > 1) orderCertain[0] = false; // check for ImageJ-style TIFF comment boolean ij = comment != null && comment.startsWith("ImageJ="); if (ij) { int nl = comment.indexOf("\n"); put("ImageJ", nl < 0 ? comment.substring(7) : comment.substring(7, nl)); metadata.remove("Comment"); } // check for Improvision-style TIFF comment boolean iv = comment != null && comment.startsWith("[Improvision Data]\n"); put("Improvision", iv ? "yes" : "no"); if (iv) { // parse key/value pairs StringTokenizer st = new StringTokenizer(comment, "\n"); while (st.hasMoreTokens()) { String line = st.nextToken(); int equals = line.indexOf("="); if (equals < 0) continue; String key = line.substring(0, equals); String value = line.substring(equals + 1); addMeta(key, value); } metadata.remove("Comment"); } // check for MetaMorph-style TIFF comment boolean metamorph = comment != null && getMeta("Software") != null && ((String) getMeta("Software")).indexOf("MetaMorph") != -1; put("MetaMorph", metamorph ? "yes" : "no"); if (metamorph) { // parse key/value pairs StringTokenizer st = new StringTokenizer(comment, "\n"); while (st.hasMoreTokens()) { String line = st.nextToken(); int colon = line.indexOf(":"); if (colon < 0) { addMeta("Comment", line); continue; } String key = line.substring(0, colon); String value = line.substring(colon + 1); addMeta(key, value); } } } /** Parses OME-XML metadata. */ protected void initMetadataStore() { // check for OME-XML in TIFF comment (OME-TIFF format) // we need an extra check to make sure that any XML we find is indeed // OME-XML (and not some other XML variant) String comment = (String) getMeta("Comment"); if (comment != null && comment.indexOf("ome.xsd") >= 0) { metadata.remove("Comment"); if (metadataStore instanceof OMEXMLMetadataStore) { OMEXMLMetadataStore xmlStore = (OMEXMLMetadataStore) metadataStore; xmlStore.createRoot(comment); return; } } super.initMetadataStore(); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#getSeriesCount(String) */ public int getSeriesCount(String id) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); return currentOrder.length; } // -- Main method -- public static void main(String[] args) throws FormatException, IOException { new TiffReader().testRead(args); } }
Remove loci.formats.ome dependencies from TiffReader.
loci/formats/in/TiffReader.java
Remove loci.formats.ome dependencies from TiffReader.
Java
bsd-2-clause
ddfb0be1588593027019b82fc4317a62517070dc
0
chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio
/* * Copyright (c) 2008 SRA International, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme.renderer.jogl; import java.nio.FloatBuffer; import java.nio.IntBuffer; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import com.jme.util.geom.BufferUtils; /** * This class collects all of the settings for a specific * {@link javax.media.opengl.GLContext}, avoiding unnecessary communications * with the graphics hardware for settings which won't change. The class is * patterned after the LWJGL {@link org.lwjgl.opengl.ContextCapabilities} * implementation, but goes the additional step of accessing common * <code>integer</code> and <code>float</code> values. This instance is not * immutable, in order to allow the values to be updated whenever the device * associated with the {@link javax.media.opengl.GLDrawable} has changed. * * @author Steve Vaughan * @see org.lwjgl.opengl.ContextCapabilities */ public final class JOGLContextCapabilities { private final IntBuffer intBuf = BufferUtils.createIntBuffer(16); // TODO Due to JOGL buffer check, you can't use smaller sized // buffers (min_size = 16) for glGetFloat(). private final FloatBuffer floatBuf = BufferUtils.createFloatBuffer(16); public boolean GL_VERSION_1_1; public boolean GL_VERSION_1_2; public boolean GL_VERSION_1_3; public boolean GL_VERSION_1_4; public boolean GL_VERSION_1_5; public boolean GL_VERSION_2_0; public boolean GL_VERSION_2_1; public boolean GL_VERSION_3_0; public boolean GL_ARB_imaging; public boolean GL_EXT_blend_func_separate; public boolean GL_EXT_blend_equation_separate; public boolean GL_EXT_blend_minmax; public boolean GL_EXT_blend_subtract; public boolean GL_ARB_depth_texture; public boolean GL_EXT_fog_coord; public boolean GL_EXT_compiled_vertex_array; public boolean GL_ARB_fragment_program; public boolean GL_ARB_shader_objects; public boolean GL_ARB_fragment_shader; public boolean GL_ARB_vertex_shader; public boolean GL_ARB_shading_language_100; public boolean GL_EXT_stencil_two_side; public boolean GL_EXT_stencil_wrap; public boolean GL_ARB_multitexture; public boolean GL_ARB_texture_env_dot3; public boolean GL_ARB_texture_env_combine; public boolean GL_SGIS_generate_mipmap; public boolean GL_ARB_vertex_program; public boolean GL_ARB_texture_mirrored_repeat; public boolean GL_EXT_texture_mirror_clamp; public boolean GL_ARB_texture_border_clamp; public boolean GL_EXT_texture_compression_s3tc; public boolean GL_EXT_texture_3d; public boolean GL_ARB_texture_cube_map; public boolean GL_EXT_texture_filter_anisotropic; public boolean GL_ARB_texture_non_power_of_two; public boolean GL_ARB_texture_rectangle; public int GL_MAX_TEXTURE_UNITS; public int GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB; public int GL_MAX_TEXTURE_IMAGE_UNITS_ARB; public int GL_MAX_TEXTURE_COORDS_ARB; public float GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT; public int GL_MAX_VERTEX_ATTRIBS_ARB; public int GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB; public int GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB; public int GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB; public int GL_MAX_VARYING_FLOATS_ARB; public String GL_SHADING_LANGUAGE_VERSION_ARB; public boolean GL_ARB_vertex_buffer_object; public boolean GL_ARB_shadow; public JOGLContextCapabilities(GLAutoDrawable autodrawable) { init(autodrawable.getGL()); } public JOGLContextCapabilities(final GL gl) { init(gl); } public void init(final GL gl) { // See Renderer GL_ARB_vertex_buffer_object = gl .isExtensionAvailable("GL_ARB_vertex_buffer_object"); GL_VERSION_1_1 = gl.isExtensionAvailable("GL_VERSION_1_1"); GL_VERSION_1_2 = gl.isExtensionAvailable("GL_VERSION_1_2"); GL_VERSION_1_3 = gl.isExtensionAvailable("GL_VERSION_1_3"); GL_VERSION_1_4 = gl.isExtensionAvailable("GL_VERSION_1_4"); GL_VERSION_1_5 = gl.isExtensionAvailable("GL_VERSION_1_5"); GL_VERSION_2_0 = gl.isExtensionAvailable("GL_VERSION_2_0"); GL_VERSION_2_1 = gl.isExtensionAvailable("GL_VERSION_2_1"); GL_VERSION_3_0 = gl.isExtensionAvailable("GL_VERSION_3_0"); // See BlendState GL_ARB_imaging = gl.isExtensionAvailable("GL_ARB_imaging"); GL_EXT_blend_func_separate = gl .isExtensionAvailable("GL_EXT_blend_func_separate"); GL_EXT_blend_equation_separate = gl .isExtensionAvailable("GL_EXT_blend_equation_separate"); GL_EXT_blend_minmax = gl.isExtensionAvailable("GL_EXT_blend_minmax"); GL_EXT_blend_subtract = gl .isExtensionAvailable("GL_EXT_blend_subtract"); // See FogState GL_EXT_fog_coord = gl.isExtensionAvailable("GL_EXT_fog_coord"); // See FragmentProgramState GL_ARB_fragment_program = gl .isExtensionAvailable("GL_ARB_fragment_program"); // See ShaderObjectsState GL_ARB_shader_objects = gl .isExtensionAvailable("GL_ARB_shader_objects"); GL_ARB_fragment_shader = gl .isExtensionAvailable("GL_ARB_fragment_shader"); GL_ARB_vertex_shader = gl.isExtensionAvailable("GL_ARB_vertex_shader"); GL_ARB_shading_language_100 = gl .isExtensionAvailable("GL_ARB_shading_language_100"); if(GL_ARB_shading_language_100){ GL_SHADING_LANGUAGE_VERSION_ARB = gl .glGetString(GL.GL_SHADING_LANGUAGE_VERSION_ARB); } else { GL_SHADING_LANGUAGE_VERSION_ARB = ""; } // See TextureState GL_ARB_depth_texture = gl.isExtensionAvailable("GL_ARB_depth_texture"); GL_ARB_shadow = gl.isExtensionAvailable("GL_ARB_shadow"); if(gl.isExtensionAvailable( "GL_ARB_vertex_shader" )) { gl.glGetIntegerv(GL.GL_MAX_VERTEX_ATTRIBS_ARB, intBuf); GL_MAX_VERTEX_ATTRIBS_ARB = intBuf.get(0); gl.glGetIntegerv(GL.GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, intBuf); GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB = intBuf.get(0); gl.glGetIntegerv(GL.GL_MAX_VARYING_FLOATS_ARB, intBuf); GL_MAX_VARYING_FLOATS_ARB = intBuf.get(0); gl.glGetIntegerv(GL.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, intBuf); GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB = intBuf.get(0); gl.glGetIntegerv(GL.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, intBuf); GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB = intBuf.get(0); gl.glGetIntegerv(GL.GL_MAX_TEXTURE_IMAGE_UNITS_ARB, intBuf); GL_MAX_TEXTURE_IMAGE_UNITS_ARB = intBuf.get(0); gl.glGetIntegerv(GL.GL_MAX_TEXTURE_COORDS_ARB, intBuf); GL_MAX_TEXTURE_COORDS_ARB = intBuf.get(0); } else { GL_MAX_VERTEX_ATTRIBS_ARB = 0; GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB = 0; GL_MAX_VARYING_FLOATS_ARB = 0; GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB = 0; GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB = 0; GL_MAX_TEXTURE_IMAGE_UNITS_ARB = 0; GL_MAX_TEXTURE_COORDS_ARB = 0; } if( gl.isExtensionAvailable( "GL_ARB_fragment_shader" )) { gl.glGetIntegerv(GL.GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, intBuf); GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB = intBuf.get(0); } else { GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB = 0; } if( gl.isExtensionAvailable( "GL_EXT_texture_filter_anisotropic" )) { // FIXME I don't think this was necessary: floatBuf.rewind(); gl.glGetFloatv(GL.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, floatBuf); GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = floatBuf.get(0); } else { GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0; } // See StencilState GL_EXT_stencil_two_side = gl .isExtensionAvailable("GL_EXT_stencil_two_side"); GL_EXT_stencil_wrap = gl.isExtensionAvailable("GL_EXT_stencil_wrap"); // See TextureState GL_ARB_multitexture = gl.isExtensionAvailable("GL_ARB_multitexture"); if(GL_ARB_multitexture) { gl.glGetIntegerv(GL.GL_MAX_TEXTURE_UNITS, intBuf); GL_MAX_TEXTURE_UNITS = intBuf.get(0); } else { GL_MAX_TEXTURE_UNITS = 1; } GL_ARB_texture_env_dot3 = gl .isExtensionAvailable("GL_ARB_texture_env_dot3"); GL_ARB_texture_env_combine = gl .isExtensionAvailable("GL_ARB_texture_env_combine"); GL_SGIS_generate_mipmap = gl .isExtensionAvailable("GL_SGIS_generate_mipmap"); GL_EXT_texture_compression_s3tc = gl .isExtensionAvailable("GL_EXT_texture_compression_s3tc"); GL_EXT_texture_3d = gl.isExtensionAvailable("GL_EXT_texture_3d"); GL_ARB_texture_cube_map = gl .isExtensionAvailable("GL_ARB_texture_cube_map"); GL_EXT_texture_filter_anisotropic = gl .isExtensionAvailable("GL_EXT_texture_filter_anisotropic"); GL_ARB_texture_non_power_of_two = gl .isExtensionAvailable("GL_ARB_texture_non_power_of_two"); GL_ARB_texture_rectangle = gl .isExtensionAvailable("GL_ARB_texture_rectangle"); // See VertexProgram GL_ARB_vertex_program = gl .isExtensionAvailable("GL_ARB_vertex_program"); // See TextureStateRecord GL_ARB_texture_mirrored_repeat = gl .isExtensionAvailable("GL_ARB_texture_mirrored_repeat"); GL_EXT_texture_mirror_clamp = gl .isExtensionAvailable("GL_EXT_texture_mirror_clamp"); GL_ARB_texture_border_clamp = gl .isExtensionAvailable("GL_ARB_texture_border_clamp"); GL_EXT_compiled_vertex_array = gl.isExtensionAvailable("GL_EXT_compiled_vertex_array"); } }
src/com/jme/renderer/jogl/JOGLContextCapabilities.java
/* * Copyright (c) 2008 SRA International, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme.renderer.jogl; import java.nio.FloatBuffer; import java.nio.IntBuffer; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLException; import com.jme.util.geom.BufferUtils; /** * This class collects all of the settings for a specific * {@link javax.media.opengl.GLContext}, avoiding unnecessary communications * with the graphics hardware for settings which won't change. The class is * patterned after the LWJGL {@link org.lwjgl.opengl.ContextCapabilities} * implementation, but goes the additional step of accessing common * <code>integer</code> and <code>float</code> values. This instance is not * immutable, in order to allow the values to be updated whenever the device * associated with the {@link javax.media.opengl.GLDrawable} has changed. * * @author Steve Vaughan * @see org.lwjgl.opengl.ContextCapabilities */ public final class JOGLContextCapabilities { private final IntBuffer intBuf = BufferUtils.createIntBuffer(16); // TODO Due to JOGL buffer check, you can't use smaller sized // buffers (min_size = 16) for glGetFloat(). private final FloatBuffer floatBuf = BufferUtils.createFloatBuffer(16); public boolean GL_VERSION_1_1; public boolean GL_VERSION_1_2; public boolean GL_VERSION_1_3; public boolean GL_VERSION_1_4; public boolean GL_VERSION_1_5; public boolean GL_VERSION_2_0; public boolean GL_VERSION_2_1; public boolean GL_VERSION_3_0; public boolean GL_ARB_imaging; public boolean GL_EXT_blend_func_separate; public boolean GL_EXT_blend_equation_separate; public boolean GL_EXT_blend_minmax; public boolean GL_EXT_blend_subtract; public boolean GL_ARB_depth_texture; public boolean GL_EXT_fog_coord; public boolean GL_EXT_compiled_vertex_array; public boolean GL_ARB_fragment_program; public boolean GL_ARB_shader_objects; public boolean GL_ARB_fragment_shader; public boolean GL_ARB_vertex_shader; public boolean GL_ARB_shading_language_100; public boolean GL_EXT_stencil_two_side; public boolean GL_EXT_stencil_wrap; public boolean GL_ARB_multitexture; public boolean GL_ARB_texture_env_dot3; public boolean GL_ARB_texture_env_combine; public boolean GL_SGIS_generate_mipmap; public boolean GL_ARB_vertex_program; public boolean GL_ARB_texture_mirrored_repeat; public boolean GL_EXT_texture_mirror_clamp; public boolean GL_ARB_texture_border_clamp; public boolean GL_EXT_texture_compression_s3tc; public boolean GL_EXT_texture_3d; public boolean GL_ARB_texture_cube_map; public boolean GL_EXT_texture_filter_anisotropic; public boolean GL_ARB_texture_non_power_of_two; public boolean GL_ARB_texture_rectangle; public int GL_MAX_TEXTURE_UNITS; public int GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB; public int GL_MAX_TEXTURE_IMAGE_UNITS_ARB; public int GL_MAX_TEXTURE_COORDS_ARB; public float GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT; public int GL_MAX_VERTEX_ATTRIBS_ARB; public int GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB; public int GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB; public int GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB; public int GL_MAX_VARYING_FLOATS_ARB; public String GL_SHADING_LANGUAGE_VERSION_ARB; public boolean GL_ARB_vertex_buffer_object; public boolean GL_ARB_shadow; public JOGLContextCapabilities(GLAutoDrawable autodrawable) { init(autodrawable.getGL()); } public JOGLContextCapabilities(final GL gl) { init(gl); } public void init(final GL gl) { // See Renderer GL_ARB_vertex_buffer_object = gl .isExtensionAvailable("GL_ARB_vertex_buffer_object"); GL_VERSION_1_1 = gl.isExtensionAvailable("GL_VERSION_1_1"); GL_VERSION_1_2 = gl.isExtensionAvailable("GL_VERSION_1_2"); GL_VERSION_1_3 = gl.isExtensionAvailable("GL_VERSION_1_3"); GL_VERSION_1_4 = gl.isExtensionAvailable("GL_VERSION_1_4"); GL_VERSION_1_5 = gl.isExtensionAvailable("GL_VERSION_1_5"); GL_VERSION_2_0 = gl.isExtensionAvailable("GL_VERSION_2_0"); GL_VERSION_2_1 = gl.isExtensionAvailable("GL_VERSION_2_1"); GL_VERSION_3_0 = gl.isExtensionAvailable("GL_VERSION_3_0"); // See BlendState GL_ARB_imaging = gl.isExtensionAvailable("GL_ARB_imaging"); GL_EXT_blend_func_separate = gl .isExtensionAvailable("GL_EXT_blend_func_separate"); GL_EXT_blend_equation_separate = gl .isExtensionAvailable("GL_EXT_blend_equation_separate"); GL_EXT_blend_minmax = gl.isExtensionAvailable("GL_EXT_blend_minmax"); GL_EXT_blend_subtract = gl .isExtensionAvailable("GL_EXT_blend_subtract"); // See FogState GL_EXT_fog_coord = gl.isExtensionAvailable("GL_EXT_fog_coord"); // See FragmentProgramState GL_ARB_fragment_program = gl .isExtensionAvailable("GL_ARB_fragment_program"); // See ShaderObjectsState GL_ARB_shader_objects = gl .isExtensionAvailable("GL_ARB_shader_objects"); GL_ARB_fragment_shader = gl .isExtensionAvailable("GL_ARB_fragment_shader"); GL_ARB_vertex_shader = gl.isExtensionAvailable("GL_ARB_vertex_shader"); GL_ARB_shading_language_100 = gl .isExtensionAvailable("GL_ARB_shading_language_100"); // See TextureState GL_ARB_depth_texture = gl.isExtensionAvailable("GL_ARB_depth_texture"); GL_ARB_shadow = gl.isExtensionAvailable("GL_ARB_shadow"); try { gl.glGetIntegerv(GL.GL_MAX_VERTEX_ATTRIBS_ARB, intBuf); GL_MAX_VERTEX_ATTRIBS_ARB = intBuf.get(0); } catch(GLException gle) { GL_MAX_VERTEX_ATTRIBS_ARB=0; } try { gl.glGetIntegerv(GL.GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, intBuf); GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB = intBuf.get(0); } catch(GLException gle){ GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB=0; } try { gl.glGetIntegerv(GL.GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, intBuf); GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB = intBuf.get(0); } catch(GLException gle) { GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB=0; } try { gl.glGetIntegerv(GL.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, intBuf); GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB = intBuf.get(0); } catch(GLException gle) { GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB=0; } try { gl.glGetIntegerv(GL.GL_MAX_VARYING_FLOATS_ARB, intBuf); GL_MAX_VARYING_FLOATS_ARB = intBuf.get(0); } catch(GLException gle) { GL_MAX_VARYING_FLOATS_ARB=0; } // See StencilState GL_EXT_stencil_two_side = gl .isExtensionAvailable("GL_EXT_stencil_two_side"); GL_EXT_stencil_wrap = gl.isExtensionAvailable("GL_EXT_stencil_wrap"); // See TextureState GL_ARB_multitexture = gl.isExtensionAvailable("GL_ARB_multitexture"); GL_ARB_texture_env_dot3 = gl .isExtensionAvailable("GL_ARB_texture_env_dot3"); GL_ARB_texture_env_combine = gl .isExtensionAvailable("GL_ARB_texture_env_combine"); GL_SGIS_generate_mipmap = gl .isExtensionAvailable("GL_SGIS_generate_mipmap"); GL_EXT_texture_compression_s3tc = gl .isExtensionAvailable("GL_EXT_texture_compression_s3tc"); GL_EXT_texture_3d = gl.isExtensionAvailable("GL_EXT_texture_3d"); GL_ARB_texture_cube_map = gl .isExtensionAvailable("GL_ARB_texture_cube_map"); GL_EXT_texture_filter_anisotropic = gl .isExtensionAvailable("GL_EXT_texture_filter_anisotropic"); GL_ARB_texture_non_power_of_two = gl .isExtensionAvailable("GL_ARB_texture_non_power_of_two"); GL_ARB_texture_rectangle = gl .isExtensionAvailable("GL_ARB_texture_rectangle"); gl.glGetIntegerv(GL.GL_MAX_TEXTURE_UNITS, intBuf); GL_MAX_TEXTURE_UNITS = intBuf.get(0); try { gl.glGetIntegerv(GL.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, intBuf); GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB = intBuf.get(0); } catch(GLException gle) { GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB=0; } try { gl.glGetIntegerv(GL.GL_MAX_TEXTURE_IMAGE_UNITS_ARB, intBuf); GL_MAX_TEXTURE_IMAGE_UNITS_ARB = intBuf.get(0); } catch(GLException gle) { GL_MAX_TEXTURE_IMAGE_UNITS_ARB=0; } try { gl.glGetIntegerv(GL.GL_MAX_TEXTURE_COORDS_ARB, intBuf); GL_MAX_TEXTURE_COORDS_ARB = intBuf.get(0); } catch(GLException gle) { GL_MAX_TEXTURE_COORDS_ARB=0; } try { GL_SHADING_LANGUAGE_VERSION_ARB = gl .glGetString(GL.GL_SHADING_LANGUAGE_VERSION_ARB); } catch(GLException gle) { GL_SHADING_LANGUAGE_VERSION_ARB=""; } // FIXME I don't think this was necessary: floatBuf.rewind(); try { gl.glGetFloatv(GL.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, floatBuf); GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = floatBuf.get(0); } catch(GLException gle) { GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT=0; } // See VertexProgram GL_ARB_vertex_program = gl .isExtensionAvailable("GL_ARB_vertex_program"); // See TextureStateRecord GL_ARB_texture_mirrored_repeat = gl .isExtensionAvailable("GL_ARB_texture_mirrored_repeat"); GL_EXT_texture_mirror_clamp = gl .isExtensionAvailable("GL_EXT_texture_mirror_clamp"); GL_ARB_texture_border_clamp = gl .isExtensionAvailable("GL_ARB_texture_border_clamp"); GL_EXT_compiled_vertex_array = gl.isExtensionAvailable("GL_EXT_compiled_vertex_array"); } }
Fix for "GLException when swapping buffers with the JOGL renderer" git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@4488 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
src/com/jme/renderer/jogl/JOGLContextCapabilities.java
Fix for "GLException when swapping buffers with the JOGL renderer"
Java
bsd-2-clause
f61cfef8a4ebbf59b4a0b78fb887f472558d7a50
0
jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu
/* * Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com * Copyright (c) 2016, Jack J. Woehr [email protected] * SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package ublu.command; import com.ibm.as400.access.AS400Message; import com.ibm.as400.access.AS400SecurityException; import com.ibm.as400.access.ErrorCompletingRequestException; import com.ibm.as400.access.JobLog; import com.ibm.as400.access.ObjectDoesNotExistException; import com.ibm.as400.access.RequestNotSupportedException; import java.io.IOException; import java.sql.SQLException; import java.util.logging.Level; import ublu.util.ArgArray; import ublu.util.DataSink; import ublu.util.Generics.QueuedMessageList; import ublu.util.Tuple; /** * Command to manipulate job logs on the server. * * @author jax */ public class CmdJobLog extends Command { { setNameAndDescription("joblog", "/0 [-as400 @as400] [--,-joblog ~@joblog] [-to datasink] [-msgfile ~@{/full/ifs/path/}] [-onthread ~@tf] [-subst ~@{message_substitution}] [ -add ~@{int_attrib} | -clear | -close | -dir ~@tf | -length | -new ~@{jobname} ~@{jobuser} ~@{jobnumber} | -qm ~@{offset} ~@{number} | -write ~@{message_id} ~@{COMPLETION|DIAGNOSTIC|INFORMATIONAL|ESCAPE} ] : manipulate job logs on the host"); } enum OPS { ADD, CLEAR, DIR, CLOSE, LENGTH, NEW, NOOP, QM, WRITE } /** * Manipulate job logs on the server * * @param argArray the remainder of the command stream * @return the new remainder of the command stream */ public ArgArray jobLog(ArgArray argArray) { Tuple jobLogTuple = null; OPS op = OPS.NOOP; String jobName = null; String jobUser = null; String jobNumber = null; Integer attrib = null; Integer messageOffset = null; Integer numberMessages = null; String substitutionData = null; String messageFileIFSPath = null; String message_id = null; String message_type = null; Boolean onThread = null; Boolean direction = null; while (argArray.hasDashCommand()) { String dashCommand = argArray.parseDashCommand(); switch (dashCommand) { case "-to": String destName = argArray.next(); setDataDest(DataSink.fromSinkName(destName)); break; // case "-from": // String srcName = argArray.next(); // setDataSrc(DataSink.fromSinkName(srcName)); // break; case "-as400": setAs400(getAS400Tuple(argArray.next())); break; case "--": case "-joblog": jobLogTuple = argArray.nextTupleOrPop(); break; case "-add": op = OPS.ADD; attrib = argArray.nextIntMaybeQuotationTuplePopString(); break; case "-clear": op = OPS.CLEAR; break; case "-close": op = OPS.CLOSE; break; case "-dir": op = OPS.DIR; direction = argArray.nextBooleanTupleOrPop(); break; case "-length": op = OPS.LENGTH; break; case "-msgfile": messageFileIFSPath = argArray.nextMaybeQuotationTuplePopString(); break; case "-new": op = OPS.NEW; jobName = argArray.nextMaybeQuotationTuplePopString(); jobUser = argArray.nextMaybeQuotationTuplePopString(); jobNumber = argArray.nextMaybeQuotationTuplePopString(); break; case "-onthread": onThread = argArray.nextBooleanTupleOrPop(); break; case "-qm": op = OPS.QM; messageOffset = argArray.nextIntMaybeQuotationTuplePopString(); numberMessages = argArray.nextIntMaybeQuotationTuplePopString(); break; case "-subst": substitutionData = argArray.nextMaybeQuotationTuplePopString(); break; case "-write": message_id = argArray.nextMaybeQuotationTuplePopString(); message_type = argArray.nextMaybeQuotationTuplePopString(); break; default: unknownDashCommand(dashCommand); } } if (havingUnknownDashCommand()) { setCommandResult(COMMANDRESULT.FAILURE); } else { JobLog jobLog = jobLogFromTuple(jobLogTuple); switch (op) { case ADD: if (jobLog != null) { try { jobLog.addAttributeToRetrieve(attrib); } catch (IOException ex) { getLogger().log(Level.SEVERE, "Couldn't set JobLog attribute in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No JobLog instance for -add in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } break; case CLEAR: if (jobLog != null) { jobLog.clearAttributesToRetrieve(); } else { getLogger().log(Level.SEVERE, "No JobLog instance for -clear in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } break; case CLOSE: if (jobLog != null) { try { jobLog.close(); } catch (AS400SecurityException | ErrorCompletingRequestException | IOException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "Couldn't close JobLog instance in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No JobLog instance for -length in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } break; case DIR: if (jobLog != null) { jobLog.setListDirection(direction); } else { getLogger().log(Level.SEVERE, "No JobLog instance for -clear in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } break; case NEW: jobLog = new JobLog(getAs400(), jobName, jobUser, jobNumber); { try { put(jobLog); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Couldn't put JobLog instance in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case LENGTH: if (jobLog != null) { try { put(jobLog.getLength()); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Couldn't put JobLog length in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No JobLog for -length in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } break; case QM: if (jobLog != null) { try { jobLog.load(); put(new QueuedMessageList(jobLog.getMessages(messageOffset, numberMessages))); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Couldn't put JobLog instance in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No JobLog for queued message list in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } break; case NOOP: break; case WRITE: if (getAs400() != null) { try { JobLog.writeMessage(getAs400(), message_id, messageTypeFromString(message_type), messageFileIFSPath, substitutionData == null ? null : substitutionData.getBytes(), onThread ); } catch (AS400SecurityException | ErrorCompletingRequestException | InterruptedException | IOException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "Couldn't write message to job log in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No as400 for write in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } break; } } return argArray; } private JobLog jobLogFromTuple(Tuple t) { JobLog jobLog = null; if (t != null) { Object o = t.getValue(); if (o instanceof JobLog) { jobLog = JobLog.class.cast(o); } } return jobLog; } private Integer messageTypeFromString(String messageType) { Integer result = null; switch (messageType.toUpperCase()) { case "COMPLETION": result = AS400Message.COMPLETION; break; case "DIAGNOSTIC": result = AS400Message.DIAGNOSTIC; break; case "INFORMATIONAL": result = AS400Message.INFORMATIONAL; break; case "ESCAPE": result = AS400Message.ESCAPE; break; } return result; } @Override public ArgArray cmd(ArgArray args ) { reinit(); return jobLog(args); } @Override public COMMANDRESULT getResult() { return getCommandResult(); } }
src/ublu/command/CmdJobLog.java
/* * Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com * Copyright (c) 2016, Jack J. Woehr [email protected] * SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package ublu.command; import com.ibm.as400.access.AS400Message; import com.ibm.as400.access.AS400SecurityException; import com.ibm.as400.access.ErrorCompletingRequestException; import com.ibm.as400.access.JobLog; import com.ibm.as400.access.ObjectDoesNotExistException; import com.ibm.as400.access.RequestNotSupportedException; import java.io.IOException; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import ublu.util.ArgArray; import ublu.util.DataSink; import ublu.util.Generics.QueuedMessageList; import ublu.util.Tuple; /** * Command to manipulate job logs on the server. * * @author jax */ public class CmdJobLog extends Command { { setNameAndDescription("joblog", "/0 [-as400 @as400] [--,-joblog ~@joblog] [-to datasink] [-msgfile ~@{/full/ifs/path/}] [-onthread ~@tf] [-subst ~@{message_substitution}] [ -close | -length | -new ~@{jobname} ~@{jobuser} ~@{jobnumber} | -qm ~@{offset} ~@{number} | -write ~@{message_id} ~@{COMPLETION|DIAGNOSTIC|INFORMATIONAL|ESCAPE} ] : manipulate job logs on the host"); } enum OPS { CLOSE, LENGTH, NEW, NOOP, QM, WRITE } /** * Manipulate job logs on the server * * @param argArray the remainder of the command stream * @return the new remainder of the command stream */ public ArgArray jobLog(ArgArray argArray) { Tuple jobLogTuple = null; OPS op = OPS.NOOP; String jobName = null; String jobUser = null; String jobNumber = null; Integer messageOffset = null; Integer numberMessages = null; String substitutionData = null; String messageFileIFSPath = null; String message_id = null; String message_type = null; Boolean onThread = null; while (argArray.hasDashCommand()) { String dashCommand = argArray.parseDashCommand(); switch (dashCommand) { case "-to": String destName = argArray.next(); setDataDest(DataSink.fromSinkName(destName)); break; // case "-from": // String srcName = argArray.next(); // setDataSrc(DataSink.fromSinkName(srcName)); // break; case "-as400": setAs400(getAS400Tuple(argArray.next())); break; case "--": case "-joblog": jobLogTuple = argArray.nextTupleOrPop(); break; case "-close": op = OPS.CLOSE; break; case "-length": op = OPS.LENGTH; break; case "-msgfile": messageFileIFSPath = argArray.nextMaybeQuotationTuplePopString(); break; case "-new": op = OPS.NEW; jobName = argArray.nextMaybeQuotationTuplePopString(); jobUser = argArray.nextMaybeQuotationTuplePopString(); jobNumber = argArray.nextMaybeQuotationTuplePopString(); break; case "-onthread": onThread = argArray.nextBooleanTupleOrPop(); break; case "-qm": op = OPS.QM; messageOffset = argArray.nextIntMaybeQuotationTuplePopString(); numberMessages = argArray.nextIntMaybeQuotationTuplePopString(); break; case "-subst": substitutionData = argArray.nextMaybeQuotationTuplePopString(); break; case "-write": message_id = argArray.nextMaybeQuotationTuplePopString(); message_type = argArray.nextMaybeQuotationTuplePopString(); break; default: unknownDashCommand(dashCommand); } } if (havingUnknownDashCommand()) { setCommandResult(COMMANDRESULT.FAILURE); } else { JobLog jobLog = jobLogFromTuple(jobLogTuple); switch (op) { case CLOSE: if (jobLog != null) { try { jobLog.close(); } catch (AS400SecurityException | ErrorCompletingRequestException | IOException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "Couldn't close JobLog instance in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No JobLog instance for -length in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } break; case NEW: jobLog = new JobLog(getAs400(), jobName, jobUser, jobNumber); { try { put(jobLog); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Couldn't put JobLog instance in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } break; case LENGTH: if (jobLog != null) { try { put(jobLog.getLength()); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Couldn't put JobLog length in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No JobLog for -length in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } break; case QM: if (jobLog != null) { try { jobLog.load(); put(new QueuedMessageList(jobLog.getMessages(messageOffset, numberMessages))); } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) { getLogger().log(Level.SEVERE, "Couldn't put JobLog instance in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No JobLog for queued message list in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } break; case NOOP: break; case WRITE: if (getAs400() != null) { try { JobLog.writeMessage(getAs400(), message_id, messageTypeFromString(message_type), messageFileIFSPath, substitutionData == null ? null : substitutionData.getBytes(), onThread ); } catch (AS400SecurityException | ErrorCompletingRequestException | InterruptedException | IOException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "Couldn't write message to job log in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No as400 for write in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } break; } } return argArray; } private JobLog jobLogFromTuple(Tuple t) { JobLog jobLog = null; if (t != null) { Object o = t.getValue(); if (o instanceof JobLog) { jobLog = JobLog.class.cast(o); } } return jobLog; } private Integer messageTypeFromString(String messageType) { Integer result = null; switch (messageType.toUpperCase()) { case "COMPLETION": result = AS400Message.COMPLETION; break; case "DIAGNOSTIC": result = AS400Message.DIAGNOSTIC; break; case "INFORMATIONAL": result = AS400Message.INFORMATIONAL; break; case "ESCAPE": result = AS400Message.ESCAPE; break; } return result; } @Override public ArgArray cmd(ArgArray args ) { reinit(); return jobLog(args); } @Override public COMMANDRESULT getResult() { return getCommandResult(); } }
more on joblog
src/ublu/command/CmdJobLog.java
more on joblog
Java
bsd-3-clause
57c3a5b13c2e98f6549ce05b83330ee561bf3ce3
0
interdroid/ibis-ipl,interdroid/ibis-ipl,interdroid/ibis-ipl
package ibis.rmi; import ibis.ipl.Ibis; import ibis.ipl.IbisIdentifier; import ibis.ipl.PortType; import ibis.ipl.ReceivePort; import ibis.ipl.ReceivePortIdentifier; import ibis.ipl.SendPort; import ibis.ipl.IbisException; import ibis.ipl.WriteMessage; import ibis.ipl.ReadMessage; import ibis.ipl.StaticProperties; import ibis.ipl.Upcall; import ibis.rmi.server.Stub; import ibis.rmi.server.RemoteStub; import ibis.rmi.server.Skeleton; import ibis.rmi.server.ExportException; import java.util.Properties; import java.util.HashMap; import java.util.Hashtable; import java.util.ArrayList; import java.net.InetAddress; import java.io.IOException; public final class RTS { public final static boolean DEBUG = false; //keys - impl objects, values - skeletons for those objects /** * Maps objects to their skeletons. */ private static HashMap skeletons; /** * Maps objects to their stubs. */ private static HashMap stubs; /** * Maps ReceivePortIdentifiers to sendports that have a connection to that * receiveport. */ private static HashMap sendports; /** * Maps an URL to a skeleton. We need this because a ReceivePortIdentifier no * longer uniquely defines the skeleton. In fact, a skeleton is now identified * by a number. Unfortunately, the Ibis registry can only handle ReceivePortIdentifiers. */ private static Hashtable urlHash; // No HashMap, this one should be synchronized. /** * This array maps skeleton ids to the corresponding skeleton. */ private static ArrayList skeletonArray; /** * Cache receiveports from stubs. */ private static ArrayList receiveports; protected static String hostname; protected static PortType portType; private static Ibis ibis; private static IbisIdentifier localID; private static ibis.ipl.Registry ibisRegistry; private static ThreadLocal clientHost; private static ReceivePort skeletonReceivePort = null; private static class UpcallHandler implements Upcall { public void upcall(ReadMessage r) throws IOException { Skeleton skel; int id = r.readInt(); if (id == -1) { String url = r.readString(); skel = (Skeleton) urlHash.get(url); } else skel = (Skeleton)(skeletonArray.get(id)); skel.upcall(r); } } private static UpcallHandler upcallHandler; static { try { skeletons = new HashMap(); stubs = new HashMap(); sendports = new HashMap(); urlHash = new Hashtable(); receiveports = new ArrayList(); skeletonArray = new ArrayList(); upcallHandler = new UpcallHandler(); hostname = InetAddress.getLocalHost().getHostName(); InetAddress adres = InetAddress.getByName(hostname); adres = InetAddress.getByName(adres.getHostAddress()); hostname = adres.getHostName(); if (DEBUG) { System.out.println(hostname + ": init RMI RTS"); System.out.println(hostname + ": creating ibis"); } // @@@ start of horrible code // System.err.println("AARG! This code completely violates the whole Ibis philosophy!!!! please fix me! --Rob & Jason"); // new Exception().printStackTrace(); // But HOW??? --Ceriel ibis = Ibis.createIbis(null); Properties p = System.getProperties(); String ibis_name = p.getProperty("ibis.name"); StaticProperties s = new StaticProperties(); String ibis_serialization = p.getProperty("ibis.serialization"); if (ibis_serialization != null) { System.out.println("Setting Serialization to " + ibis_serialization); s.add("Serialization", ibis_serialization); } else { System.out.println("Setting Serialization to ibis"); s.add("Serialization", "ibis"); } if (ibis_name != null && ibis_name.startsWith("net.")) { // System.err.println("AARG! This code completely violates the whole Ibis philosophy!!!! please fix me! --Rob & Jason"); // new Exception().printStackTrace(); // But HOW??? --Ceriel String driver = ibis_name.substring("net.".length()); String path = "/"; if (ibis_serialization != null && ! ibis_serialization.equals("none")) { String top = "s_" + ibis_serialization; // System.err.println("Now register static property \"" + (path + ":Driver") + "\" as \"" + top + "\""); s.add(path + ":Driver", top); path = path + top; } while (true) { int dot = driver.indexOf('.'); int end = dot; if (end == -1) { end = driver.length(); } String top = driver.substring(0, end); // System.err.println("Now register static property \"" + (path + ":Driver") + "\" as \"" + top + "\""); s.add(path + ":Driver", top); if (dot == -1) { break; } if (path.equals("/")) { path = path + top; } else { path = path + "/" + top; } driver = driver.substring(dot + 1); } } // @@@ end of horrible code if (DEBUG) { System.out.println(hostname + ": ibis created"); } localID = ibis.identifier(); ibisRegistry = ibis.registry(); portType = ibis.createPortType("RMI", s); skeletonReceivePort = portType.createReceivePort("//" + hostname + "/rmi_skeleton" + (new java.rmi.server.UID()).toString(), upcallHandler); skeletonReceivePort.enableConnections(); skeletonReceivePort.enableUpcalls(); clientHost = new ThreadLocal(); if(DEBUG) { System.out.println(hostname + ": RMI RTS init done"); } } catch (Exception e) { System.err.println(hostname + ": Could not init RMI RTS " + e); e.printStackTrace(); System.exit(1); } /**** * This is only supported in SDK 1.4 and upwards. Comment out * if you run an older SDK. */ Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { ibis.end(); // System.err.println("Ended Ibis"); } catch (IOException e) { System.err.println("ibis.end throws " + e); } } }); /* End of 1.4-specific code */ } private static String get_skel_name(Class c) { String class_name = c.getName(); Package pkg = c.getPackage(); String package_name = pkg != null ? pkg.getName() : null; if (package_name == null || package_name.equals("")) { return "rmi_skeleton_" + class_name; } return package_name + ".rmi_skeleton_" + class_name.substring(class_name.lastIndexOf('.') + 1); } private static String get_stub_name(Class c) { String class_name = c.getName(); Package pkg = c.getPackage(); String package_name = pkg != null ? pkg.getName() : null; if (package_name == null || package_name.equals("")) { return "rmi_stub_" + class_name; } return package_name + ".rmi_stub_" + class_name.substring(class_name.lastIndexOf('.') + 1); } private synchronized static Skeleton createSkel(Remote obj) throws IOException { try { Skeleton skel; Class c = obj.getClass(); ReceivePort rec; String skel_name = get_skel_name(c); // System.out.println("skel_name = " + skel_name); // Use the classloader of the original class! // Fix is by Fabrice Huet. ClassLoader loader = c.getClassLoader(); Class skel_c = null; if (loader != null) { skel_c = loader.loadClass(skel_name); } else { skel_c = Class.forName(skel_name); } skel = (Skeleton) skel_c.newInstance(); int skelId = skeletonArray.size(); skeletonArray.add(skel); skel.init(skelId, obj); skeletons.put(obj, skel); return skel; } catch (ClassNotFoundException ec) { throw new RemoteException("Cannot create skeleton", ec); } catch (InstantiationException en) { throw new RemoteException("Cannot create skeleton", en); } catch (IllegalAccessException el) { throw new RemoteException("Cannot create skeleton", el); } } public static RemoteStub exportObject(Remote obj) throws Exception { Stub stub; Class c = obj.getClass(); Skeleton skel; String classname = c.getName(); String class_name = classname.substring(classname.lastIndexOf('.') + 1); synchronized(RTS.class) { skel = (Skeleton) skeletons.get(obj); } if (skel == null) { //create a skeleton skel = createSkel(obj); } else { throw new ExportException("object already exported"); } //create a stub // Use the classloader of the original class! // Fix is by Fabrice Huet. ClassLoader loader = obj.getClass().getClassLoader(); Class stub_c = null; if (loader != null) { stub_c = loader.loadClass(get_stub_name(c)); } else { stub_c = Class.forName(get_stub_name(c)); } stub = (Stub) stub_c.newInstance(); stub.init(null, null, 0, skel.skeletonId, skeletonReceivePort.identifier(), false); if (DEBUG) { System.out.println(hostname + ": Created stub of type rmi_stub_" + classname); } stubs.put(obj, stub); return (RemoteStub) stub; } public static synchronized Object getStub(Object o) { return stubs.get(o); } public static synchronized void bind(String url, Remote o) throws AlreadyBoundException, IbisException, IOException, InstantiationException, IllegalAccessException { // String url = "//" + RTS.hostname + "/" + name; if (DEBUG) { System.out.println(hostname + ": Trying to bind object to " + url); } ReceivePortIdentifier dest = null; try { dest = ibisRegistry.lookup(url, 1); } catch(IOException e) { } if (dest != null) { throw new AlreadyBoundException(url + " already bound"); } Skeleton skel = (Skeleton) skeletons.get(o); if (skel == null) { // throw new RemoteException("object not exported"); //or just export it??? skel = createSkel(o); } //new method ibisRegistry.bind(url, skeletonReceivePort.identifier()); urlHash.put(url, skel); if (DEBUG) { System.out.println(hostname + ": Bound to object " + url); } } public static synchronized void rebind(String url, Remote o) throws IbisException, IOException, InstantiationException, IllegalAccessException { if (DEBUG) { System.out.println(hostname + ": Trying to rebind object to " + url); } Skeleton skel = (Skeleton) skeletons.get(o); if (skel == null) { // throw new RemoteException("object not exported"); //or just export it??? skel = createSkel(o); } //new method ibisRegistry.rebind(url, skeletonReceivePort.identifier()); urlHash.put(url, skel); } public static void unbind(String url) throws NotBoundException, ClassNotFoundException, IOException { if (DEBUG) { System.out.println(hostname + ": Trying to unbind object from " + url); } ReceivePortIdentifier dest = null; try { dest = ibisRegistry.lookup(url, 1); } catch (IOException e) { } if (dest == null) { throw new NotBoundException(url + " not bound"); } //new method ibisRegistry.unbind(url); } public static Remote lookup(String url) throws NotBoundException, IOException { Stub result; SendPort s = null; if (DEBUG) { System.out.println(hostname + ": Trying to lookup object " + url); } ReceivePortIdentifier dest = null; synchronized(RTS.class) { try { dest = ibisRegistry.lookup(url, 1); // System.err.println("ibisRegistry.lookup(" + url + ". 1) is " + dest); } catch(IOException e) { // System.err.println("ibisRegistry.lookup(" + url + ". 1) throws " + e); } } if (dest == null) { throw new NotBoundException(url + " not bound"); } if (DEBUG) { System.out.println(hostname + ": Found skeleton " + url + " connecting"); } s = getSendPort(dest); if (DEBUG) { System.out.println(hostname + ": Got sendport"); } ReceivePort r = getReceivePort(); if (DEBUG) { System.out.println(hostname + ": Created receiveport for stub -> id = " + r.identifier()); } WriteMessage wm = s.newMessage(); if (DEBUG) { System.out.println(hostname + ": Created new WriteMessage"); } wm.writeInt(-1); wm.writeString(url); wm.writeInt(-1); wm.writeInt(0); wm.writeObject(r.identifier()); wm.send(); wm.finish(); if (DEBUG) { System.out.println(hostname + ": Sent new WriteMessage"); } ReadMessage rm = r.receive(); if (DEBUG) { System.out.println(hostname + ": Received readMessage"); } int stubID = rm.readInt(); int skelID = rm.readInt(); String stubType = rm.readString(); rm.finish(); if (DEBUG) { System.out.println(hostname + ": read typename " + stubType); } try { result = (Stub) Class.forName(stubType).newInstance(); } catch (Exception e) { // The loading of the class has failed. // maybe Ibis was loaded using the primordial classloader // and the needed class was not. // Fix is by Fabrice Huet. try { result = (Stub) Thread.currentThread().getContextClassLoader() .loadClass(stubType).newInstance(); } catch(Exception e2) { // s.free(); // r.forcedClose(); throw new RemoteException("stub class " + stubType + " not found", e2); } } if (DEBUG) { System.out.println(hostname + ": Loaded class " + stubType); } result.init(s, r, stubID, skelID, dest, true); if (DEBUG) { System.out.println(hostname + ": Found object " + url); } return (Remote) result; } public static String[] list(String url) throws IOException { int urlLength = url.length(); String[] names = ibisRegistry.list(url /*+ ".*"*/); for (int i=0; i<names.length; i++) { names[i] = names[i].substring(urlLength); } return names; } public static SendPort createSendPort() throws IOException { return portType.createSendPort(new RMIReplacer()); } public static synchronized SendPort getSendPort(ReceivePortIdentifier rpi) throws IOException { SendPort s = (SendPort) sendports.get(rpi); if (s == null) { s = createSendPort(); s.connect(rpi); sendports.put(rpi, s); if (DEBUG) { System.out.println(hostname + ": New sendport for receiport: " + rpi); } } else if (DEBUG) { System.out.println(hostname + ": Reuse sendport for receiport: " + rpi); } return s; } public static synchronized ReceivePort getReceivePort() throws IOException { ReceivePort r; int len = receiveports.size(); if (len > 0) { r = (ReceivePort) receiveports.remove(len-1); if (DEBUG) { System.out.println(hostname + ": Reuse receiveport: " + r.identifier()); } } else { r = portType.createReceivePort("//" + hostname + "/rmi_stub" + (new java.rmi.server.UID()).toString()); if (DEBUG) { System.out.println(hostname + ": New receiveport: " + r.identifier()); } } r.enableConnections(); return r; } public static synchronized void putReceivePort(ReceivePort r) { r.disableConnections(); if (DEBUG) { System.out.println(hostname + ": receiveport returned"); } receiveports.add(r); } public static void createRegistry(int port) throws RemoteException { String url = "registry://" + hostname + ":" + port; try { portType.createReceivePort(url); } catch (IOException e) { throw new RemoteException("there already is a registry running on port " + port); } } public static String getHostname() { return hostname; } public static void setClientHost(String s) { clientHost.set(s); } public static String getClientHost() { Object o = clientHost.get(); if (o == null) return "UNKNOWN_HOST"; String s = (String) o; return s; } }
src/ibis/rmi/RTS.java
package ibis.rmi; import ibis.ipl.Ibis; import ibis.ipl.IbisIdentifier; import ibis.ipl.PortType; import ibis.ipl.ReceivePort; import ibis.ipl.ReceivePortIdentifier; import ibis.ipl.SendPort; import ibis.ipl.IbisException; import ibis.ipl.WriteMessage; import ibis.ipl.ReadMessage; import ibis.ipl.StaticProperties; import ibis.ipl.Upcall; import ibis.rmi.server.Stub; import ibis.rmi.server.RemoteStub; import ibis.rmi.server.Skeleton; import ibis.rmi.server.ExportException; import java.util.Properties; import java.util.HashMap; import java.util.Hashtable; import java.util.ArrayList; import java.net.InetAddress; import java.io.IOException; public final class RTS { public final static boolean DEBUG = false; //keys - impl objects, values - skeletons for those objects /** * Maps objects to their skeletons. */ private static HashMap skeletons; /** * Maps objects to their stubs. */ private static HashMap stubs; /** * Maps ReceivePortIdentifiers to sendports that have a connection to that * receiveport. */ private static HashMap sendports; /** * Maps an URL to a skeleton. We need this because a ReceivePortIdentifier no * longer uniquely defines the skeleton. In fact, a skeleton is now identified * by a number. Unfortunately, the Ibis registry can only handle ReceivePortIdentifiers. */ private static Hashtable urlHash; // No HashMap, this one should be synchronized. /** * This array maps skeleton ids to the corresponding skeleton. */ private static ArrayList skeletonArray; /** * Cache receiveports from stubs. */ private static ArrayList receiveports; protected static String hostname; protected static PortType portType; private static Ibis ibis; private static IbisIdentifier localID; private static ibis.ipl.Registry ibisRegistry; private static ThreadLocal clientHost; private static ReceivePort skeletonReceivePort = null; private static class UpcallHandler implements Upcall { public void upcall(ReadMessage r) throws IOException { Skeleton skel; int id = r.readInt(); if (id == -1) { String url = r.readString(); skel = (Skeleton) urlHash.get(url); } else skel = (Skeleton)(skeletonArray.get(id)); skel.upcall(r); } } private static UpcallHandler upcallHandler; static { try { skeletons = new HashMap(); stubs = new HashMap(); sendports = new HashMap(); urlHash = new Hashtable(); receiveports = new ArrayList(); skeletonArray = new ArrayList(); upcallHandler = new UpcallHandler(); hostname = InetAddress.getLocalHost().getHostName(); InetAddress adres = InetAddress.getByName(hostname); adres = InetAddress.getByName(adres.getHostAddress()); hostname = adres.getHostName(); if (DEBUG) { System.out.println(hostname + ": init RMI RTS"); System.out.println(hostname + ": creating ibis"); } // @@@ start of horrible code // System.err.println("AARG! This code completely violates the whole Ibis philosophy!!!! please fix me! --Rob & Jason"); // new Exception().printStackTrace(); // But HOW??? --Ceriel ibis = Ibis.createIbis(null); Properties p = System.getProperties(); String ibis_name = p.getProperty("ibis.name"); StaticProperties s = new StaticProperties(); String ibis_serialization = p.getProperty("ibis.serialization"); if (ibis_serialization != null) { System.out.println("Setting Serialization to " + ibis_serialization); s.add("Serialization", ibis_serialization); } else { System.out.println("Setting Serialization to ibis"); s.add("Serialization", "ibis"); } if (ibis_name != null && ibis_name.startsWith("net.")) { // System.err.println("AARG! This code completely violates the whole Ibis philosophy!!!! please fix me! --Rob & Jason"); // new Exception().printStackTrace(); // But HOW??? --Ceriel String driver = ibis_name.substring("net.".length()); String path = "/"; if (ibis_serialization != null && ! ibis_serialization.equals("none")) { String top = "s_" + ibis_serialization; // System.err.println("Now register static property \"" + (path + ":Driver") + "\" as \"" + top + "\""); s.add(path + ":Driver", top); path = path + top; } while (true) { int dot = driver.indexOf('.'); int end = dot; if (end == -1) { end = driver.length(); } String top = driver.substring(0, end); // System.err.println("Now register static property \"" + (path + ":Driver") + "\" as \"" + top + "\""); s.add(path + ":Driver", top); if (dot == -1) { break; } if (path.equals("/")) { path = path + top; } else { path = path + "/" + top; } driver = driver.substring(dot + 1); } } // @@@ end of horrible code if (DEBUG) { System.out.println(hostname + ": ibis created"); } localID = ibis.identifier(); ibisRegistry = ibis.registry(); portType = ibis.createPortType("RMI", s); skeletonReceivePort = portType.createReceivePort("//" + hostname + "/rmi_skeleton", upcallHandler); skeletonReceivePort.enableConnections(); skeletonReceivePort.enableUpcalls(); clientHost = new ThreadLocal(); if(DEBUG) { System.out.println(hostname + ": RMI RTS init done"); } } catch (Exception e) { System.err.println(hostname + ": Could not init RMI RTS " + e); e.printStackTrace(); System.exit(1); } /**** * This is only supported in SDK 1.4 and upwards. Comment out * if you run an older SDK. */ Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { ibis.end(); // System.err.println("Ended Ibis"); } catch (IOException e) { System.err.println("ibis.end throws " + e); } } }); /* End of 1.4-specific code */ } private static String get_skel_name(Class c) { String class_name = c.getName(); Package pkg = c.getPackage(); String package_name = pkg != null ? pkg.getName() : null; if (package_name == null || package_name.equals("")) { return "rmi_skeleton_" + class_name; } return package_name + ".rmi_skeleton_" + class_name.substring(class_name.lastIndexOf('.') + 1); } private static String get_stub_name(Class c) { String class_name = c.getName(); Package pkg = c.getPackage(); String package_name = pkg != null ? pkg.getName() : null; if (package_name == null || package_name.equals("")) { return "rmi_stub_" + class_name; } return package_name + ".rmi_stub_" + class_name.substring(class_name.lastIndexOf('.') + 1); } private synchronized static Skeleton createSkel(Remote obj) throws IOException { try { Skeleton skel; Class c = obj.getClass(); ReceivePort rec; String skel_name = get_skel_name(c); // System.out.println("skel_name = " + skel_name); // Use the classloader of the original class! // Fix is by Fabrice Huet. ClassLoader loader = c.getClassLoader(); Class skel_c = null; if (loader != null) { skel_c = loader.loadClass(skel_name); } else { skel_c = Class.forName(skel_name); } skel = (Skeleton) skel_c.newInstance(); int skelId = skeletonArray.size(); skeletonArray.add(skel); skel.init(skelId, obj); skeletons.put(obj, skel); return skel; } catch (ClassNotFoundException ec) { throw new RemoteException("Cannot create skeleton", ec); } catch (InstantiationException en) { throw new RemoteException("Cannot create skeleton", en); } catch (IllegalAccessException el) { throw new RemoteException("Cannot create skeleton", el); } } public static RemoteStub exportObject(Remote obj) throws Exception { Stub stub; Class c = obj.getClass(); Skeleton skel; String classname = c.getName(); String class_name = classname.substring(classname.lastIndexOf('.') + 1); synchronized(RTS.class) { skel = (Skeleton) skeletons.get(obj); } if (skel == null) { //create a skeleton skel = createSkel(obj); } else { throw new ExportException("object already exported"); } //create a stub // Use the classloader of the original class! // Fix is by Fabrice Huet. ClassLoader loader = obj.getClass().getClassLoader(); Class stub_c = null; if (loader != null) { stub_c = loader.loadClass(get_stub_name(c)); } else { stub_c = Class.forName(get_stub_name(c)); } stub = (Stub) stub_c.newInstance(); stub.init(null, null, 0, skel.skeletonId, skeletonReceivePort.identifier(), false); if (DEBUG) { System.out.println(hostname + ": Created stub of type rmi_stub_" + classname); } stubs.put(obj, stub); return (RemoteStub) stub; } public static synchronized Object getStub(Object o) { return stubs.get(o); } public static synchronized void bind(String url, Remote o) throws AlreadyBoundException, IbisException, IOException, InstantiationException, IllegalAccessException { // String url = "//" + RTS.hostname + "/" + name; if (DEBUG) { System.out.println(hostname + ": Trying to bind object to " + url); } ReceivePortIdentifier dest = null; try { dest = ibisRegistry.lookup(url, 1); } catch(IOException e) { } if (dest != null) { throw new AlreadyBoundException(url + " already bound"); } Skeleton skel = (Skeleton) skeletons.get(o); if (skel == null) { // throw new RemoteException("object not exported"); //or just export it??? skel = createSkel(o); } //new method ibisRegistry.bind(url, skeletonReceivePort.identifier()); urlHash.put(url, skel); if (DEBUG) { System.out.println(hostname + ": Bound to object " + url); } } public static synchronized void rebind(String url, Remote o) throws IbisException, IOException, InstantiationException, IllegalAccessException { if (DEBUG) { System.out.println(hostname + ": Trying to rebind object to " + url); } Skeleton skel = (Skeleton) skeletons.get(o); if (skel == null) { // throw new RemoteException("object not exported"); //or just export it??? skel = createSkel(o); } //new method ibisRegistry.rebind(url, skeletonReceivePort.identifier()); urlHash.put(url, skel); } public static void unbind(String url) throws NotBoundException, ClassNotFoundException, IOException { if (DEBUG) { System.out.println(hostname + ": Trying to unbind object from " + url); } ReceivePortIdentifier dest = null; try { dest = ibisRegistry.lookup(url, 1); } catch (IOException e) { } if (dest == null) { throw new NotBoundException(url + " not bound"); } //new method ibisRegistry.unbind(url); } public static Remote lookup(String url) throws NotBoundException, IOException { Stub result; SendPort s = null; if (DEBUG) { System.out.println(hostname + ": Trying to lookup object " + url); } ReceivePortIdentifier dest = null; synchronized(RTS.class) { try { dest = ibisRegistry.lookup(url, 1); // System.err.println("ibisRegistry.lookup(" + url + ". 1) is " + dest); } catch(IOException e) { // System.err.println("ibisRegistry.lookup(" + url + ". 1) throws " + e); } } if (dest == null) { throw new NotBoundException(url + " not bound"); } if (DEBUG) { System.out.println(hostname + ": Found skeleton " + url + " connecting"); } s = getSendPort(dest); if (DEBUG) { System.out.println(hostname + ": Got sendport"); } ReceivePort r = getReceivePort(); if (DEBUG) { System.out.println(hostname + ": Created receiveport for stub -> id = " + r.identifier()); } WriteMessage wm = s.newMessage(); if (DEBUG) { System.out.println(hostname + ": Created new WriteMessage"); } wm.writeInt(-1); wm.writeString(url); wm.writeInt(-1); wm.writeInt(0); wm.writeObject(r.identifier()); wm.send(); wm.finish(); if (DEBUG) { System.out.println(hostname + ": Sent new WriteMessage"); } ReadMessage rm = r.receive(); if (DEBUG) { System.out.println(hostname + ": Received readMessage"); } int stubID = rm.readInt(); int skelID = rm.readInt(); String stubType = rm.readString(); rm.finish(); if (DEBUG) { System.out.println(hostname + ": read typename " + stubType); } try { result = (Stub) Class.forName(stubType).newInstance(); } catch (Exception e) { // The loading of the class has failed. // maybe Ibis was loaded using the primordial classloader // and the needed class was not. // Fix is by Fabrice Huet. try { result = (Stub) Thread.currentThread().getContextClassLoader() .loadClass(stubType).newInstance(); } catch(Exception e2) { // s.free(); // r.forcedClose(); throw new RemoteException("stub class " + stubType + " not found", e2); } } if (DEBUG) { System.out.println(hostname + ": Loaded class " + stubType); } result.init(s, r, stubID, skelID, dest, true); if (DEBUG) { System.out.println(hostname + ": Found object " + url); } return (Remote) result; } public static String[] list(String url) throws IOException { int urlLength = url.length(); String[] names = ibisRegistry.list(url /*+ ".*"*/); for (int i=0; i<names.length; i++) { names[i] = names[i].substring(urlLength); } return names; } public static SendPort createSendPort() throws IOException { return portType.createSendPort(new RMIReplacer()); } public static synchronized SendPort getSendPort(ReceivePortIdentifier rpi) throws IOException { SendPort s = (SendPort) sendports.get(rpi); if (s == null) { s = createSendPort(); s.connect(rpi); sendports.put(rpi, s); if (DEBUG) { System.out.println(hostname + ": New sendport for receiport: " + rpi); } } else if (DEBUG) { System.out.println(hostname + ": Reuse sendport for receiport: " + rpi); } return s; } public static synchronized ReceivePort getReceivePort() throws IOException { ReceivePort r; int len = receiveports.size(); if (len > 0) { r = (ReceivePort) receiveports.remove(len-1); if (DEBUG) { System.out.println(hostname + ": Reuse receiveport: " + r.identifier()); } } else { r = portType.createReceivePort("//" + hostname + "/rmi_stub" + (new java.rmi.server.UID()).toString()); if (DEBUG) { System.out.println(hostname + ": New receiveport: " + r.identifier()); } } r.enableConnections(); return r; } public static synchronized void putReceivePort(ReceivePort r) { r.disableConnections(); if (DEBUG) { System.out.println(hostname + ": receiveport returned"); } receiveports.add(r); } public static void createRegistry(int port) throws RemoteException { String url = "registry://" + hostname + ":" + port; try { portType.createReceivePort(url); } catch (IOException e) { throw new RemoteException("there already is a registry running on port " + port); } } public static String getHostname() { return hostname; } public static void setClientHost(String s) { clientHost.set(s); } public static String getClientHost() { Object o = clientHost.get(); if (o == null) return "UNKNOWN_HOST"; String s = (String) o; return s; } }
Made name unique git-svn-id: f22e84ca493ccad7df8d2727bca69d1c9fc2e5c5@803 aaf88347-d911-0410-b711-e54d386773bb
src/ibis/rmi/RTS.java
Made name unique
Java
bsd-3-clause
d0bf199b1ddaef50b66acc519908c7f68c3c3f50
0
Clunker5/tregmine-2.0,Clunker5/tregmine-2.0
package info.tregmine.commands; import info.tregmine.Tregmine; import info.tregmine.api.GenericPlayer; import info.tregmine.api.Rank; import info.tregmine.database.DAOException; import info.tregmine.database.IContext; import info.tregmine.database.IPlayerDAO; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.entity.Player; import java.util.Collection; import static org.bukkit.ChatColor.WHITE; public class ActionCommand extends AbstractCommand { public ActionCommand(Tregmine tregmine) { super(tregmine, "action"); } private String argsToMessage(String[] args) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" "); buf.append(args[i]); } return buf.toString(); } @Override public boolean handlePlayer(GenericPlayer player, String[] args) { if (args.length == 0) { return false; } Server server = player.getServer(); String channel = player.getChatChannel(); String msg = argsToMessage(args); if (player.getRank() != Rank.RESIDENT && player.getRank() != Rank.SETTLER && player.getRank() != Rank.TOURIST && player.getRank() != Rank.UNVERIFIED) { msg = ChatColor.translateAlternateColorCodes('#', msg); } else { player.sendMessage(ChatColor.RED + "You are not allowed to use chat colors!"); } Collection<? extends Player> players = server.getOnlinePlayers(); for (Player tp : players) { GenericPlayer to = tregmine.getPlayer(tp); if (!channel.equals(to.getChatChannel())) { continue; } boolean ignored; try (IContext ctx = tregmine.createContext()) { IPlayerDAO playerDAO = ctx.getPlayerDAO(); ignored = playerDAO.doesIgnore(to, player); } catch (DAOException e) { throw new RuntimeException(e); } if (player.getRank().canNotBeIgnored()) ignored = false; if (ignored == true) continue; TextComponent begin = new TextComponent("* "); TextComponent middle = new TextComponent(player.decideVS(to)); TextComponent end = new TextComponent(" " + WHITE + msg); to.sendMessage(begin, middle, end); } Tregmine.LOGGER.info("* " + player.getName() + " " + msg); if (player.getRank() != Rank.SENIOR_ADMIN && player.getRank() != Rank.JUNIOR_ADMIN) { msg = msg.replaceAll("@everyone", "").replaceAll("@here", ""); } this.tregmine.getDiscordDelegate().getChatChannel().sendMessage("**" + player.getChatNameNoColor() + "** " + ChatColor.stripColor(msg)).complete(); return true; } }
src/main/java/info/tregmine/commands/ActionCommand.java
package info.tregmine.commands; import info.tregmine.Tregmine; import info.tregmine.api.GenericPlayer; import info.tregmine.api.Rank; import info.tregmine.database.DAOException; import info.tregmine.database.IContext; import info.tregmine.database.IPlayerDAO; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.entity.Player; import java.util.Collection; import static org.bukkit.ChatColor.WHITE; public class ActionCommand extends AbstractCommand { public ActionCommand(Tregmine tregmine) { super(tregmine, "action"); } private String argsToMessage(String[] args) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" "); buf.append(args[i]); } return buf.toString(); } @Override public boolean handlePlayer(GenericPlayer player, String[] args) { if (args.length == 0) { return false; } Server server = player.getServer(); String channel = player.getChatChannel(); String msg = argsToMessage(args); if (player.getRank() != Rank.RESIDENT && player.getRank() != Rank.SETTLER && player.getRank() != Rank.TOURIST && player.getRank() != Rank.UNVERIFIED) { if (msg.contains("#r") || msg.contains("#R")) { msg = msg.replaceAll("#R", ChatColor.RESET + ""); msg = msg.replaceAll("#r", ChatColor.RESET + ""); } if (msg.contains("#0")) { msg = msg.replaceAll("#0", ChatColor.BLACK + ""); } if (msg.contains("#1")) { msg = msg.replaceAll("#1", ChatColor.DARK_BLUE + ""); } if (msg.contains("#2")) { msg = msg.replaceAll("#2", ChatColor.DARK_GREEN + ""); } if (msg.contains("#3")) { msg = msg.replaceAll("#3", ChatColor.DARK_AQUA + ""); } if (msg.contains("#4")) { msg = msg.replaceAll("#4", ChatColor.DARK_RED + ""); } if (msg.contains("#5")) { msg = msg.replaceAll("#5", ChatColor.DARK_PURPLE + ""); } if (msg.contains("#6")) { msg = msg.replaceAll("#6", ChatColor.GOLD + ""); } if (msg.contains("#7")) { msg = msg.replaceAll("#7", ChatColor.GRAY + ""); } if (msg.contains("#8")) { msg = msg.replaceAll("#8", ChatColor.DARK_GRAY + ""); } if (msg.contains("#9")) { msg = msg.replaceAll("#9", ChatColor.BLUE + ""); } if (msg.contains("#a") || msg.contains("#A")) { msg = msg.replaceAll("#A", ChatColor.GREEN + ""); msg = msg.replaceAll("#a", ChatColor.GREEN + ""); } if (msg.contains("#b") || msg.contains("#B")) { msg = msg.replaceAll("#B", ChatColor.AQUA + ""); msg = msg.replaceAll("#b", ChatColor.AQUA + ""); } if (msg.contains("#c") || msg.contains("#C")) { msg = msg.replaceAll("#C", ChatColor.RED + ""); msg = msg.replaceAll("#c", ChatColor.RED + ""); } if (msg.contains("#d") || msg.contains("#D")) { msg = msg.replaceAll("#D", ChatColor.LIGHT_PURPLE + ""); msg = msg.replaceAll("#d", ChatColor.LIGHT_PURPLE + ""); } if (msg.contains("#e") || msg.contains("#E")) { msg = msg.replaceAll("#E", ChatColor.YELLOW + ""); msg = msg.replaceAll("#e", ChatColor.YELLOW + ""); } if (msg.contains("#f") || msg.contains("#F")) { msg = msg.replaceAll("#F", ChatColor.WHITE + ""); msg = msg.replaceAll("#f", ChatColor.WHITE + ""); } if (msg.contains("#k") || msg.contains("#K")) { msg = msg.replaceAll("#K", ChatColor.MAGIC + ""); msg = msg.replaceAll("#k", ChatColor.MAGIC + ""); } if (msg.contains("#l") || msg.contains("#L")) { msg = msg.replaceAll("#L", ChatColor.BOLD + ""); msg = msg.replaceAll("#l", ChatColor.BOLD + ""); } if (msg.contains("#m") || msg.contains("#M")) { msg = msg.replaceAll("#M", ChatColor.STRIKETHROUGH + ""); msg = msg.replaceAll("#m", ChatColor.STRIKETHROUGH + ""); } if (msg.contains("#n") || msg.contains("#N")) { msg = msg.replaceAll("#N", ChatColor.UNDERLINE + ""); msg = msg.replaceAll("#n", ChatColor.UNDERLINE + ""); } if (msg.contains("#o") || msg.contains("#O")) { msg = msg.replaceAll("#O", ChatColor.ITALIC + ""); msg = msg.replaceAll("#o", ChatColor.ITALIC + ""); } } else { player.sendMessage(ChatColor.RED + "You are not allowed to use chat colors!"); } Collection<? extends Player> players = server.getOnlinePlayers(); for (Player tp : players) { GenericPlayer to = tregmine.getPlayer(tp); if (!channel.equals(to.getChatChannel())) { continue; } boolean ignored; try (IContext ctx = tregmine.createContext()) { IPlayerDAO playerDAO = ctx.getPlayerDAO(); ignored = playerDAO.doesIgnore(to, player); } catch (DAOException e) { throw new RuntimeException(e); } if (player.getRank().canNotBeIgnored()) ignored = false; if (ignored == true) continue; TextComponent begin = new TextComponent("* "); TextComponent middle = new TextComponent(player.decideVS(to)); TextComponent end = new TextComponent(" " + WHITE + msg); to.sendMessage(begin, middle, end); } Tregmine.LOGGER.info("* " + player.getName() + " " + msg); if (player.getRank() != Rank.SENIOR_ADMIN && player.getRank() != Rank.JUNIOR_ADMIN) { msg = msg.replaceAll("@everyone", "").replaceAll("@here", ""); } this.tregmine.getDiscordDelegate().getChatChannel().sendMessage("**" + player.getChatNameNoColor() + "** " + ChatColor.stripColor(msg)).complete(); return true; } }
Optimized color codes
src/main/java/info/tregmine/commands/ActionCommand.java
Optimized color codes
Java
mit
c7376eaded929e66931029641430ead2836e7350
0
Nunnery/MythicDrops
package net.nunnerycode.bukkit.mythicdrops.items; import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; import net.nunnerycode.bukkit.mythicdrops.api.enchantments.MythicEnchantment; import net.nunnerycode.bukkit.mythicdrops.api.items.ItemGenerationReason; import net.nunnerycode.bukkit.mythicdrops.api.items.MythicItemStack; import net.nunnerycode.bukkit.mythicdrops.api.items.NonrepairableItemStack; import net.nunnerycode.bukkit.mythicdrops.api.items.builders.DropBuilder; import net.nunnerycode.bukkit.mythicdrops.api.names.NameType; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.events.RandomItemGenerationEvent; import net.nunnerycode.bukkit.mythicdrops.names.NameMap; import net.nunnerycode.bukkit.mythicdrops.tiers.TierMap; import net.nunnerycode.bukkit.mythicdrops.utils.ItemStackUtil; import net.nunnerycode.bukkit.mythicdrops.utils.ItemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.RandomRangeUtil; import org.apache.commons.lang.Validate; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang.math.RandomUtils; import org.apache.commons.lang3.text.WordUtils; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.EnchantmentWrapper; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.material.MaterialData; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public final class MythicDropBuilder implements DropBuilder { private Tier tier; private MaterialData materialData; private ItemGenerationReason itemGenerationReason; private World world; private boolean useDurability; private boolean callEvent; public MythicDropBuilder() { tier = null; itemGenerationReason = ItemGenerationReason.DEFAULT; world = Bukkit.getServer().getWorlds().get(0); useDurability = false; callEvent = true; } public DropBuilder withCallEvent(boolean b) { this.callEvent = b; return this; } @Override public DropBuilder withTier(Tier tier) { this.tier = tier; return this; } @Override public DropBuilder withTier(String tierName) { this.tier = TierMap.getInstance().get(tierName); return this; } @Override public DropBuilder withMaterialData(MaterialData materialData) { this.materialData = materialData; return this; } @Override public DropBuilder withMaterialData(String materialDataString) { MaterialData matData = null; if (materialDataString.contains(";")) { String[] split = materialDataString.split(";"); matData = new MaterialData(NumberUtils.toInt(split[0], 0), (byte) NumberUtils.toInt(split[1], 0)); } else { matData = new MaterialData(NumberUtils.toInt(materialDataString, 0)); } this.materialData = matData; return this; } @Override public DropBuilder withItemGenerationReason(ItemGenerationReason reason) { this.itemGenerationReason = reason; return this; } @Override public DropBuilder inWorld(World world) { this.world = world; return this; } @Override public DropBuilder inWorld(String worldName) { this.world = Bukkit.getWorld(worldName); return this; } @Override public DropBuilder useDurability(boolean b) { this.useDurability = b; return this; } @Override public ItemStack build() { World w = world != null ? world : Bukkit.getWorlds().get(0); Tier t = (tier != null) ? tier : TierMap.getInstance().getRandomWithChance(w.getName()); if (t == null) { t = TierMap.getInstance().getRandomWithChance("default"); if (t == null) { return null; } } MaterialData md = (materialData != null) ? materialData : ItemUtil.getRandomMaterialDataFromCollection (ItemUtil.getMaterialDatasFromTier(t)); NonrepairableItemStack nis = new NonrepairableItemStack(md.getItemType(), 1, (short) 0, ""); ItemMeta im = nis.getItemMeta(); Map<Enchantment, Integer> baseEnchantmentMap = getBaseEnchantments(nis, t); Map<Enchantment, Integer> bonusEnchantmentMap = getBonusEnchantments(nis, t); for (Map.Entry<Enchantment, Integer> baseEnch : baseEnchantmentMap.entrySet()) { im.addEnchant(baseEnch.getKey(), baseEnch.getValue(), true); } for (Map.Entry<Enchantment, Integer> bonusEnch : bonusEnchantmentMap.entrySet()) { im.addEnchant(bonusEnch.getKey(), bonusEnch.getValue(), true); } if (useDurability) { nis.setDurability(ItemStackUtil.getDurabilityForMaterial(nis.getType(), t.getMinimumDurabilityPercentage (), t.getMaximumDurabilityPercentage())); } String name = generateName(nis); List<String> lore = generateLore(nis); im.setDisplayName(name); im.setLore(lore); if (nis.getItemMeta() instanceof LeatherArmorMeta) { ((LeatherArmorMeta) im).setColor(Color.fromRGB(RandomUtils.nextInt(255), RandomUtils.nextInt(255), RandomUtils.nextInt(255))); } nis.setItemMeta(im); if (callEvent) { RandomItemGenerationEvent rige = new RandomItemGenerationEvent(t, nis, itemGenerationReason); Bukkit.getPluginManager().callEvent(rige); if (rige.isCancelled()) { return null; } return rige.getItemStack(); } return nis; } private Map<Enchantment, Integer> getBonusEnchantments(MythicItemStack is, Tier t) { Validate.notNull(is, "MythicItemStack cannot be null"); Validate.notNull(t, "Tier cannot be null"); if (t.getBonusEnchantments().isEmpty()) { return new HashMap<>(); } Map<Enchantment, Integer> map = new HashMap<>(); int added = 0; int attempts = 0; int range = (int) RandomRangeUtil.randomRangeDoubleInclusive(t.getMinimumBonusEnchantments(), t.getMaximumBonusEnchantments()); MythicEnchantment[] array = t.getBonusEnchantments().toArray(new MythicEnchantment[t.getBonusEnchantments() .size()]); while (added < range && attempts < 10) { MythicEnchantment chosenEnch = array[RandomUtils.nextInt(array.length)]; if (chosenEnch == null || chosenEnch.getEnchantment() == null) { attempts++; continue; } Enchantment e = chosenEnch.getEnchantment(); int randLevel = (int) RandomRangeUtil.randomRangeLongInclusive(chosenEnch.getMinimumLevel(), chosenEnch.getMaximumLevel()); if (is.containsEnchantment(e)) { randLevel += is.getEnchantmentLevel(e); } if (t.isSafeBonusEnchantments() && e.canEnchantItem(is)) { if (t.isAllowHighBonusEnchantments()) { map.put(e, randLevel); } else { map.put(e, getAcceptableEnchantmentLevel(e, randLevel)); } } else if (!t.isSafeBonusEnchantments()) { if (t.isAllowHighBonusEnchantments()) { map.put(e, randLevel); } else { map.put(e, getAcceptableEnchantmentLevel(e, randLevel)); } } else { continue; } added++; } return map; } private Map<Enchantment, Integer> getBaseEnchantments(MythicItemStack is, Tier t) { Validate.notNull(is, "MythicItemStack cannot be null"); Validate.notNull(t, "Tier cannot be null"); if (t.getBaseEnchantments().isEmpty()) { return new HashMap<>(); } Map<Enchantment, Integer> map = new HashMap<>(); for (MythicEnchantment me : t.getBaseEnchantments()) { if (me == null || me.getEnchantment() == null) { continue; } Enchantment e = me.getEnchantment(); int minimumLevel = Math.max(me.getMinimumLevel(), e.getStartLevel()); int maximumLevel = Math.min(me.getMaximumLevel(), e.getMaxLevel()); if (t.isSafeBaseEnchantments() && e.canEnchantItem(is)) { if (t.isAllowHighBaseEnchantments()) { map.put(e, (int) RandomRangeUtil.randomRangeLongInclusive (minimumLevel, maximumLevel)); } else { map.put(e, getAcceptableEnchantmentLevel(e, (int) RandomRangeUtil.randomRangeLongInclusive(minimumLevel, maximumLevel))); } } else if (!t.isSafeBaseEnchantments()) { map.put(e, (int) RandomRangeUtil.randomRangeLongInclusive (minimumLevel, maximumLevel)); } } return map; } private int getAcceptableEnchantmentLevel(Enchantment ench, int level) { EnchantmentWrapper ew = new EnchantmentWrapper(ench.getId()); return Math.max(Math.min(level, ew.getMaxLevel()), ew.getStartLevel()); } private List<String> generateLore(ItemStack itemStack) { List<String> lore = new ArrayList<String>(); if (itemStack == null || tier == null) { return lore; } List<String> tooltipFormat = MythicDropsPlugin.getInstance().getConfigSettings().getTooltipFormat(); String minecraftName = getMinecraftMaterialName(itemStack.getData().getItemType()); String mythicName = getMythicMaterialName(itemStack.getData()); String itemType = getItemTypeName(ItemUtil.getItemTypeFromMaterialData(itemStack.getData())); String materialType = getItemTypeName(ItemUtil.getMaterialTypeFromMaterialData(itemStack.getData())); String tierName = tier.getDisplayName(); ItemMeta itemMeta = itemStack.getItemMeta(); String enchantment = getEnchantmentTypeName(itemMeta); if (MythicDropsPlugin.getInstance().getConfigSettings().isRandomLoreEnabled() && RandomUtils.nextDouble() < MythicDropsPlugin.getInstance().getConfigSettings().getRandomLoreChance()) { String generalLoreString = NameMap.getInstance().getRandom(NameType.GENERAL_LORE, ""); String materialLoreString = NameMap.getInstance().getRandom(NameType.MATERIAL_LORE, itemStack.getType().name().toLowerCase()); String tierLoreString = NameMap.getInstance().getRandom(NameType.TIER_LORE, tier.getName().toLowerCase()); String enchantmentLoreString = NameMap.getInstance().getRandom(NameType.ENCHANTMENT_LORE, enchantment != null ? enchantment.toLowerCase() : ""); List<String> generalLore = null; if (generalLoreString != null && !generalLoreString.isEmpty()) { generalLore = Arrays.asList(generalLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n")); } List<String> materialLore = null; if (materialLoreString != null && !materialLoreString.isEmpty()) { materialLore = Arrays.asList(materialLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n")); } List<String> tierLore = null; if (tierLoreString != null && !tierLoreString.isEmpty()) { tierLore = Arrays.asList(tierLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n")); } List<String> enchantmentLore = null; if (enchantmentLoreString != null && !enchantmentLoreString.isEmpty()) { enchantmentLore = Arrays.asList(enchantmentLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n")); } if (generalLore != null && !generalLore.isEmpty()) { lore.addAll(generalLore); } if (materialLore != null && !materialLore.isEmpty()) { lore.addAll(materialLore); } if (tierLore != null && !tierLore.isEmpty()) { lore.addAll(tierLore); } if (enchantmentLore != null && !enchantmentLore.isEmpty()) { lore.addAll(enchantmentLore); } } for (String s : tooltipFormat) { String line = s; line = line.replace("%basematerial%", minecraftName != null ? minecraftName : ""); line = line.replace("%mythicmaterial%", mythicName != null ? mythicName : ""); line = line.replace("%itemtype%", itemType != null ? itemType : ""); line = line.replace("%materialtype%", materialType != null ? materialType : ""); line = line.replace("%tiername%", tierName != null ? tierName : ""); line = line.replace("%enchantment%", enchantment != null ? enchantment : ""); line = line.replace('&', '\u00A7').replace("\u00A7\u00A7", "&"); lore.add(line); } for (String s : tier.getBaseLore()) { String[] strings = s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n"); lore.addAll(Arrays.asList(strings)); } int numOfBonusLore = (int) RandomRangeUtil.randomRangeLongInclusive(tier.getMinimumBonusLore(), tier.getMaximumBonusLore()); List<String> chosenLore = new ArrayList<>(); for (int i = 0; i < numOfBonusLore; i++) { if (tier.getBonusLore() == null || tier.getBonusLore().isEmpty() || chosenLore.size() == tier .getBonusLore().size()) { continue; } // choose a random String out of the tier's bonus lore String s = tier.getBonusLore().get(RandomUtils.nextInt(tier.getBonusLore().size())); if (chosenLore.contains(s)) { i--; continue; } chosenLore.add(s); // split on the next line /n String[] strings = s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n"); // add to lore by wrapping in Arrays.asList(Object...) lore.addAll(Arrays.asList(strings)); } if (MythicDropsPlugin.getInstance().getSockettingSettings().isEnabled() && RandomUtils.nextDouble() < tier .getChanceToHaveSockets()) { int numberOfSockets = (int) RandomRangeUtil.randomRangeLongInclusive(tier.getMinimumSockets(), tier.getMaximumSockets()); for (int i = 0; i < numberOfSockets; i++) { lore.add(MythicDropsPlugin.getInstance().getSockettingSettings().getSockettedItemString().replace ('&', '\u00A7').replace("\u00A7\u00A7", "&")); } if (numberOfSockets > 0) { for (String s : MythicDropsPlugin.getInstance().getSockettingSettings().getSockettedItemLore()) { lore.add(s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&")); } } } return lore; } private String getEnchantmentTypeName(ItemMeta itemMeta) { Enchantment enchantment = ItemStackUtil.getHighestEnchantment(itemMeta); if (enchantment == null) { return MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString("displayNames" + ".Ordinary"); } String ench = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString("displayNames." + enchantment.getName()); if (ench != null) { return ench; } return "Ordinary"; } private String getMythicMaterialName(MaterialData matData) { String comb = String.format("%s;%s", String.valueOf(matData.getItemTypeId()), String.valueOf(matData.getData())); String comb2; if (matData.getData() == (byte) 0) { comb2 = String.valueOf(matData.getItemTypeId()); } else { comb2 = comb; } String mythicMatName = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString( "displayNames." + comb.toLowerCase()); if (mythicMatName == null || mythicMatName.equals("displayNames." + comb.toLowerCase())) { mythicMatName = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString( "displayNames." + comb2.toLowerCase()); if (mythicMatName == null || mythicMatName.equals("displayNames." + comb2.toLowerCase())) { mythicMatName = getMinecraftMaterialName(matData.getItemType()); } } return WordUtils.capitalize(mythicMatName); } private String getMinecraftMaterialName(Material material) { String prettyMaterialName = ""; String matName = material.name(); String[] split = matName.split("_"); for (String s : split) { if (s.equals(split[split.length - 1])) { prettyMaterialName = String .format("%s%s%s", prettyMaterialName, s.substring(0, 1).toUpperCase(), s.substring(1, s.length()).toLowerCase()); } else { prettyMaterialName = prettyMaterialName + (String.format("%s%s", s.substring(0, 1).toUpperCase(), s.substring(1, s.length()).toLowerCase())) + " "; } } return WordUtils.capitalizeFully(prettyMaterialName); } private String getItemTypeName(String itemType) { if (itemType == null) { return null; } String mythicMatName = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString( "displayNames." + itemType.toLowerCase()); if (mythicMatName == null) { mythicMatName = itemType; } return WordUtils.capitalizeFully(mythicMatName); } private String getItemTypeFromMaterialData(MaterialData matData) { String comb = String.format("%s;%s", String.valueOf(matData.getItemTypeId()), String.valueOf(matData.getData())); String comb2; if (matData.getData() == (byte) 0) { comb2 = String.valueOf(matData.getItemTypeId()); } else { comb2 = comb; } String comb3 = String.valueOf(matData.getItemTypeId()); Map<String, List<String>> ids = new HashMap<String, List<String>>(); ids.putAll(MythicDropsPlugin.getInstance().getConfigSettings().getItemTypesWithIds()); for (Map.Entry<String, List<String>> e : ids.entrySet()) { if (e.getValue().contains(comb) || e.getValue().contains(comb2) || e.getValue().contains(comb3)) { if (MythicDropsPlugin.getInstance().getConfigSettings().getMaterialTypes().contains(e.getKey())) { continue; } return e.getKey(); } } return null; } private String generateName(ItemStack itemStack) { Validate.notNull(itemStack, "ItemStack cannot be null"); Validate.notNull(tier, "Tier cannot be null"); String format = MythicDropsPlugin.getInstance().getConfigSettings().getItemDisplayNameFormat(); if (format == null) { return "Mythic Item"; } String minecraftName = getMinecraftMaterialName(itemStack.getData().getItemType()); String mythicName = getMythicMaterialName(itemStack.getData()); String generalPrefix = NameMap.getInstance().getRandom(NameType.GENERAL_PREFIX, ""); String generalSuffix = NameMap.getInstance().getRandom(NameType.GENERAL_SUFFIX, ""); String materialPrefix = NameMap.getInstance().getRandom(NameType.MATERIAL_PREFIX, itemStack.getType().name().toLowerCase()); String materialSuffix = NameMap.getInstance().getRandom(NameType.MATERIAL_SUFFIX, itemStack.getType().name().toLowerCase()); String tierPrefix = NameMap.getInstance().getRandom(NameType.TIER_PREFIX, tier.getName().toLowerCase()); String tierSuffix = NameMap.getInstance().getRandom(NameType.TIER_SUFFIX, tier.getName().toLowerCase()); String itemType = ItemUtil.getItemTypeFromMaterialData(itemStack.getData()); String materialType = ItemUtil.getMaterialTypeFromMaterialData(itemStack.getData()); String tierName = tier.getDisplayName(); String enchantment = getEnchantmentTypeName(itemStack.getItemMeta()); Enchantment highestEnch = ItemStackUtil.getHighestEnchantment(itemStack.getItemMeta()); String enchantmentPrefix = NameMap.getInstance().getRandom(NameType.ENCHANTMENT_PREFIX, highestEnch != null ? highestEnch.getName().toLowerCase() : ""); String enchantmentSuffix = NameMap.getInstance().getRandom(NameType.ENCHANTMENT_SUFFIX, highestEnch != null ? highestEnch.getName().toLowerCase() : ""); String name = format; if (name.contains("%basematerial%")) { name = name.replace("%basematerial%", minecraftName); } if (name.contains("%mythicmaterial%")) { name = name.replace("%mythicmaterial%", mythicName); } if (name.contains("%generalprefix%")) { name = name.replace("%generalprefix%", generalPrefix); } if (name.contains("%generalsuffix%")) { name = name.replace("%generalsuffix%", generalSuffix); } if (name.contains("%materialprefix%")) { name = name.replace("%materialprefix%", materialPrefix); } if (name.contains("%materialsuffix%")) { name = name.replace("%materialsuffix%", materialSuffix); } if (name.contains("%tierprefix%")) { name = name.replace("%tierprefix%", tierPrefix); } if (name.contains("%tiersuffix%")) { name = name.replace("%tiersuffix%", tierSuffix); } if (name.contains("%itemtype%")) { name = name.replace("%itemtype%", itemType); } if (name.contains("%materialtype%")) { name = name.replace("%materialtype%", materialType); } if (name.contains("%tiername%")) { name = name.replace("%tiername%", tierName); } if (name.contains("%enchantment%")) { name = name.replace("%enchantment%", enchantment); } if (name.contains("%enchantmentprefix%")) { name = name.replace("%enchantmentprefix%", enchantmentPrefix); } if (name.contains("%enchantmentsuffix%")) { name = name.replace("%enchantmentsuffix%", enchantmentSuffix); } return tier.getDisplayColor() + name.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").trim() + tier.getIdentificationColor(); } }
MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/items/MythicDropBuilder.java
package net.nunnerycode.bukkit.mythicdrops.items; import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; import net.nunnerycode.bukkit.mythicdrops.api.enchantments.MythicEnchantment; import net.nunnerycode.bukkit.mythicdrops.api.items.ItemGenerationReason; import net.nunnerycode.bukkit.mythicdrops.api.items.MythicItemStack; import net.nunnerycode.bukkit.mythicdrops.api.items.NonrepairableItemStack; import net.nunnerycode.bukkit.mythicdrops.api.items.builders.DropBuilder; import net.nunnerycode.bukkit.mythicdrops.api.names.NameType; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.events.RandomItemGenerationEvent; import net.nunnerycode.bukkit.mythicdrops.names.NameMap; import net.nunnerycode.bukkit.mythicdrops.tiers.TierMap; import net.nunnerycode.bukkit.mythicdrops.utils.ItemStackUtil; import net.nunnerycode.bukkit.mythicdrops.utils.ItemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.RandomRangeUtil; import org.apache.commons.lang.Validate; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang.math.RandomUtils; import org.apache.commons.lang3.text.WordUtils; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.EnchantmentWrapper; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.material.MaterialData; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public final class MythicDropBuilder implements DropBuilder { private Tier tier; private MaterialData materialData; private ItemGenerationReason itemGenerationReason; private World world; private boolean useDurability; private boolean callEvent; public MythicDropBuilder() { tier = null; itemGenerationReason = ItemGenerationReason.DEFAULT; world = Bukkit.getServer().getWorlds().get(0); useDurability = false; callEvent = true; } public DropBuilder withCallEvent(boolean b) { this.callEvent = b; return this; } @Override public DropBuilder withTier(Tier tier) { this.tier = tier; return this; } @Override public DropBuilder withTier(String tierName) { this.tier = TierMap.getInstance().get(tierName); return this; } @Override public DropBuilder withMaterialData(MaterialData materialData) { this.materialData = materialData; return this; } @Override public DropBuilder withMaterialData(String materialDataString) { MaterialData matData = null; if (materialDataString.contains(";")) { String[] split = materialDataString.split(";"); matData = new MaterialData(NumberUtils.toInt(split[0], 0), (byte) NumberUtils.toInt(split[1], 0)); } else { matData = new MaterialData(NumberUtils.toInt(materialDataString, 0)); } this.materialData = matData; return this; } @Override public DropBuilder withItemGenerationReason(ItemGenerationReason reason) { this.itemGenerationReason = reason; return this; } @Override public DropBuilder inWorld(World world) { this.world = world; return this; } @Override public DropBuilder inWorld(String worldName) { this.world = Bukkit.getWorld(worldName); return this; } @Override public DropBuilder useDurability(boolean b) { this.useDurability = b; return this; } @Override public ItemStack build() { World w = world != null ? world : Bukkit.getWorlds().get(0); Tier t = (tier != null) ? tier : TierMap.getInstance().getRandomWithChance(w.getName()); if (t == null) { t = TierMap.getInstance().getRandomWithChance("default"); if (t == null) { return null; } } MaterialData md = (materialData != null) ? materialData : ItemUtil.getRandomMaterialDataFromCollection (ItemUtil.getMaterialDatasFromTier(t)); NonrepairableItemStack nis = new NonrepairableItemStack(md.getItemType(), 1, (short) 0, ""); ItemMeta im = nis.getItemMeta(); Map<Enchantment, Integer> baseEnchantmentMap = getBaseEnchantments(nis, t); Map<Enchantment, Integer> bonusEnchantmentMap = getBonusEnchantments(nis, t); for (Map.Entry<Enchantment, Integer> baseEnch : baseEnchantmentMap.entrySet()) { im.addEnchant(baseEnch.getKey(), baseEnch.getValue(), true); } for (Map.Entry<Enchantment, Integer> bonusEnch : bonusEnchantmentMap.entrySet()) { im.addEnchant(bonusEnch.getKey(), bonusEnch.getValue(), true); } if (useDurability) { nis.setDurability(ItemStackUtil.getDurabilityForMaterial(nis.getType(), t.getMinimumDurabilityPercentage (), t.getMaximumDurabilityPercentage())); } String name = generateName(nis); List<String> lore = generateLore(nis); im.setDisplayName(name); im.setLore(lore); if (nis.getItemMeta() instanceof LeatherArmorMeta) { ((LeatherArmorMeta) im).setColor(Color.fromRGB(RandomUtils.nextInt(255), RandomUtils.nextInt(255), RandomUtils.nextInt(255))); } nis.setItemMeta(im); if (callEvent) { RandomItemGenerationEvent rige = new RandomItemGenerationEvent(t, nis, itemGenerationReason); Bukkit.getPluginManager().callEvent(rige); if (rige.isCancelled()) { return null; } return rige.getItemStack(); } return nis; } private Map<Enchantment, Integer> getBonusEnchantments(MythicItemStack is, Tier t) { Validate.notNull(is, "MythicItemStack cannot be null"); Validate.notNull(t, "Tier cannot be null"); if (t.getBonusEnchantments().isEmpty()) { return new HashMap<>(); } Map<Enchantment, Integer> map = new HashMap<>(); int added = 0; int attempts = 0; int range = (int) RandomRangeUtil.randomRangeDoubleInclusive(t.getMinimumBonusEnchantments(), t.getMaximumBonusEnchantments()); MythicEnchantment[] array = t.getBonusEnchantments().toArray(new MythicEnchantment[t.getBonusEnchantments() .size()]); while (added < range && attempts < 10) { MythicEnchantment chosenEnch = array[RandomUtils.nextInt(array.length)]; if (chosenEnch == null || chosenEnch.getEnchantment() == null) { attempts++; continue; } Enchantment e = chosenEnch.getEnchantment(); int randLevel = (int) RandomRangeUtil.randomRangeLongInclusive(chosenEnch.getMinimumLevel(), chosenEnch.getMaximumLevel()); if (is.containsEnchantment(e)) { randLevel += is.getEnchantmentLevel(e); } if (t.isSafeBonusEnchantments() && e.canEnchantItem(is)) { if (t.isAllowHighBonusEnchantments()) { map.put(e, randLevel); } else { map.put(e, getAcceptableEnchantmentLevel(e, randLevel)); } } else if (!t.isSafeBonusEnchantments()) { if (t.isAllowHighBonusEnchantments()) { map.put(e, randLevel); } else { map.put(e, getAcceptableEnchantmentLevel(e, randLevel)); } } else { continue; } added++; } return map; } private Map<Enchantment, Integer> getBaseEnchantments(MythicItemStack is, Tier t) { Validate.notNull(is, "MythicItemStack cannot be null"); Validate.notNull(t, "Tier cannot be null"); if (t.getBaseEnchantments().isEmpty()) { return new HashMap<>(); } Map<Enchantment, Integer> map = new HashMap<>(); for (MythicEnchantment me : t.getBaseEnchantments()) { if (me == null || me.getEnchantment() == null) { continue; } Enchantment e = me.getEnchantment(); int minimumLevel = Math.max(me.getMinimumLevel(), e.getStartLevel()); int maximumLevel = Math.min(me.getMaximumLevel(), e.getMaxLevel()); if (t.isSafeBaseEnchantments() && e.canEnchantItem(is)) { if (t.isAllowHighBaseEnchantments()) { map.put(e, (int) RandomRangeUtil.randomRangeLongInclusive (minimumLevel, maximumLevel)); } else { map.put(e, getAcceptableEnchantmentLevel(e, (int) RandomRangeUtil.randomRangeLongInclusive(minimumLevel, maximumLevel))); } } else if (!t.isSafeBaseEnchantments()) { map.put(e, (int) RandomRangeUtil.randomRangeLongInclusive (minimumLevel, maximumLevel)); } } return map; } private int getAcceptableEnchantmentLevel(Enchantment ench, int level) { EnchantmentWrapper ew = new EnchantmentWrapper(ench.getId()); return Math.max(Math.min(level, ew.getMaxLevel()), ew.getStartLevel()); } private List<String> generateLore(ItemStack itemStack) { List<String> lore = new ArrayList<String>(); if (itemStack == null || tier == null) { return lore; } List<String> tooltipFormat = MythicDropsPlugin.getInstance().getConfigSettings().getTooltipFormat(); String minecraftName = getMinecraftMaterialName(itemStack.getData().getItemType()); String mythicName = getMythicMaterialName(itemStack.getData()); String itemType = getItemTypeName(ItemUtil.getItemTypeFromMaterialData(itemStack.getData())); String materialType = getItemTypeName(ItemUtil.getMaterialTypeFromMaterialData(itemStack.getData())); String tierName = tier.getDisplayName(); ItemMeta itemMeta = itemStack.getItemMeta(); String enchantment = getEnchantmentTypeName(itemMeta); if (MythicDropsPlugin.getInstance().getConfigSettings().isRandomLoreEnabled() && RandomUtils.nextDouble() < MythicDropsPlugin.getInstance().getConfigSettings().getRandomLoreChance()) { String generalLoreString = NameMap.getInstance().getRandom(NameType.GENERAL_LORE, ""); String materialLoreString = NameMap.getInstance().getRandom(NameType.MATERIAL_LORE, itemStack.getType().name()); String tierLoreString = NameMap.getInstance().getRandom(NameType.TIER_LORE, tier.getName()); String enchantmentLoreString = NameMap.getInstance().getRandom(NameType.ENCHANTMENT_LORE, enchantment != null ? enchantment : ""); List<String> generalLore = null; if (generalLoreString != null && !generalLoreString.isEmpty()) { generalLore = Arrays.asList(generalLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n")); } List<String> materialLore = null; if (materialLoreString != null && !materialLoreString.isEmpty()) { materialLore = Arrays.asList(materialLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n")); } List<String> tierLore = null; if (tierLoreString != null && !tierLoreString.isEmpty()) { tierLore = Arrays.asList(tierLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n")); } List<String> enchantmentLore = null; if (enchantmentLoreString != null && !enchantmentLoreString.isEmpty()) { enchantmentLore = Arrays.asList(enchantmentLoreString.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n")); } if (generalLore != null && !generalLore.isEmpty()) { lore.addAll(generalLore); } if (materialLore != null && !materialLore.isEmpty()) { lore.addAll(materialLore); } if (tierLore != null && !tierLore.isEmpty()) { lore.addAll(tierLore); } if (enchantmentLore != null && !enchantmentLore.isEmpty()) { lore.addAll(enchantmentLore); } } for (String s : tooltipFormat) { String line = s; line = line.replace("%basematerial%", minecraftName != null ? minecraftName : ""); line = line.replace("%mythicmaterial%", mythicName != null ? mythicName : ""); line = line.replace("%itemtype%", itemType != null ? itemType : ""); line = line.replace("%materialtype%", materialType != null ? materialType : ""); line = line.replace("%tiername%", tierName != null ? tierName : ""); line = line.replace("%enchantment%", enchantment != null ? enchantment : ""); line = line.replace('&', '\u00A7').replace("\u00A7\u00A7", "&"); lore.add(line); } for (String s : tier.getBaseLore()) { String[] strings = s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n"); lore.addAll(Arrays.asList(strings)); } int numOfBonusLore = (int) RandomRangeUtil.randomRangeLongInclusive(tier.getMinimumBonusLore(), tier.getMaximumBonusLore()); List<String> chosenLore = new ArrayList<>(); for (int i = 0; i < numOfBonusLore; i++) { if (tier.getBonusLore() == null || tier.getBonusLore().isEmpty() || chosenLore.size() == tier .getBonusLore().size()) { continue; } // choose a random String out of the tier's bonus lore String s = tier.getBonusLore().get(RandomUtils.nextInt(tier.getBonusLore().size())); if (chosenLore.contains(s)) { i--; continue; } chosenLore.add(s); // split on the next line /n String[] strings = s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").split("/n"); // add to lore by wrapping in Arrays.asList(Object...) lore.addAll(Arrays.asList(strings)); } if (MythicDropsPlugin.getInstance().getSockettingSettings().isEnabled() && RandomUtils.nextDouble() < tier .getChanceToHaveSockets()) { int numberOfSockets = (int) RandomRangeUtil.randomRangeLongInclusive(tier.getMinimumSockets(), tier.getMaximumSockets()); for (int i = 0; i < numberOfSockets; i++) { lore.add(MythicDropsPlugin.getInstance().getSockettingSettings().getSockettedItemString().replace ('&', '\u00A7').replace("\u00A7\u00A7", "&")); } if (numberOfSockets > 0) { for (String s : MythicDropsPlugin.getInstance().getSockettingSettings().getSockettedItemLore()) { lore.add(s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&")); } } } return lore; } private String getEnchantmentTypeName(ItemMeta itemMeta) { Enchantment enchantment = ItemStackUtil.getHighestEnchantment(itemMeta); if (enchantment == null) { return MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString("displayNames" + ".Ordinary"); } String ench = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString("displayNames." + enchantment.getName()); if (ench != null) { return ench; } return "Ordinary"; } private String getMythicMaterialName(MaterialData matData) { String comb = String.format("%s;%s", String.valueOf(matData.getItemTypeId()), String.valueOf(matData.getData())); String comb2; if (matData.getData() == (byte) 0) { comb2 = String.valueOf(matData.getItemTypeId()); } else { comb2 = comb; } String mythicMatName = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString( "displayNames." + comb.toLowerCase()); if (mythicMatName == null || mythicMatName.equals("displayNames." + comb.toLowerCase())) { mythicMatName = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString( "displayNames." + comb2.toLowerCase()); if (mythicMatName == null || mythicMatName.equals("displayNames." + comb2.toLowerCase())) { mythicMatName = getMinecraftMaterialName(matData.getItemType()); } } return WordUtils.capitalize(mythicMatName); } private String getMinecraftMaterialName(Material material) { String prettyMaterialName = ""; String matName = material.name(); String[] split = matName.split("_"); for (String s : split) { if (s.equals(split[split.length - 1])) { prettyMaterialName = String .format("%s%s%s", prettyMaterialName, s.substring(0, 1).toUpperCase(), s.substring(1, s.length()).toLowerCase()); } else { prettyMaterialName = prettyMaterialName + (String.format("%s%s", s.substring(0, 1).toUpperCase(), s.substring(1, s.length()).toLowerCase())) + " "; } } return WordUtils.capitalizeFully(prettyMaterialName); } private String getItemTypeName(String itemType) { if (itemType == null) { return null; } String mythicMatName = MythicDropsPlugin.getInstance().getConfigSettings().getFormattedLanguageString( "displayNames." + itemType.toLowerCase()); if (mythicMatName == null) { mythicMatName = itemType; } return WordUtils.capitalizeFully(mythicMatName); } private String getItemTypeFromMaterialData(MaterialData matData) { String comb = String.format("%s;%s", String.valueOf(matData.getItemTypeId()), String.valueOf(matData.getData())); String comb2; if (matData.getData() == (byte) 0) { comb2 = String.valueOf(matData.getItemTypeId()); } else { comb2 = comb; } String comb3 = String.valueOf(matData.getItemTypeId()); Map<String, List<String>> ids = new HashMap<String, List<String>>(); ids.putAll(MythicDropsPlugin.getInstance().getConfigSettings().getItemTypesWithIds()); for (Map.Entry<String, List<String>> e : ids.entrySet()) { if (e.getValue().contains(comb) || e.getValue().contains(comb2) || e.getValue().contains(comb3)) { if (MythicDropsPlugin.getInstance().getConfigSettings().getMaterialTypes().contains(e.getKey())) { continue; } return e.getKey(); } } return null; } private String generateName(ItemStack itemStack) { Validate.notNull(itemStack, "ItemStack cannot be null"); Validate.notNull(tier, "Tier cannot be null"); String format = MythicDropsPlugin.getInstance().getConfigSettings().getItemDisplayNameFormat(); if (format == null) { return "Mythic Item"; } String minecraftName = getMinecraftMaterialName(itemStack.getData().getItemType()); String mythicName = getMythicMaterialName(itemStack.getData()); String generalPrefix = NameMap.getInstance().getRandom(NameType.GENERAL_PREFIX, ""); String generalSuffix = NameMap.getInstance().getRandom(NameType.GENERAL_SUFFIX, ""); String materialPrefix = NameMap.getInstance().getRandom(NameType.MATERIAL_PREFIX, itemStack.getType().name().toLowerCase()); String materialSuffix = NameMap.getInstance().getRandom(NameType.MATERIAL_SUFFIX, itemStack.getType().name().toLowerCase()); String tierPrefix = NameMap.getInstance().getRandom(NameType.TIER_PREFIX, tier.getName().toLowerCase()); String tierSuffix = NameMap.getInstance().getRandom(NameType.TIER_SUFFIX, tier.getName().toLowerCase()); String itemType = ItemUtil.getItemTypeFromMaterialData(itemStack.getData()); String materialType = ItemUtil.getMaterialTypeFromMaterialData(itemStack.getData()); String tierName = tier.getDisplayName(); String enchantment = getEnchantmentTypeName(itemStack.getItemMeta()); Enchantment highestEnch = ItemStackUtil.getHighestEnchantment(itemStack.getItemMeta()); String enchantmentPrefix = NameMap.getInstance().getRandom(NameType.ENCHANTMENT_PREFIX, highestEnch != null ? highestEnch.getName().toLowerCase() : ""); String enchantmentSuffix = NameMap.getInstance().getRandom(NameType.ENCHANTMENT_SUFFIX, highestEnch != null ? highestEnch.getName().toLowerCase() : ""); String name = format; if (name.contains("%basematerial%")) { name = name.replace("%basematerial%", minecraftName); } if (name.contains("%mythicmaterial%")) { name = name.replace("%mythicmaterial%", mythicName); } if (name.contains("%generalprefix%")) { name = name.replace("%generalprefix%", generalPrefix); } if (name.contains("%generalsuffix%")) { name = name.replace("%generalsuffix%", generalSuffix); } if (name.contains("%materialprefix%")) { name = name.replace("%materialprefix%", materialPrefix); } if (name.contains("%materialsuffix%")) { name = name.replace("%materialsuffix%", materialSuffix); } if (name.contains("%tierprefix%")) { name = name.replace("%tierprefix%", tierPrefix); } if (name.contains("%tiersuffix%")) { name = name.replace("%tiersuffix%", tierSuffix); } if (name.contains("%itemtype%")) { name = name.replace("%itemtype%", itemType); } if (name.contains("%materialtype%")) { name = name.replace("%materialtype%", materialType); } if (name.contains("%tiername%")) { name = name.replace("%tiername%", tierName); } if (name.contains("%enchantment%")) { name = name.replace("%enchantment%", enchantment); } if (name.contains("%enchantmentprefix%")) { name = name.replace("%enchantmentprefix%", enchantmentPrefix); } if (name.contains("%enchantmentsuffix%")) { name = name.replace("%enchantmentsuffix%", enchantmentSuffix); } return tier.getDisplayColor() + name.replace('&', '\u00A7').replace("\u00A7\u00A7", "&").trim() + tier.getIdentificationColor(); } }
hopefully a fix for no material lore working
MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/items/MythicDropBuilder.java
hopefully a fix for no material lore working
Java
mit
8efd20fa7cbc21c58ecd342e25e3c0e2de2afb2b
0
gems-uff/oceano,gems-uff/oceano,gems-uff/oceano,gems-uff/oceano,gems-uff/oceano,gems-uff/oceano
core/src/main/java/br/uff/ic/oceano/core/control/ConfigCtrl.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.uff.ic.oceano.core.control; import br.uff.ic.oceano.core.tools.maven.MavenUtil; /** * * @author daniel heráclio */ public class ConfigCtrl { }
Removed unused class.
core/src/main/java/br/uff/ic/oceano/core/control/ConfigCtrl.java
Removed unused class.
Java
mit
3ed7491d5b1272177b4a47fad2ddcffd084cbd9e
0
Codeforces/inmemo
package com.codeforces.inmemo; import org.apache.commons.lang.ObjectUtils; import org.apache.log4j.Logger; import org.jacuzzi.core.Jacuzzi; import org.jacuzzi.core.Row; import org.jacuzzi.core.TypeOracle; import javax.sql.DataSource; import java.util.*; /** * @author MikeMirzayanov ([email protected]) */ class TableUpdater<T extends HasId> { private static final Logger logger = Logger.getLogger(TableUpdater.class); private static final int MAX_ROWS_IN_SINGLE_SQL_STATEMENT = 200_000; private static DataSource dataSource; private static final Collection<TableUpdater<? extends HasId>> instances = new ArrayList<>(); private final Table table; private final Thread thread; private final String threadName; private volatile boolean running; private final Jacuzzi jacuzzi; private final TypeOracle<T> typeOracle; private Object lastIndicatorValue; /** * Delay after meaningless update try. */ private static final long rescanTimeMillis = 500; private final Collection<Long> lastUpdatedEntityIds = new HashSet<>(); TableUpdater(final Table<T> table, Object initialIndicatorValue) { if (dataSource == null) { logger.error("It should be called static Inmemo#setDataSource() before any instance of TableUpdater."); throw new InmemoException("It should be called static Inmemo#setDataSource() before any instance of TableUpdater."); } this.table = table; this.lastIndicatorValue = initialIndicatorValue; jacuzzi = Jacuzzi.getJacuzzi(dataSource); typeOracle = TypeOracle.getTypeOracle(table.getClazz()); threadName = "InmemoUpdater#" + table.getClazz(); thread = new Thread(new TableUpdaterRunnable(), threadName); thread.setDaemon(true); logger.info("Started Inmemo table updater thread '" + threadName + "'."); //noinspection ThisEscapedInObjectConstruction instances.add(this); } @SuppressWarnings("UnusedDeclaration") static void setDataSource(final DataSource dataSource) { TableUpdater.dataSource = dataSource; } @SuppressWarnings("UnusedDeclaration") static void stop() { for (final TableUpdater<? extends HasId> instance : instances) { instance.running = false; } } void start() { running = true; thread.start(); } private void update() { long startTimeMillis = System.currentTimeMillis(); final List<Row> rows = getRecentlyChangedRows(lastIndicatorValue); if (rows.size() >= 10) { logger.info(String.format("Thread '%s' has found %s rows to update in %d ms.", threadName, rows.size(), System.currentTimeMillis() - startTimeMillis)); } int updatedCount = 0; final Object previousIndicatorLastValue = lastIndicatorValue; final boolean hasInsertOrUpdateByItem = table.hasInsertOrUpdateByItem(); final boolean hasInsertOrUpdateByRow = table.hasInsertOrUpdateByRow(); for (final Row row : rows) { long id = getRowId(row); if (ObjectUtils.equals(row.get(table.getIndicatorField()), previousIndicatorLastValue) && lastUpdatedEntityIds.contains(id)) { continue; } if (hasInsertOrUpdateByItem) { final T entity = typeOracle.convertFromRow(row); table.insertOrUpdate(entity); } if (hasInsertOrUpdateByRow) { table.insertOrUpdate(row); } // logger.log(Level.INFO, "Updated entity " + entity + '.'); lastIndicatorValue = row.get(table.getIndicatorField()); ++updatedCount; } if (updatedCount >= 10) { logger.info(String.format("Thread '%s' has updated %d items in %d ms.", threadName, updatedCount, System.currentTimeMillis() - startTimeMillis)); } if (rows.size() <= lastUpdatedEntityIds.size()) { table.setPreloaded(true); } lastUpdatedEntityIds.clear(); for (final Row row : rows) { if (ObjectUtils.equals(row.get(table.getIndicatorField()), lastIndicatorValue)) { lastUpdatedEntityIds.add(getRowId(row)); } } sleepBetweenRescans(updatedCount); } private long getRowId(Row row) { Long id = (Long) row.get("id"); if (id == null) { id = (Long) row.get("ID"); } return id; } private void sleepBetweenRescans(final int updatedCount) { if (updatedCount == 0) { sleep(rescanTimeMillis); } else if ((updatedCount << 1) > MAX_ROWS_IN_SINGLE_SQL_STATEMENT) { logger.info(String.format( "Thread '%s' will not sleep because it updated near maximum row count.", threadName )); } else { sleep(rescanTimeMillis / 10); } } private void sleep(final long timeMillis) { try { Thread.sleep(timeMillis); } catch (InterruptedException e) { logger.error("Thread '" + threadName + "' has been stopped because of InterruptedException.", e); running = false; } } private List<Row> getRecentlyChangedRows(final Object indicatorLastValue) { final List<Row> rows; final long startTimeMillis = System.currentTimeMillis(); final String forceIndexClause = table.getDatabaseIndex() == null ? "" : ("FORCE INDEX (" + table.getDatabaseIndex() + ")"); if (indicatorLastValue == null) { rows = jacuzzi.findRows( String.format( "SELECT * FROM %s %s ORDER BY %s, %s LIMIT %d", typeOracle.getTableName(), forceIndexClause, table.getIndicatorField(), typeOracle.getIdColumn(), MAX_ROWS_IN_SINGLE_SQL_STATEMENT ) ); } else { rows = jacuzzi.findRows( String.format( "SELECT * FROM %s %s WHERE %s >= ? ORDER BY %s, %s LIMIT %d", typeOracle.getTableName(), forceIndexClause, table.getIndicatorField(), table.getIndicatorField(), typeOracle.getIdColumn(), MAX_ROWS_IN_SINGLE_SQL_STATEMENT ), indicatorLastValue ); } final long queryTimeMillis = System.currentTimeMillis() - startTimeMillis; if (queryTimeMillis * 10 > rescanTimeMillis) { logger.warn(String.format( "Rescanning query for entity `%s` took too long time %d ms.", table.getClazz().getName(), queryTimeMillis )); } final int rowCount = rows.size(); if (rowCount == MAX_ROWS_IN_SINGLE_SQL_STATEMENT) { logger.warn(String.format( "Suspicious row count while rescanning `%s` [rowCount=%d, queryTime=%d ms].", table.getClazz().getName(), MAX_ROWS_IN_SINGLE_SQL_STATEMENT, queryTimeMillis )); } return rows; } private class TableUpdaterRunnable implements Runnable { @Override public void run() { while (running) { try { update(); } catch (Exception e) { logger.error("Unexpected " + e.getClass().getName() + " exception in TableUpdaterRunnable of " + threadName + ": " + e, e); } } } } }
src/main/java/com/codeforces/inmemo/TableUpdater.java
package com.codeforces.inmemo; import org.apache.commons.lang.ObjectUtils; import org.apache.log4j.Logger; import org.jacuzzi.core.Jacuzzi; import org.jacuzzi.core.Row; import org.jacuzzi.core.TypeOracle; import javax.sql.DataSource; import java.util.*; /** * @author MikeMirzayanov ([email protected]) */ class TableUpdater<T extends HasId> { private static final Logger logger = Logger.getLogger(TableUpdater.class); private static final int MAX_ROWS_IN_SINGLE_SQL_STATEMENT = 200_000; private static DataSource dataSource; private static final Collection<TableUpdater<? extends HasId>> instances = new ArrayList<>(); private final Table table; private final Thread thread; private final String threadName; private volatile boolean running; private final Jacuzzi jacuzzi; private final TypeOracle<T> typeOracle; private Object lastIndicatorValue; /** * Delay after meaningless update try. */ private static final long rescanTimeMillis = 500; private final Collection<Long> lastUpdatedEntityIds = new HashSet<>(); TableUpdater(final Table<T> table, Object initialIndicatorValue) { if (dataSource == null) { logger.error("It should be called static Inmemo#setDataSource() before any instance of TableUpdater."); throw new InmemoException("It should be called static Inmemo#setDataSource() before any instance of TableUpdater."); } this.table = table; this.lastIndicatorValue = initialIndicatorValue; jacuzzi = Jacuzzi.getJacuzzi(dataSource); typeOracle = TypeOracle.getTypeOracle(table.getClazz()); threadName = "InmemoUpdater#" + table.getClazz(); thread = new Thread(new TableUpdaterRunnable(), threadName); thread.setDaemon(true); logger.info("Started Inmemo table updater thread '" + threadName + "'."); //noinspection ThisEscapedInObjectConstruction instances.add(this); } @SuppressWarnings("UnusedDeclaration") static void setDataSource(final DataSource dataSource) { TableUpdater.dataSource = dataSource; } @SuppressWarnings("UnusedDeclaration") static void stop() { for (final TableUpdater<? extends HasId> instance : instances) { instance.running = false; } } void start() { running = true; thread.start(); } private void update() { long startTimeMillis = System.currentTimeMillis(); final List<Row> rows = getRecentlyChangedRows(lastIndicatorValue); if (rows.size() >= 10) { logger.info(String.format("Thread '%s' has found %s rows to update in %d ms.", threadName, rows.size(), System.currentTimeMillis() - startTimeMillis)); } int updatedCount = 0; final Object previousIndicatorLastValue = lastIndicatorValue; final boolean hasInsertOrUpdateByItem = table.hasInsertOrUpdateByItem(); final boolean hasInsertOrUpdateByRow = table.hasInsertOrUpdateByRow(); for (final Row row : rows) { long id = getRowId(row); if (ObjectUtils.equals(row.get(table.getIndicatorField()), previousIndicatorLastValue) && lastUpdatedEntityIds.contains(id)) { continue; } if (hasInsertOrUpdateByItem) { final T entity = typeOracle.convertFromRow(row); table.insertOrUpdate(entity); } if (hasInsertOrUpdateByRow) { table.insertOrUpdate(row); } // logger.log(Level.INFO, "Updated entity " + entity + '.'); lastIndicatorValue = row.get(table.getIndicatorField()); ++updatedCount; } if (updatedCount > 0) { logger.info(String.format("Thread '%s' has updated %d items in %d ms.", threadName, updatedCount, System.currentTimeMillis() - startTimeMillis)); } if (rows.size() <= lastUpdatedEntityIds.size()) { table.setPreloaded(true); } lastUpdatedEntityIds.clear(); for (final Row row : rows) { if (ObjectUtils.equals(row.get(table.getIndicatorField()), lastIndicatorValue)) { lastUpdatedEntityIds.add(getRowId(row)); } } sleepBetweenRescans(updatedCount); } private long getRowId(Row row) { Long id = (Long) row.get("id"); if (id == null) { id = (Long) row.get("ID"); } return id; } private void sleepBetweenRescans(final int updatedCount) { if (updatedCount == 0) { sleep(rescanTimeMillis); } else if ((updatedCount << 1) > MAX_ROWS_IN_SINGLE_SQL_STATEMENT) { logger.info(String.format( "Thread '%s' will not sleep because it updated near maximum row count.", threadName )); } else { sleep(rescanTimeMillis / 10); } } private void sleep(final long timeMillis) { try { Thread.sleep(timeMillis); } catch (InterruptedException e) { logger.error("Thread '" + threadName + "' has been stopped because of InterruptedException.", e); running = false; } } private List<Row> getRecentlyChangedRows(final Object indicatorLastValue) { final List<Row> rows; final long startTimeMillis = System.currentTimeMillis(); final String forceIndexClause = table.getDatabaseIndex() == null ? "" : ("FORCE INDEX (" + table.getDatabaseIndex() + ")"); if (indicatorLastValue == null) { rows = jacuzzi.findRows( String.format( "SELECT * FROM %s %s ORDER BY %s, %s LIMIT %d", typeOracle.getTableName(), forceIndexClause, table.getIndicatorField(), typeOracle.getIdColumn(), MAX_ROWS_IN_SINGLE_SQL_STATEMENT ) ); } else { rows = jacuzzi.findRows( String.format( "SELECT * FROM %s %s WHERE %s >= ? ORDER BY %s, %s LIMIT %d", typeOracle.getTableName(), forceIndexClause, table.getIndicatorField(), table.getIndicatorField(), typeOracle.getIdColumn(), MAX_ROWS_IN_SINGLE_SQL_STATEMENT ), indicatorLastValue ); } final long queryTimeMillis = System.currentTimeMillis() - startTimeMillis; if (queryTimeMillis * 10 > rescanTimeMillis) { logger.warn(String.format( "Rescanning query for entity `%s` took too long time %d ms.", table.getClazz().getName(), queryTimeMillis )); } final int rowCount = rows.size(); if (rowCount == MAX_ROWS_IN_SINGLE_SQL_STATEMENT) { logger.warn(String.format( "Suspicious row count while rescanning `%s` [rowCount=%d, queryTime=%d ms].", table.getClazz().getName(), MAX_ROWS_IN_SINGLE_SQL_STATEMENT, queryTimeMillis )); } return rows; } private class TableUpdaterRunnable implements Runnable { @Override public void run() { while (running) { try { update(); } catch (Exception e) { logger.error("Unexpected " + e.getClass().getName() + " exception in TableUpdaterRunnable of " + threadName + ": " + e, e); } } } } }
- log messages about row updates now will appear iff at least 10 rows were updated.
src/main/java/com/codeforces/inmemo/TableUpdater.java
- log messages about row updates now will appear iff at least 10 rows were updated.
Java
mit
0bf11fbdcdcfc486985c9f4d01a0c9c79275ec74
0
lucmoreau/OpenProvenanceModel
package org.openprovenance.model; import java.util.List; import java.util.HashMap; import java.util.LinkedList; import java.io.File; import java.io.PrintStream; import java.io.FileOutputStream; import java.io.OutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBElement; import org.w3c.dom.Element; /** Serialisation of OPM Graphs to DOT format. */ public class OPMToDot { OPMUtilities u=new OPMUtilities(); OPMFactory of=new OPMFactory(); public OPMToDot() { init(); } public void init() { processNameMap.put("http://process.org/add1ToAll","add1ToAll"); processNameMap.put("http://process.org/split","split"); processNameMap.put("http://process.org/plus1","+1"); processNameMap.put("http://process.org/cons","cons"); processNameMap.put("http://process.org/fry","fry"); processNameMap.put("http://process.org/bake","bake"); processNameMap.put("http://process.org/badBake","badBake"); edgeStyleMap.put("org.openprovenance.model.Used","dotted"); edgeStyleMap.put("org.openprovenance.model.WasGeneratedBy","dotted"); edgeStyleMap.put("org.openprovenance.model.WasDerivedFrom","bold"); accountColourMap.put("orange","red"); defaultEdgeStyle="filled"; this.name="OPMGraph"; this.defaultAccountLabel="black"; this.displayProcessValue=true; this.displayArtifactValue=true; } public void convert(OPMGraph graph, String dotFile, String pdfFile) throws java.io.FileNotFoundException, java.io.IOException { convert(graph,new File(dotFile)); Runtime runtime = Runtime.getRuntime(); java.lang.Process proc = runtime.exec("dot -o " + pdfFile + " -Tpdf " + dotFile); } public void convert(OPMGraph graph, File file) throws java.io.FileNotFoundException{ OutputStream os=new FileOutputStream(file); convert(graph, new PrintStream(os)); } public void convert(OPMGraph graph, PrintStream out) { List<Edge> edges=u.getEdges(graph); prelude(out); if (graph.getProcesses()!=null) { for (Process p: graph.getProcesses().getProcess()) { emitProcess(p,out); } } if (graph.getArtifacts()!=null) { for (Artifact p: graph.getArtifacts().getArtifact()) { emitArtifact(p,out); } } if (graph.getAgents()!=null) { for (Agent p: graph.getAgents().getAgent()) { emitAgent(p,out); } } for (Edge e: edges) { emitDependency(e,out); } postlude(out); } ////////////////////////////////////////////////////////////////////// /// /// NODES /// ////////////////////////////////////////////////////////////////////// public void emitProcess(Process p, PrintStream out) { HashMap<String,String> properties=new HashMap(); emitNode(p.getId(), addProcessShape(p,addProcessLabel(p, properties)), out); } public void emitArtifact(Artifact a, PrintStream out) { HashMap<String,String> properties=new HashMap(); emitNode(a.getId(), addArtifactShape(a,addArtifactLabel(a, properties)), out); } public void emitAgent(Agent ag, PrintStream out) { HashMap<String,String> properties=new HashMap(); emitNode(ag.getId(), addAgentShape(ag,addAgentLabel(ag, properties)), out); } public HashMap<String,String> addProcessShape(Process p, HashMap<String,String> properties) { properties.put("shape","poligon"); properties.put("sides","4"); return properties; } public HashMap<String,String> addProcessLabel(Process p, HashMap<String,String> properties) { properties.put("label",processLabel(p)); return properties; } public HashMap<String,String> addArtifactShape(Artifact p, HashMap<String,String> properties) { // default is good for artifact return properties; } public HashMap<String,String> addArtifactLabel(Artifact p, HashMap<String,String> properties) { properties.put("label",artifactLabel(p)); return properties; } public HashMap<String,String> addAgentShape(Agent p, HashMap<String,String> properties) { properties.put("shape","poligon"); properties.put("sides","5"); return properties; } public HashMap<String,String> addAgentLabel(Agent p, HashMap<String,String> properties) { properties.put("label",agentLabel(p)); return properties; } boolean displayProcessValue; boolean displayArtifactValue; boolean displayAgentValue; public String processLabel(Process p) { if (displayProcessValue) { return convertProcessName(""+p.getValue()); } else { return p.getId(); } } public String artifactLabel(Artifact p) { if (displayArtifactValue) { return convertArtifactName(""+p.getValue()); } else { return p.getId(); } } public String agentLabel(Agent p) { if (displayAgentValue) { return convertAgentName(""+p.getValue()); } else { return p.getId(); } } HashMap<String,String> processNameMap=new HashMap<String,String>(); public String convertProcessName(String process) { String name=processNameMap.get(process); if (name!=null) return name; return process; } HashMap<String,String> artifactNameMap=new HashMap<String,String>(); public String convertArtifactName(String artifact) { String name=artifactNameMap.get(artifact); if (name!=null) return name; return artifact; } HashMap<String,String> agentNameMap=new HashMap<String,String>(); public String convertAgentName(String agent) { String name=agentNameMap.get(agent); if (name!=null) return name; return agent; } ////////////////////////////////////////////////////////////////////// /// /// EDGES /// ////////////////////////////////////////////////////////////////////// public void emitDependency(Edge e, PrintStream out) { HashMap<String,String> properties=new HashMap(); List<AccountId> accounts=e.getAccount(); if (accounts.isEmpty()) { accounts=new LinkedList(); accounts.add(of.newAccountId(of.newAccount(defaultAccountLabel))); } for (AccountId acc: accounts) { String accountLabel=((Account)acc.getId()).getId(); addEdgeAttributes(accountLabel,e,properties); emitEdge( ((Node)e.getEffect().getId()).getId(), ((Node)e.getCause().getId()).getId(), properties, out); } } public HashMap<String,String> addEdgeAttributes(String accountLabel, Edge e, HashMap<String,String> properties) { String colour=convertAccount(accountLabel); properties.put("color",colour); properties.put("fontcolor",colour); properties.put("style",getEdgeStyle(e)); return properties; } HashMap<String,String> accountColourMap=new HashMap<String,String>(); public String convertAccount(String account) { String colour=accountColourMap.get(account); if (colour!=null) return colour; return account; } String defaultEdgeStyle; HashMap<String,String> edgeStyleMap=new HashMap<String,String>(); public String getEdgeStyle(Edge edge) { String name=edge.getClass().getName(); System.out.println("name " + name); String style=edgeStyleMap.get(name); if (style!=null) return style; return defaultEdgeStyle; } ////////////////////////////////////////////////////////////////////// /// /// DOT FORMAT GENERATION /// ////////////////////////////////////////////////////////////////////// String name; String defaultAccountLabel; public void emitNode(String name, HashMap<String,String> properties, PrintStream out) { StringBuffer sb=new StringBuffer(); sb.append(name); emitProperties(sb,properties); out.println(sb.toString()); } public void emitEdge(String src, String dest, HashMap<String,String> properties, PrintStream out) { StringBuffer sb=new StringBuffer(); sb.append(src); sb.append(" -> "); sb.append(dest); emitProperties(sb,properties); out.println(sb.toString()); } public void emitProperties(StringBuffer sb,HashMap<String,String> properties) { sb.append(" ["); for (String key: properties.keySet()) { String value=properties.get(key); sb.append(key); sb.append("=\""); sb.append(value); sb.append("\""); } sb.append("]"); } void prelude(PrintStream out) { out.println("digraph " + name + " { rankdir=\"BT\"; "); } void postlude(PrintStream out) { out.println("}"); out.close(); } }
opm/src/main/java/org/openprovenance/model/OPMToDot.java
package org.openprovenance.model; import java.util.List; import java.util.HashMap; import java.util.LinkedList; import java.io.File; import java.io.PrintStream; import java.io.FileOutputStream; import java.io.OutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBElement; import org.w3c.dom.Element; /** Serialisation of OPM Graphs to DOT format. */ public class OPMToDot { OPMUtilities u=new OPMUtilities(); OPMFactory of=new OPMFactory(); public OPMToDot() { init(); } public void init() { processNameMap.put("http://process.org/add1ToAll","add1ToAll"); processNameMap.put("http://process.org/split","split"); processNameMap.put("http://process.org/plus1","+1"); processNameMap.put("http://process.org/cons","cons"); processNameMap.put("http://process.org/fry","fry"); processNameMap.put("http://process.org/bake","bake"); processNameMap.put("http://process.org/badBake","badBake"); edgeStyleMap.put("org.openprovenance.model.Used","dotted"); edgeStyleMap.put("org.openprovenance.model.WasGeneratedBy","dotted"); edgeStyleMap.put("org.openprovenance.model.WasDerivedFrom","bold"); accountColourMap.put("orange","red"); defaultEdgeStyle="filled"; this.name="OPMGraph"; this.defaultAccountLabel="black"; this.displayProcessValue=false; this.displayArtifactValue=true; } public void convert(OPMGraph graph, String dotFile, String pdfFile) throws java.io.FileNotFoundException, java.io.IOException { convert(graph,new File(dotFile)); Runtime runtime = Runtime.getRuntime(); java.lang.Process proc = runtime.exec("dot -o " + pdfFile + " -Tpdf " + dotFile); } public void convert(OPMGraph graph, File file) throws java.io.FileNotFoundException{ OutputStream os=new FileOutputStream(file); convert(graph, new PrintStream(os)); } public void convert(OPMGraph graph, PrintStream out) { List<Edge> edges=u.getEdges(graph); prelude(out); if (graph.getProcesses()!=null) { for (Process p: graph.getProcesses().getProcess()) { emitProcess(p,out); } } if (graph.getArtifacts()!=null) { for (Artifact p: graph.getArtifacts().getArtifact()) { emitArtifact(p,out); } } if (graph.getAgents()!=null) { for (Agent p: graph.getAgents().getAgent()) { emitAgent(p,out); } } for (Edge e: edges) { emitDependency(e,out); } postlude(out); } ////////////////////////////////////////////////////////////////////// /// /// NODES /// ////////////////////////////////////////////////////////////////////// public void emitProcess(Process p, PrintStream out) { HashMap<String,String> properties=new HashMap(); emitNode(p.getId(), addProcessShape(p,addProcessLabel(p, properties)), out); } public void emitArtifact(Artifact a, PrintStream out) { HashMap<String,String> properties=new HashMap(); emitNode(a.getId(), addArtifactShape(a,addArtifactLabel(a, properties)), out); } public void emitAgent(Agent ag, PrintStream out) { HashMap<String,String> properties=new HashMap(); emitNode(ag.getId(), addAgentShape(ag,addAgentLabel(ag, properties)), out); } public HashMap<String,String> addProcessShape(Process p, HashMap<String,String> properties) { properties.put("shape","poligon"); properties.put("sides","4"); return properties; } public HashMap<String,String> addProcessLabel(Process p, HashMap<String,String> properties) { properties.put("label",processLabel(p)); return properties; } public HashMap<String,String> addArtifactShape(Artifact p, HashMap<String,String> properties) { // default is good for artifact return properties; } public HashMap<String,String> addArtifactLabel(Artifact p, HashMap<String,String> properties) { properties.put("label",artifactLabel(p)); return properties; } public HashMap<String,String> addAgentShape(Agent p, HashMap<String,String> properties) { properties.put("shape","poligon"); properties.put("sides","5"); return properties; } public HashMap<String,String> addAgentLabel(Agent p, HashMap<String,String> properties) { properties.put("label",agentLabel(p)); return properties; } boolean displayProcessValue; boolean displayArtifactValue; boolean displayAgentValue; public String processLabel(Process p) { if (displayProcessValue) { return convertProcessName(""+p.getValue()); } else { return p.getId(); } } public String artifactLabel(Artifact p) { if (displayArtifactValue) { return convertArtifactName(""+p.getValue()); } else { return p.getId(); } } public String agentLabel(Agent p) { if (displayAgentValue) { return convertAgentName(""+p.getValue()); } else { return p.getId(); } } HashMap<String,String> processNameMap=new HashMap<String,String>(); public String convertProcessName(String process) { String name=processNameMap.get(process); if (name!=null) return name; return process; } HashMap<String,String> artifactNameMap=new HashMap<String,String>(); public String convertArtifactName(String artifact) { String name=artifactNameMap.get(artifact); if (name!=null) return name; return artifact; } HashMap<String,String> agentNameMap=new HashMap<String,String>(); public String convertAgentName(String agent) { String name=agentNameMap.get(agent); if (name!=null) return name; return agent; } ////////////////////////////////////////////////////////////////////// /// /// EDGES /// ////////////////////////////////////////////////////////////////////// public void emitDependency(Edge e, PrintStream out) { HashMap<String,String> properties=new HashMap(); List<AccountId> accounts=e.getAccount(); if (accounts.isEmpty()) { accounts=new LinkedList(); accounts.add(of.newAccountId(of.newAccount(defaultAccountLabel))); } for (AccountId acc: accounts) { String accountLabel=((Account)acc.getId()).getId(); addEdgeAttributes(accountLabel,e,properties); emitEdge( ((Node)e.getEffect().getId()).getId(), ((Node)e.getCause().getId()).getId(), properties, out); } } public HashMap<String,String> addEdgeAttributes(String accountLabel, Edge e, HashMap<String,String> properties) { String colour=convertAccount(accountLabel); properties.put("color",colour); properties.put("fontcolor",colour); properties.put("style",getEdgeStyle(e)); return properties; } HashMap<String,String> accountColourMap=new HashMap<String,String>(); public String convertAccount(String account) { String colour=accountColourMap.get(account); if (colour!=null) return colour; return account; } String defaultEdgeStyle; HashMap<String,String> edgeStyleMap=new HashMap<String,String>(); public String getEdgeStyle(Edge edge) { String name=edge.getClass().getName(); System.out.println("name " + name); String style=edgeStyleMap.get(name); if (style!=null) return style; return defaultEdgeStyle; } ////////////////////////////////////////////////////////////////////// /// /// DOT FORMAT GENERATION /// ////////////////////////////////////////////////////////////////////// String name; String defaultAccountLabel; public void emitNode(String name, HashMap<String,String> properties, PrintStream out) { StringBuffer sb=new StringBuffer(); sb.append(name); emitProperties(sb,properties); out.println(sb.toString()); } public void emitEdge(String src, String dest, HashMap<String,String> properties, PrintStream out) { StringBuffer sb=new StringBuffer(); sb.append(src); sb.append(" -> "); sb.append(dest); emitProperties(sb,properties); out.println(sb.toString()); } public void emitProperties(StringBuffer sb,HashMap<String,String> properties) { sb.append(" ["); for (String key: properties.keySet()) { String value=properties.get(key); sb.append(key); sb.append("=\""); sb.append(value); sb.append("\""); } sb.append("]"); } void prelude(PrintStream out) { out.println("digraph " + name + " { rankdir=\"BT\"; "); } void postlude(PrintStream out) { out.println("}"); out.close(); } }
git-svn-id: https://provenance.ecs.soton.ac.uk/contrib-svn/trunk/opm@242 eaacffd3-9a98-4465-91bf-87518ec83039
opm/src/main/java/org/openprovenance/model/OPMToDot.java
Java
mit
71867ca6675f0bb08dca42067fd1a8b817844382
0
infsci2560sp16/full-stack-web-project-zhonghz,infsci2560sp16/full-stack-web-project-zhonghz,infsci2560sp16/full-stack-web-project-zhonghz,infsci2560sp16/full-stack-web-project-zhonghz
import com.google.gson.Gson; import org.json.JSONObject; import java.sql.*; import java.util.*; import java.util.Date; import java.text.SimpleDateFormat; import java.net.URI; import java.net.URISyntaxException; import static spark.Spark.*; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import com.heroku.sdk.jdbc.DatabaseUrl; import spark.Request; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class Main { public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); get("/hello", (req, res) -> "Hello World"); //ftl get("/index", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); ArrayList<String> oddtopics = new ArrayList<String>(); oddtopics.add("Animal"); oddtopics.add("Beauty"); oddtopics.add("Books"); oddtopics.add("Television"); ArrayList<String> eventopics = new ArrayList<String>(); eventopics.add("Culture"); eventopics.add("Music"); eventopics.add("Technology"); ArrayList<String> weektopics = new ArrayList<String>(); weektopics.add("Cooking"); weektopics.add("Movies"); weektopics.add("Sports"); weektopics.add("Travel"); SimpleDateFormat formatter = new SimpleDateFormat("EEEE"); String dayOfWeek = formatter.format(new Date()); attributes.put("oddtopics", oddtopics); attributes.put("eventopics", eventopics); attributes.put("weektopics", weektopics); attributes.put("dayOfWeek", dayOfWeek); return new ModelAndView(attributes, "index.ftl"); } , new FreeMarkerEngine()); //get("/", (request, response) -> { // Map<String, Object> attributes = new HashMap<>(); // attributes.put("message", "Hello World!"); // // return new ModelAndView(attributes, "index.ftl"); // }, new FreeMarkerEngine()); Gson gson = new Gson(); //GET JSON get("api/find", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); // stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); // stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT username, nlanguage, planguage FROM users"); //Map<String, Object> data = new HashMap<>(); //ArrayList<String> output = new ArrayList<String>(); List<Object> data = new ArrayList<>(); while (rs.next()) { Map<String, Object> member = new HashMap<>(); member.put("username", rs.getString("username")); member.put("nlanguage", rs.getString("nlanguage")); member.put("planguage", rs.getString("planguage")); //data.put(rs.getString("username"), member); data.add(member); } return data; //attributes.put("results", output); //return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, gson::toJson); //POST JSON post("api/register", (req, res) -> { Connection connection = null; //Testing System.out.println(req.body()); try { connection = DatabaseUrl.extract().getConnection(); JSONObject obj = new JSONObject(req.body()); String username = obj.getString("username"); String password = obj.getString("password"); String email = obj.getString("email"); String fname = obj.getString("fname"); String lname = obj.getString("lname"); String gender = obj.getString("gender"); String language = obj.getString("language"); String planguage = obj.getString("planguage"); String topic = obj.getString("topic"); String sql = "INSERT INTO users VALUES ('"+ username + "','" + password + "','" + email + "','" + fname + "','"+ lname + "','" + gender + "','" + language + "','" + planguage + "','" + topic + "')"; connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate(sql); ResultSet rs = stmt.executeQuery("SELECT * FROM users where username ='" + username + "'"); Map<String, Object> currentuser = new HashMap<>(); currentuser.put("username", rs.getString("username")); currentuser.put("email", rs.getString("email")); return currentuser; // return req.body(); } catch (Exception e) { return e.getMessage(); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }); //GET XML get("api/forum", (req, res) -> { Connection connection = null; // res.type("application/xml"); //Return as XML Map<String, Object> attributes = new HashMap<>(); try { //Connect to Database and execute SQL Query connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT title,username,threads.planguage,threads.topic,description FROM users,threads WHERE users.email=threads.email"); String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<forum xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:SchemaLocation=\"forum.xsd\">"; while (rs.next()) { xml += "<thread>"; xml += "<title>"+rs.getString("title")+"</title>"; xml += "<username>"+rs.getString("username")+"</username>"; xml += "<language>"+rs.getString("planguage")+"</language>"; xml += "<topic>"+rs.getString("topic")+"</topic>"; xml += "<description>"+rs.getString("description")+"</description>"; xml += "</thread>"; } xml += "</forum>"; res.type("text/xml"); return xml; } catch (Exception e) { attributes.put("message", "There was an error: " + e); return attributes; } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } });//End api/forum get("/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); } }
src/main/java/Main.java
import com.google.gson.Gson; import org.json.JSONObject; import java.sql.*; import java.util.*; import java.util.Date; import java.text.SimpleDateFormat; import java.net.URI; import java.net.URISyntaxException; import static spark.Spark.*; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import com.heroku.sdk.jdbc.DatabaseUrl; import spark.Request; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class Main { public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); get("/hello", (req, res) -> "Hello World"); //ftl get("/index", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); ArrayList<String> oddtopics = new ArrayList<String>(); oddtopics.add("Animal"); oddtopics.add("Beauty"); oddtopics.add("Books"); oddtopics.add("Television"); ArrayList<String> eventopics = new ArrayList<String>(); eventopics.add("Culture"); eventopics.add("Music"); eventopics.add("Technology"); ArrayList<String> weektopics = new ArrayList<String>(); weektopics.add("Cooking"); weektopics.add("Movies"); weektopics.add("Sports"); weektopics.add("Travel"); SimpleDateFormat formatter = new SimpleDateFormat("EEEE"); String dayOfWeek = formatter.format(new Date()); attributes.put("oddtopics", oddtopics); attributes.put("eventopics", eventopics); attributes.put("weektopics", weektopics); attributes.put("dayOfWeek", dayOfWeek); return new ModelAndView(attributes, "index.ftl"); } , new FreeMarkerEngine()); //get("/", (request, response) -> { // Map<String, Object> attributes = new HashMap<>(); // attributes.put("message", "Hello World!"); // // return new ModelAndView(attributes, "index.ftl"); // }, new FreeMarkerEngine()); Gson gson = new Gson(); //GET JSON get("api/find", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); // stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); // stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT username, nlanguage, planguage FROM users"); //Map<String, Object> data = new HashMap<>(); //ArrayList<String> output = new ArrayList<String>(); List<Object> data = new ArrayList<>(); while (rs.next()) { Map<String, Object> member = new HashMap<>(); member.put("username", rs.getString("username")); member.put("nlanguage", rs.getString("nlanguage")); member.put("planguage", rs.getString("planguage")); //data.put(rs.getString("username"), member); data.add(member); } return data; //attributes.put("results", output); //return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, gson::toJson); //POST JSON post("api/register", (req, res) -> { Connection connection = null; //Testing System.out.println(req.body()); try { connection = DatabaseUrl.extract().getConnection(); JSONObject obj = new JSONObject(req.body()); String username = obj.getString("username"); String password = obj.getString("password"); String email = obj.getString("email"); String fname = obj.getString("fname"); String lname = obj.getString("lname"); String gender = obj.getString("gender"); String language = obj.getString("language"); String planguage = obj.getString("planguage"); String topic = obj.getString("topic"); String sql = "INSERT INTO users VALUES ('"+ username + "','" + password + "','" + email + "','" + fname + "','"+ lname + "','" + gender + "','" + language + "','" + planguage + "','" + topic + "')"; connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate(sql); ResultSet rs = stmt.executeQuery("SELECT * FROM users where username ='" + username + "'"); Map<String, Object> currentuser = new HashMap<>(); currentuser.put("username", rs.getString("username")); currentuser.put("email", rs.getString("email")); return currentuser; // return req.body(); } catch (Exception e) { return e.getMessage(); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }); //GET XML get("api/forum", (req, res) -> { Connection connection = null; // res.type("application/xml"); //Return as XML Map<String, Object> attributes = new HashMap<>(); try { //Connect to Database and execute SQL Query connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT title,username,threads.planguage,threads.topic,description FROM users,threads WHERE users.email=threads.email"); String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<forum xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespace SchemaLocation=\"forum.xsd\">"; while (rs.next()) { xml += "<thread>"; xml += "<title>"+rs.getString("title")+"</title>"; xml += "<username>"+rs.getString("username")+"</username>"; xml += "<language>"+rs.getString("planguage")+"</language>"; xml += "<topic>"+rs.getString("topic")+"</topic>"; xml += "<description>"+rs.getString("description")+"</description>"; xml += "</thread>"; } xml += "</forum>"; res.type("text/xml"); return xml; } catch (Exception e) { attributes.put("message", "There was an error: " + e); return attributes; } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } });//End api/forum get("/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); } }
Update XML
src/main/java/Main.java
Update XML
Java
mit
2cb5877a7487cd9252d2f94946119f14deb80e6e
0
seqcode/seqcode-core,seqcode/seqcode-core,seqcode/seqcode-core,seqcode/seqcode-core
package org.seqcode.motifs; public class ConsensusSequenceScoreProfile { private ConsensusSequence consensus; private int[] forward, reverse; public ConsensusSequenceScoreProfile(ConsensusSequence c, int[] f, int[] r) { consensus = c; if(f.length != r.length) { throw new IllegalArgumentException(); } forward = (int[])f.clone(); reverse = (int[])r.clone(); } public int length() { return forward.length; } public ConsensusSequence getConsensus() { return consensus; } public int[] getForwardScores() { return forward; } public int[] getReverseScores() { return reverse; } /** Strand of lowest mismatch over the whole sequence*/ public char getLowestMismatchStrand() { int min = Integer.MAX_VALUE; int minScore = consensus.getMaxMismatch(); char str = '+'; for(int i = 0; i < forward.length; i++) { int ms = getLowestMismatch(i); if(min == Integer.MAX_VALUE || ms < minScore) { minScore= ms; min = i; str = getLowestMismatchStrand(i); } } return str; } /** Strand of lowest mismatch (from 2 strands) at this position */ public char getLowestMismatchStrand(int i) { if(forward[i] <= reverse[i]) { return '+'; } else { return '-'; } } /** Strand of the lowest mismatch over a window*/ public char getLowestMismatchStrandBoundedWin(int l, int r){ int minScore = consensus.getMaxMismatch(); char str = '+'; for(int i = l; i <=r; i++) { int ms = getLowestMismatch(i); if(ms < minScore) { minScore= ms; str = getLowestMismatchStrand(i); } } return str; } /** Lowest mismatch (from 2 strands) at this position */ public int getLowestMismatch(int i) { return Math.min(forward[i], reverse[i]); } /** Lowest mismatch over a window*/ public int getLowestMismatchBoundedWin(int l, int r){ int min = consensus.getMaxMismatch(); if(l>0 && r>=0 && l<forward.length && r<forward.length && l<=r){ for(int i=l; i<=r; i++){ if(getLowestMismatch(i)<min) min = getLowestMismatch(i); } return min; }else{ return -1; } } /** Lowest mismatch over the whole sequence*/ public int getLowestMismatch(){ return(getLowestMismatch(getLowestMismatchIndex())); } /** Index of lowest mismatch level. If multiple equivalent, leftmost is returned**/ public int getLowestMismatchIndex() { int min = Integer.MAX_VALUE; int minScore = consensus.getMaxMismatch(); for(int i = 0; i < forward.length; i++) { int ms = getLowestMismatch(i); if(min == Integer.MAX_VALUE || ms<minScore) { minScore = ms; min = i; } } return min; } /** Index of lowest mismatch level. If multiple equivalent, leftmost is returned**/ public int getLowestMismatchIndexBoundedWin(int l, int r) { int min = Integer.MAX_VALUE; int minScore = consensus.getMaxMismatch(); for(int i = l; i <= r; i++) { int ms = getLowestMismatch(i); if(min == Integer.MAX_VALUE || ms<minScore) { minScore = ms; min = i; } } return min; } }
src/org/seqcode/motifs/ConsensusSequenceScoreProfile.java
package org.seqcode.motifs; public class ConsensusSequenceScoreProfile { private ConsensusSequence consensus; private int[] forward, reverse; public ConsensusSequenceScoreProfile(ConsensusSequence c, int[] f, int[] r) { consensus = c; if(f.length != r.length) { throw new IllegalArgumentException(); } forward = (int[])f.clone(); reverse = (int[])r.clone(); } public int length() { return forward.length; } public ConsensusSequence getConsensus() { return consensus; } public int[] getForwardScores() { return forward; } public int[] getReverseScores() { return reverse; } /** Strand of lowest mismatch over the whole sequence*/ public char getLowestMismatchStrand() { int min = Integer.MAX_VALUE; int minScore = consensus.getMaxMismatch(); char str = '+'; for(int i = 0; i < forward.length; i++) { int ms = getLowestMismatch(i); if(min == Integer.MAX_VALUE || ms < minScore) { minScore= ms; min = i; str = getLowestMismatchStrand(i); } } return str; } /** Strand of lowest mismatch (from 2 strands) at this position */ public char getLowestMismatchStrand(int i) { if(forward[i] <= reverse[i]) { return '+'; } else { return '-'; } } /** Strand of the lowest mismatch over a window*/ public char getLowestMismatchStrandBoundedWin(int l, int r){ int min = Integer.MAX_VALUE; int minScore = consensus.getMaxMismatch(); char str = '+'; for(int i = l; i <=r; i++) { int ms = getLowestMismatch(i); if(min == Integer.MAX_VALUE || ms < minScore) { minScore= ms; min = i; str = getLowestMismatchStrand(i); } } return str; } /** Lowest mismatch (from 2 strands) at this position */ public int getLowestMismatch(int i) { return Math.min(forward[i], reverse[i]); } /** Lowest mismatch over a window*/ public int getLowestMismatchBoundedWin(int l, int r){ int min = consensus.getMaxMismatch(); if(l>0 && r>=0 && l<forward.length && r<forward.length && l<r){ for(int i=l; i<=r; i++){ if(getLowestMismatch(i)<min) min = getLowestMismatch(i); } return min; }else{ return -1; } } /** Lowest mismatch over the whole sequence*/ public int getLowestMismatch(){ return(getLowestMismatch(getLowestMismatchIndex())); } /** Index of lowest mismatch level. If multiple equivalent, leftmost is returned**/ public int getLowestMismatchIndex() { int min = Integer.MAX_VALUE; int minScore = consensus.getMaxMismatch(); for(int i = 0; i < forward.length; i++) { int ms = getLowestMismatch(i); if(min == Integer.MAX_VALUE || ms<minScore) { minScore = ms; min = i; } } return min; } /** Index of lowest mismatch level. If multiple equivalent, leftmost is returned**/ public int getLowestMismatchIndexBoundedWin(int l, int r) { int min = Integer.MAX_VALUE; int minScore = consensus.getMaxMismatch(); for(int i = l; i <= r; i++) { int ms = getLowestMismatch(i); if(min == Integer.MAX_VALUE || ms<minScore) { minScore = ms; min = i; } } return min; } }
Bug fix to ConsensusMetaMaker
src/org/seqcode/motifs/ConsensusSequenceScoreProfile.java
Bug fix to ConsensusMetaMaker
Java
mit
eea2bd55a2a6d1486f6ec1d13bfdb201ddb9feb5
0
henfredemars/dbproject,henfredemars/dbproject,henfredemars/dbproject,henfredemars/dbproject
package henfredemars; import java.util.Calendar; //Interface to the DataSample data structure public interface DataSampleInterface { public void setStationId(String station); public void setTemperature(double tempInF); public void setHumidity(double relativeHumidity); public void setWindSpeed(double windSpeedInMPH); public void setPressure(double seaLevelPressureInMillibars); public void setRainfall(double hourlyInches); public void setDate(Calendar date); public String getStationId(); public double getTemperature(); public double getHumidity(); public double getWindSpeed(); public double getPressure(); public double getRainfall(); public Calendar getDate(); //BE CAREFUL that you use new Calendar instances for each DataSample public DataStatus checkSample(); }
HourlyDataParser/src/henfredemars/DataSampleInterface.java
package henfredemars; import java.util.Calendar; //Interface to the DataSample data structure public interface DataSampleInterface { public void setStationId(String station); public void setTemperature(double tempInF); public void setHumidity(double relativeHumidity); public void setWindSpeed(double windSpeedInMPH); public void setPressure(double seaLevelPressureInMillibars); public void setRainfall(double hourlyInches); public void setDate(Calendar date); public String getStationId(); public double getTemperature(); public double getHumidity(); public double getWindSpeed(); public double getPressure(); public double getRainfall(); public Calendar getDate(); //BE CAREFUL the you use new Calendar instances for each DataSample public DataStatus checkSample(); }
Update DataSampleInterface.java Correct typo
HourlyDataParser/src/henfredemars/DataSampleInterface.java
Update DataSampleInterface.java
Java
agpl-3.0
46f4c46380cb8ddb77777e107111b4e005a012e8
0
KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1
package nl.mpi.kinnate.kindata; import javax.xml.bind.annotation.XmlAttribute; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; /** * Document : EntityRelation * Created on : Mar 25, 2011, 6:18:44 PM * Author : Peter Withers */ public class EntityRelation implements Comparable<EntityRelation> { @XmlTransient private EntityData alterNode; // @XmlElement(name = "GenerationalDistance", namespace = "http://mpi.nl/tla/kin") // public int generationalDistance; @XmlElement(name = "Identifier", namespace = "http://mpi.nl/tla/kin") public UniqueIdentifier alterUniqueIdentifier = null; @XmlAttribute(name = "Type", namespace = "http://mpi.nl/tla/kin") public DataTypes.RelationType relationType; @XmlElement(name = "Label", namespace = "http://mpi.nl/tla/kin") public String labelString; @XmlElement(name = "Colour", namespace = "http://mpi.nl/tla/kin") public String lineColour = null; // line colour is normally only assigned in memory and will not be serialised except into the svg, so with the exception of kin terms that are automatically added to the diagram, the colour will be set by the diagram relation settings @XmlAttribute(name = "dcr", namespace = "http://mpi.nl/tla/kin") public String dcrType = null; @XmlAttribute(name = "CustomType", namespace = "http://mpi.nl/tla/kin") public String customType = null; @XmlTransient private int relationOrder = 0; // this is used to indicate for instance; first, second child and fist, second husband etc. public EntityRelation() { } public EntityRelation(String dcrType, String customType, String lineColour, DataTypes.RelationType relationType, String labelString) { this.dcrType = dcrType; this.customType = customType; this.lineColour = lineColour; this.relationType = relationType; this.labelString = labelString; } public void setAlterNode(EntityData graphDataNode) { // if (graphDataNode != null) { // if the nodes has been reloaded then it must always be updated here // todo: it might be better to use a hashmap of all current nodes alterNode = graphDataNode; if (alterUniqueIdentifier == null) { alterUniqueIdentifier = alterNode.getUniqueIdentifier(); } // } } @XmlTransient public EntityData getAlterNode() { return alterNode; } public int compareTo(EntityRelation o) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final EntityRelation other = (EntityRelation) obj; if (this.alterUniqueIdentifier != other.alterUniqueIdentifier && (this.alterUniqueIdentifier == null || !this.alterUniqueIdentifier.equals(other.alterUniqueIdentifier))) { return false; } if (this.relationType != other.relationType) { return false; } if ((this.labelString == null) ? (other.labelString != null) : !this.labelString.equals(other.labelString)) { return false; } if ((this.lineColour == null) ? (other.lineColour != null) : !this.lineColour.equals(other.lineColour)) { return false; } if ((this.dcrType == null) ? (other.dcrType != null) : !this.dcrType.equals(other.dcrType)) { return false; } if ((this.customType == null) ? (other.customType != null) : !this.customType.equals(other.customType)) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 71 * hash + (this.alterUniqueIdentifier != null ? this.alterUniqueIdentifier.hashCode() : 0); hash = 71 * hash + (this.relationType != null ? this.relationType.hashCode() : 0); hash = 71 * hash + (this.labelString != null ? this.labelString.hashCode() : 0); hash = 71 * hash + (this.lineColour != null ? this.lineColour.hashCode() : 0); hash = 71 * hash + (this.dcrType != null ? this.dcrType.hashCode() : 0); hash = 71 * hash + (this.customType != null ? this.customType.hashCode() : 0); return hash; } @XmlTransient public int getRelationOrder() { // todo: this is limited and a richer syntax will be required because there could be multiple birth orders eg maternal, paternal or only on shared parents or all parents etc. // for (EntityRelation entityRelation : getDistinctRelateNodes()){ if (!alterUniqueIdentifier.isTransientIdentifier()) { throw new UnsupportedOperationException("Getting the birth order on a non transient entity is not yet supported"); } // } return relationOrder; } public void setRelationOrder(int birthOrder) { if (!alterUniqueIdentifier.isTransientIdentifier()) { throw new UnsupportedOperationException("Cannot set the birth order on a non transient entity, it must be calculated from the birth dates"); } this.relationOrder = birthOrder; } }
desktop/src/main/java/nl/mpi/kinnate/kindata/EntityRelation.java
package nl.mpi.kinnate.kindata; import javax.xml.bind.annotation.XmlAttribute; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; /** * Document : EntityRelation * Created on : Mar 25, 2011, 6:18:44 PM * Author : Peter Withers */ public class EntityRelation implements Comparable<EntityRelation> { @XmlTransient private EntityData alterNode; // @XmlElement(name = "GenerationalDistance", namespace = "http://mpi.nl/tla/kin") // public int generationalDistance; @XmlElement(name = "Identifier", namespace = "http://mpi.nl/tla/kin") public UniqueIdentifier alterUniqueIdentifier = null; @XmlAttribute(name = "Type", namespace = "http://mpi.nl/tla/kin") public DataTypes.RelationType relationType; @XmlElement(name = "Label", namespace = "http://mpi.nl/tla/kin") public String labelString; @XmlElement(name = "Colour", namespace = "http://mpi.nl/tla/kin") public String lineColour = null; // line colour is normally only assigned in memory and will not be serialised except into the svg, so with the exception of kin terms that are automatically added to the diagram, the colour will be set by the diagram relation settings @XmlAttribute(name = "dcr", namespace = "http://mpi.nl/tla/kin") public String dcrType = null; @XmlAttribute(name = "CustomType", namespace = "http://mpi.nl/tla/kin") public String customType = null; @XmlTransient private int relationOrder = 0; // this is used to indicate for instance; first, second child and fist, second husband etc. public EntityRelation() { } public EntityRelation(String dcrType, String customType, String lineColour, DataTypes.RelationType relationType, String labelString) { this.dcrType = dcrType; this.customType = customType; this.lineColour = lineColour; this.relationType = relationType; this.labelString = labelString; } public void setAlterNode(EntityData graphDataNode) { // if (graphDataNode != null) { // if the nodes has been reloaded then it must always be updated here // todo: it might be better to use a hashmap of all current nodes alterNode = graphDataNode; if (alterUniqueIdentifier == null) { alterUniqueIdentifier = alterNode.getUniqueIdentifier(); } // } } @XmlTransient public EntityData getAlterNode() { return alterNode; } public int compareTo(EntityRelation o) { if (o.alterUniqueIdentifier.equals(alterUniqueIdentifier) // && o.generationalDistance == generationalDistance // && o.relationLineType.equals(relationLineType) && o.relationType.equals(relationType) && ((dcrType == null && dcrType == null) || o.dcrType.equals(dcrType)) && ((customType == null && customType == null) || o.customType.equals(customType)) && ((labelString == null && labelString == null) || o.labelString.equals(labelString)) && ((lineColour == null && lineColour == null) || o.lineColour.equals(lineColour))) { return 0; } return -1; } @XmlTransient public int getRelationOrder() { // todo: this is limited and a richer syntax will be required because there could be multiple birth orders eg maternal, paternal or only on shared parents or all parents etc. // for (EntityRelation entityRelation : getDistinctRelateNodes()){ if (!alterUniqueIdentifier.isTransientIdentifier()) { throw new UnsupportedOperationException("Getting the birth order on a non transient entity is not yet supported"); } // } return relationOrder; } public void setRelationOrder(int birthOrder) { if (!alterUniqueIdentifier.isTransientIdentifier()) { throw new UnsupportedOperationException("Cannot set the birth order on a non transient entity, it must be calculated from the birth dates"); } this.relationOrder = birthOrder; } }
Updated some sample diagrams to reflect recent changes. Updated the line rendering to reflect recent changes. Replaced the entity relation comparator code.
desktop/src/main/java/nl/mpi/kinnate/kindata/EntityRelation.java
Updated some sample diagrams to reflect recent changes. Updated the line rendering to reflect recent changes. Replaced the entity relation comparator code.
Java
agpl-3.0
349700d29a8b73b6ab0c0a8faa715976c872f8ca
0
neo4j-contrib/neo4j-meta-model
package org.neo4j.neometa.structure; import org.neo4j.api.core.NeoService; import org.neo4j.api.core.Node; import org.neo4j.api.core.Relationship; import org.neo4j.api.core.RelationshipType; import org.neo4j.api.core.Transaction; import org.neo4j.util.NeoUtil; /** * A super class for basically all meta structure objects which wraps a * {@link Node}. */ public abstract class MetaStructureObject { static final String KEY_MIN_CARDINALITY = "min_cardinality"; static final String KEY_MAX_CARDINALITY = "max_cardinality"; static final String KEY_COLLECTION_CLASS = "collection_class"; /** * The node property for a meta structure objects name. */ public static final String KEY_NAME = "name"; private MetaStructure meta; private Node node; MetaStructureObject( MetaStructure meta, Node node ) { this.meta = meta; this.node = node; } /** * @return the underlying {@link MetaStructure}. */ public MetaStructure meta() { return this.meta; } /** * @return the {@link NeoService} instance used with this instance. */ public NeoService neo() { return ( ( MetaStructureImpl ) meta() ).neo(); } protected NeoUtil neoUtil() { return ( ( MetaStructureImpl ) meta() ).neoUtil(); } /** * @return the {@link Node} which this object wraps. */ public Node node() { return this.node; } protected void setProperty( String key, Object value ) { neoUtil().setProperty( node(), key, value ); } protected Object getProperty( String key ) { return neoUtil().getProperty( node(), key ); } protected Object getProperty( String key, Object defaultValue ) { return neoUtil().getProperty( node(), key, defaultValue ); } protected Object removeProperty( String key ) { return neoUtil().removeProperty( node(), key ); } protected void setOrRemoteProperty( String key, Object value ) { if ( value == null ) { removeProperty( key ); } else { setProperty( key, value ); } } protected void setSingleRelationshipOrNull( Node node, RelationshipType type ) { Transaction tx = neo().beginTx(); try { Relationship relationship = getSingleRelationshipOrNull( type ); if ( relationship != null ) { relationship.delete(); } if ( node != null ) { node().createRelationshipTo( node, type ); } tx.success(); } finally { tx.finish(); } } protected Relationship getSingleRelationshipOrNull( RelationshipType type ) { return neoUtil().getSingleRelationship( node(), type ); } void setName( String name ) { setProperty( KEY_NAME, name ); } /** * @return the name set for this object. */ public String getName() { return ( String ) getProperty( KEY_NAME, null ); } @Override public int hashCode() { return node().hashCode(); } @Override public boolean equals( Object o ) { return o != null && getClass().equals( o.getClass() ) && node().equals( ( ( MetaStructureObject ) o ).node() ); } }
src/main/java/org/neo4j/neometa/structure/MetaStructureObject.java
package org.neo4j.neometa.structure; import org.neo4j.api.core.NeoService; import org.neo4j.api.core.Node; import org.neo4j.api.core.Relationship; import org.neo4j.api.core.RelationshipType; import org.neo4j.api.core.Transaction; import org.neo4j.util.NeoUtil; /** * A super class for basically all meta structure objects which wraps a * {@link Node}. */ public abstract class MetaStructureObject { static final String KEY_MIN_CARDINALITY = "min_cardinality"; static final String KEY_MAX_CARDINALITY = "max_cardinality"; static final String KEY_COLLECTION_CLASS = "collection_class"; static final String KEY_NAME = "name"; private MetaStructure meta; private Node node; MetaStructureObject( MetaStructure meta, Node node ) { this.meta = meta; this.node = node; } /** * @return the underlying {@link MetaStructure}. */ public MetaStructure meta() { return this.meta; } /** * @return the {@link NeoService} instance used with this instance. */ public NeoService neo() { return ( ( MetaStructureImpl ) meta() ).neo(); } protected NeoUtil neoUtil() { return ( ( MetaStructureImpl ) meta() ).neoUtil(); } /** * @return the {@link Node} which this object wraps. */ public Node node() { return this.node; } protected void setProperty( String key, Object value ) { neoUtil().setProperty( node(), key, value ); } protected Object getProperty( String key ) { return neoUtil().getProperty( node(), key ); } protected Object getProperty( String key, Object defaultValue ) { return neoUtil().getProperty( node(), key, defaultValue ); } protected Object removeProperty( String key ) { return neoUtil().removeProperty( node(), key ); } protected void setOrRemoteProperty( String key, Object value ) { if ( value == null ) { removeProperty( key ); } else { setProperty( key, value ); } } protected void setSingleRelationshipOrNull( Node node, RelationshipType type ) { Transaction tx = neo().beginTx(); try { Relationship relationship = getSingleRelationshipOrNull( type ); if ( relationship != null ) { relationship.delete(); } if ( node != null ) { node().createRelationshipTo( node, type ); } tx.success(); } finally { tx.finish(); } } protected Relationship getSingleRelationshipOrNull( RelationshipType type ) { return neoUtil().getSingleRelationship( node(), type ); } void setName( String name ) { setProperty( KEY_NAME, name ); } /** * @return the name set for this object. */ public String getName() { return ( String ) getProperty( KEY_NAME, null ); } @Override public int hashCode() { return node().hashCode(); } @Override public boolean equals( Object o ) { return o != null && getClass().equals( o.getClass() ) && node().equals( ( ( MetaStructureObject ) o ).node() ); } }
Made the node "name" property key public so that it may be used by others
src/main/java/org/neo4j/neometa/structure/MetaStructureObject.java
Made the node "name" property key public so that it may be used by others
Java
lgpl-2.1
5861a4fc7ae2634843e7583b268b74b669a35b1e
0
exedio/copernica,exedio/copernica,exedio/copernica
/* * Copyright (C) 2004-2005 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope.testmodel; import com.exedio.cope.Item; /** * An item not having any attribute. * @cope.persistent * @author Ralf Wiebicke */ public class EmptyItem extends Item { /** * This dummy attribute has the same name * as an attribute in super class item. * This tests, that there are no name collisions. */ boolean type; /** * This dummy attribute has the same name * as an attribute in super class item. * This tests, that there are no name collisions. */ boolean pk; /** ** * Creates a new EmptyItem with all the attributes initially needed. * @cope.generated This method has been generated by the cope instrumentor and will be overwritten by the build process. * */public EmptyItem() { this(new com.exedio.cope.AttributeValue[]{ }); }/** ** * Creates a new EmptyItem and sets the given attributes initially. * This constructor is called by {@link com.exedio.cope.Type#newItem Type.newItem}. * @cope.generated This method has been generated by the cope instrumentor and will be overwritten by the build process. * */private EmptyItem(final com.exedio.cope.AttributeValue[] initialAttributes) { super(initialAttributes); }/** ** * Reactivation constructor. Used for internal purposes only. * @cope.generated This method has been generated by the cope instrumentor and will be overwritten by the build process. * @see Item#Item(com.exedio.cope.util.ReactivationConstructorDummy,int) * */private EmptyItem(com.exedio.cope.util.ReactivationConstructorDummy d,final int pk) { super(d,pk); }/** ** * The persistent type information for emptyItem. * @cope.generated This method has been generated by the cope instrumentor and will be overwritten by the build process. * */public static final com.exedio.cope.Type TYPE = new com.exedio.cope.Type(EmptyItem.class) ;}
lib/testmodelsrc/com/exedio/cope/testmodel/EmptyItem.java
/* * Copyright (C) 2004-2005 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope.testmodel; import com.exedio.cope.Item; /** * An item not having any attribute. * @cope.persistent * @author Ralf Wiebicke */ public class EmptyItem extends Item { /** ** * Creates a new EmptyItem with all the attributes initially needed. * @cope.generated This method has been generated by the cope instrumentor and will be overwritten by the build process. * */public EmptyItem() { this(new com.exedio.cope.AttributeValue[]{ }); }/** ** * Creates a new EmptyItem and sets the given attributes initially. * This constructor is called by {@link com.exedio.cope.Type#newItem Type.newItem}. * @cope.generated This method has been generated by the cope instrumentor and will be overwritten by the build process. * */private EmptyItem(final com.exedio.cope.AttributeValue[] initialAttributes) { super(initialAttributes); }/** ** * Reactivation constructor. Used for internal purposes only. * @cope.generated This method has been generated by the cope instrumentor and will be overwritten by the build process. * @see Item#Item(com.exedio.cope.util.ReactivationConstructorDummy,int) * */private EmptyItem(com.exedio.cope.util.ReactivationConstructorDummy d,final int pk) { super(d,pk); }/** ** * The persistent type information for emptyItem. * @cope.generated This method has been generated by the cope instrumentor and will be overwritten by the build process. * */public static final com.exedio.cope.Type TYPE = new com.exedio.cope.Type(EmptyItem.class) ;}
test name collision git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@2810 e7d4fc99-c606-0410-b9bf-843393a9eab7
lib/testmodelsrc/com/exedio/cope/testmodel/EmptyItem.java
test name collision
Java
apache-2.0
86a92debf83ef9836821391af9b59141d147cd4f
0
apache/directory-fortress-commander,apache/directory-fortress-commander
/* * 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.directory.fortress.web.control; import com.googlecode.wicket.jquery.ui.form.button.IndicatingAjaxButton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.wicket.Component; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.directory.fortress.core.*; import org.apache.directory.fortress.core.model.Permission; import javax.servlet.http.HttpServletRequest; /** * ... * * @author Shawn McKinney * @version $Rev$ */ public class SecureIndicatingAjaxButton extends IndicatingAjaxButton { Permission perm; @SpringBean private AccessMgr accessMgr; private static final Logger LOG = LoggerFactory.getLogger( SecureIndicatingAjaxButton.class.getName() ); public SecureIndicatingAjaxButton( Component component, String id, String objectName, String opName ) { super( id ); this.perm = new Permission(objectName, opName); if( SecUtils.IS_PERM_CACHED) { if(!SecUtils.isFound( perm, this )) setVisible( false ); } else { boolean isAuthorized = false; try { WicketSession session = ( WicketSession )component.getSession(); isAuthorized = accessMgr.checkAccess( session.getSession(), perm ); LOG.info( "Fortress checkAccess objectName: " + objectName + " operationName: " + opName + " userId: " + session.getSession().getUserId() + " result: " + isAuthorized); } catch(org.apache.directory.fortress.core.SecurityException se) { String error = "Fortress SecurityException checkAccess objectName: " + objectName + " operationName: " + opName + " error=" + se; LOG.error( error ); } if(!isAuthorized) setVisible( false ); } } public SecureIndicatingAjaxButton( String id, String roleName ) { super( id ); HttpServletRequest servletReq = ( HttpServletRequest ) getRequest().getContainerRequest(); if( ! SecUtils.isAuthorized( roleName, servletReq ) ) setVisible( false ); } public SecureIndicatingAjaxButton( String id, String objName, String opName ) { super( id ); if ( !SecUtils.isFound( new Permission( objName, opName ), this ) ) setVisible( false ); LOG.info( "arbac perm objName: " + this.perm.getObjName() + " opName: " + this.perm.getOpName() + ", not found in session"); } protected boolean checkAccess( String objectName, String opName ) { boolean isAuthorized = false; try { WicketSession session = ( WicketSession )getSession(); Permission permission = new Permission( objectName, opName ); //Permission permission = new Permission( objectName, perm.getOpName() ); isAuthorized = accessMgr.checkAccess( session.getSession(), permission ); LOG.info( "Fortress checkAccess objectName: " + permission.getObjName() + " operationName: " + permission.getOpName() + " userId: " + session.getSession().getUserId() + " result: " + isAuthorized); } catch(org.apache.directory.fortress.core.SecurityException se) { String error = "Fortress SecurityException checkAccess objectName: " + this.perm.getObjName() + " operationName: " + this.perm.getOpName() + " error=" + se; LOG.error( error ); } return isAuthorized; } protected boolean checkAccess( ) { boolean isAuthorized = false; try { WicketSession session = ( WicketSession )getSession(); isAuthorized = accessMgr.checkAccess( session.getSession(), perm ); LOG.info( "Fortress checkAccess objName: " + this.perm.getObjName() + " opName: " + this.perm.getOpName() + " userId: " + session.getSession().getUserId() + " result: " + isAuthorized); } catch(org.apache.directory.fortress.core.SecurityException se) { String error = "Fortress SecurityException checkAccess objName: " + this.perm.getObjName() + " opName: " + this.perm.getOpName() + " error=" + se; LOG.error( error ); } return isAuthorized; } protected boolean checkAccess( String objectId ) { boolean isAuthorized = false; try { WicketSession session = ( WicketSession )getSession(); Permission finePerm = new Permission(perm.getObjName(), perm.getOpName(), objectId); isAuthorized = accessMgr.checkAccess( session.getSession(), finePerm ); LOG.info( "Fortress checkAccess objName: " + this.perm.getObjName() + " opName: " + this.perm.getOpName() + ", objId: " + finePerm.getObjId() + ", userId: " + session.getSession().getUserId() + " result: " + isAuthorized); } catch(org.apache.directory.fortress.core.SecurityException se) { String error = "Fortress SecurityException checkAccess objectName: " + this.perm.getObjName() + " opName: " + this.perm.getOpName() + ", objId: " + objectId + ", error=" + se; LOG.error( error ); } return isAuthorized; } }
src/main/java/org/apache/directory/fortress/web/control/SecureIndicatingAjaxButton.java
/* * 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.directory.fortress.web.control; import com.googlecode.wicket.jquery.ui.form.button.IndicatingAjaxButton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.wicket.Component; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.directory.fortress.core.*; import org.apache.directory.fortress.core.model.Permission; import javax.servlet.http.HttpServletRequest; /** * ... * * @author Shawn McKinney * @version $Rev$ */ public class SecureIndicatingAjaxButton extends IndicatingAjaxButton { Permission perm; @SpringBean private AccessMgr accessMgr; private static final Logger LOG = LoggerFactory.getLogger( SecureIndicatingAjaxButton.class.getName() ); public SecureIndicatingAjaxButton( Component component, String id, String objectName, String opName ) { super( id ); this.perm = new Permission(objectName, opName); if( SecUtils.IS_PERM_CACHED) { if(!SecUtils.isFound( perm, this )) setVisible( false ); } else { boolean isAuthorized = false; try { WicketSession session = ( WicketSession )component.getSession(); isAuthorized = accessMgr.checkAccess( session.getSession(), perm ); LOG.info( "Fortress checkAccess objectName: " + objectName + " operationName: " + opName + " userId: " + session.getSession().getUserId() + " result: " + isAuthorized); } catch(org.apache.directory.fortress.core.SecurityException se) { String error = "Fortress SecurityException checkAccess objectName: " + objectName + " operationName: " + opName + " error=" + se; LOG.error( error ); } if(!isAuthorized) setVisible( false ); } } public SecureIndicatingAjaxButton( String id, String roleName ) { super( id ); HttpServletRequest servletReq = ( HttpServletRequest ) getRequest().getContainerRequest(); if( ! SecUtils.isAuthorized( roleName, servletReq ) ) setVisible( false ); } public SecureIndicatingAjaxButton( String id, String objName, String opName ) { super( id ); if ( !SecUtils.isFound( new Permission( objName, opName ), this ) ) setVisible( false ); } protected boolean checkAccess( String objectName, String opName ) { boolean isAuthorized = false; try { WicketSession session = ( WicketSession )getSession(); Permission permission = new Permission( objectName, opName ); //Permission permission = new Permission( objectName, perm.getOpName() ); isAuthorized = accessMgr.checkAccess( session.getSession(), permission ); LOG.info( "Fortress checkAccess objectName: " + permission.getObjName() + " operationName: " + permission.getOpName() + " userId: " + session.getSession().getUserId() + " result: " + isAuthorized); } catch(org.apache.directory.fortress.core.SecurityException se) { String error = "Fortress SecurityException checkAccess objectName: " + this.perm.getObjName() + " operationName: " + this.perm.getOpName() + " error=" + se; LOG.error( error ); } return isAuthorized; } protected boolean checkAccess( ) { boolean isAuthorized = false; try { WicketSession session = ( WicketSession )getSession(); isAuthorized = accessMgr.checkAccess( session.getSession(), perm ); LOG.info( "Fortress checkAccess objName: " + this.perm.getObjName() + " opName: " + this.perm.getOpName() + " userId: " + session.getSession().getUserId() + " result: " + isAuthorized); } catch(org.apache.directory.fortress.core.SecurityException se) { String error = "Fortress SecurityException checkAccess objName: " + this.perm.getObjName() + " opName: " + this.perm.getOpName() + " error=" + se; LOG.error( error ); } return isAuthorized; } protected boolean checkAccess( String objectId ) { boolean isAuthorized = false; try { WicketSession session = ( WicketSession )getSession(); Permission finePerm = new Permission(perm.getObjName(), perm.getOpName(), objectId); isAuthorized = accessMgr.checkAccess( session.getSession(), finePerm ); LOG.info( "Fortress checkAccess objName: " + this.perm.getObjName() + " opName: " + this.perm.getOpName() + ", objId: " + finePerm.getObjId() + ", userId: " + session.getSession().getUserId() + " result: " + isAuthorized); } catch(org.apache.directory.fortress.core.SecurityException se) { String error = "Fortress SecurityException checkAccess objectName: " + this.perm.getObjName() + " opName: " + this.perm.getOpName() + ", objId: " + objectId + ", error=" + se; LOG.error( error ); } return isAuthorized; } }
info msg when button can't be shown
src/main/java/org/apache/directory/fortress/web/control/SecureIndicatingAjaxButton.java
info msg when button can't be shown
Java
apache-2.0
93201959b8aa6b660b6bfd8793b841f139d12414
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
package org.apache.solr.search; /* * 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. */ import java.util.HashSet; import java.util.Set; import org.apache.lucene.search.Query; import org.apache.lucene.search.QueryUtils; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrRequestInfo; import org.apache.solr.response.SolrQueryResponse; import org.junit.AfterClass; import org.junit.BeforeClass; /** * Sanity checks that queries (generated by the QParser and ValueSourceParser * framework) are appropriately {@link Object#equals} and * {@link Object#hashCode()} equivalent. If you are adding a new default * QParser or ValueSourceParser, you will most likely get a failure from * {@link #testParserCoverage} until you add a new test method to this class. * * @see ValueSourceParser#standardValueSourceParsers * @see QParserPlugin#standardPlugins * @see QueryUtils **/ public class QueryEqualityTest extends SolrTestCaseJ4 { @BeforeClass public static void beforeClass() throws Exception { initCore("solrconfig.xml","schema15.xml"); } /** @see #testParserCoverage */ @AfterClass public static void afterClassParserCoverageTest() { if ( ! doAssertParserCoverage) return; for (int i=0; i < QParserPlugin.standardPlugins.length; i+=2) { assertTrue("qparser #"+i+" name not a string", QParserPlugin.standardPlugins[i] instanceof String); final String name = (String)QParserPlugin.standardPlugins[i]; assertTrue("testParserCoverage was run w/o any other method explicitly testing qparser: " + name, qParsersTested.contains(name)); } for (final String name : ValueSourceParser.standardValueSourceParsers.keySet()) { assertTrue("testParserCoverage was run w/o any other method explicitly testing val parser: " + name, valParsersTested.contains(name)); } } /** @see #testParserCoverage */ private static boolean doAssertParserCoverage = false; /** @see #testParserCoverage */ private static final Set<String> qParsersTested = new HashSet<String>(); /** @see #testParserCoverage */ private static final Set<String> valParsersTested = new HashSet<String>(); public void testDateMathParsingEquality() throws Exception { // regardless of parser, these should all be equivalent queries assertQueryEquals (null ,"{!lucene}f_tdt:2013-09-11T00\\:00\\:00Z" ,"{!lucene}f_tdt:2013-03-08T00\\:46\\:15Z/DAY+6MONTHS+3DAYS" ,"{!lucene}f_tdt:\"2013-03-08T00:46:15Z/DAY+6MONTHS+3DAYS\"" ,"{!field f=f_tdt}2013-03-08T00:46:15Z/DAY+6MONTHS+3DAYS" ,"{!field f=f_tdt}2013-09-11T00:00:00Z" ,"{!term f=f_tdt}2013-03-08T00:46:15Z/DAY+6MONTHS+3DAYS" ,"{!term f=f_tdt}2013-09-11T00:00:00Z" ); } public void testQueryLucene() throws Exception { assertQueryEquals("lucene", "{!lucene}apache solr", "apache solr", "apache solr "); assertQueryEquals("lucene", "+apache +solr", "apache AND solr", " +apache +solr"); } public void testQueryLucenePlusSort() throws Exception { assertQueryEquals("lucenePlusSort", "apache solr", "apache solr", "apache solr ; score desc"); assertQueryEquals("lucenePlusSort", "+apache +solr", "apache AND solr", " +apache +solr; score desc"); } public void testQueryPrefix() throws Exception { SolrQueryRequest req = req("myField","foo_s"); try { assertQueryEquals("prefix", req, "{!prefix f=$myField}asdf", "{!prefix f=foo_s}asdf"); } finally { req.close(); } } public void testQueryBoost() throws Exception { SolrQueryRequest req = req("df","foo_s","myBoost","sum(3,foo_i)"); try { assertQueryEquals("boost", req, "{!boost b=$myBoost}asdf", "{!boost b=$myBoost v=asdf}", "{!boost b=sum(3,foo_i)}foo_s:asdf"); } finally { req.close(); } } public void testQuerySwitch() throws Exception { SolrQueryRequest req = req("myXXX", "XXX", "myField", "foo_s", "myQ", "{!prefix f=$myField}asdf"); try { assertQueryEquals("switch", req, "{!switch case.foo=XXX case.bar=zzz case.yak=qqq}foo", "{!switch case.foo=qqq case.bar=XXX case.yak=zzz} bar ", "{!switch case.foo=qqq case.bar=XXX case.yak=zzz v=' bar '}", "{!switch default=XXX case.foo=qqq case.bar=zzz}asdf", "{!switch default=$myXXX case.foo=qqq case.bar=zzz}asdf", "{!switch case=XXX case.bar=zzz case.yak=qqq v=''}", "{!switch case.bar=zzz case=XXX case.yak=qqq v=''}", "{!switch case=XXX case.bar=zzz case.yak=qqq}", "{!switch case=XXX case.bar=zzz case.yak=qqq} ", "{!switch case=$myXXX case.bar=zzz case.yak=qqq} "); assertQueryEquals("switch", req, "{!switch case.foo=$myQ case.bar=zzz case.yak=qqq}foo", "{!query v=$myQ}"); } finally { req.close(); } } public void testQueryDismax() throws Exception { for (final String type : new String[]{"dismax","edismax"}) { assertQueryEquals(type, "{!"+type+"}apache solr", "apache solr", "apache solr", "apache solr "); assertQueryEquals(type, "+apache +solr", "apache AND solr", " +apache +solr"); } } public void testField() throws Exception { SolrQueryRequest req = req("myField","foo_s"); try { assertQueryEquals("field", req, "{!field f=$myField}asdf", "{!field f=$myField v=asdf}", "{!field f=foo_s}asdf"); } finally { req.close(); } } public void testQueryRaw() throws Exception { SolrQueryRequest req = req("myField","foo_s"); try { assertQueryEquals("raw", req, "{!raw f=$myField}asdf", "{!raw f=$myField v=asdf}", "{!raw f=foo_s}asdf"); } finally { req.close(); } } public void testQueryTerm() throws Exception { SolrQueryRequest req = req("myField","foo_s"); try { assertQueryEquals("term", req, "{!term f=$myField}asdf", "{!term f=$myField v=asdf}", "{!term f=foo_s}asdf"); } finally { req.close(); } } public void testQueryNested() throws Exception { SolrQueryRequest req = req("df", "foo_s"); try { assertQueryEquals("query", req, "{!query defType=lucene}asdf", "{!query v='foo_s:asdf'}", "{!query}foo_s:asdf", "{!query}asdf"); } finally { req.close(); } } public void testQueryFunc() throws Exception { // more involved tests of specific functions in other methods SolrQueryRequest req = req("myVar", "5", "myField","foo_i", "myInner","product(4,foo_i)"); try { assertQueryEquals("func", req, "{!func}sum(4,5)", "{!func}sum(4,$myVar)", "sum(4,5)"); assertQueryEquals("func", req, "{!func}sum(1,2,3,4,5)", "{!func}sum(1,2,3,4,$myVar)", "sum(1,2,3,4,5)"); assertQueryEquals("func", req, "{!func}sum(4,$myInner)", "{!func}sum(4,product(4,foo_i))", "{!func}sum(4,product(4,$myField))", "{!func}sum(4,product(4,field(foo_i)))"); } finally { req.close(); } } public void testQueryFrange() throws Exception { SolrQueryRequest req = req("myVar", "5", "low","0.2", "high", "20.4", "myField","foo_i", "myInner","product(4,foo_i)"); try { assertQueryEquals("frange", req, "{!frange l=0.2 h=20.4}sum(4,5)", "{!frange l=$low h=$high}sum(4,$myVar)"); } finally { req.close(); } } public void testQueryGeofilt() throws Exception { checkQuerySpatial("geofilt"); } public void testQueryBbox() throws Exception { checkQuerySpatial("bbox"); } private void checkQuerySpatial(final String type) throws Exception { SolrQueryRequest req = req("myVar", "5", "d","109", "pt","10.312,-20.556", "sfield","store"); try { assertQueryEquals(type, req, "{!"+type+" d=109}", "{!"+type+" sfield=$sfield}", "{!"+type+" sfield=store d=109}", "{!"+type+" sfield=store d=$d pt=$pt}", "{!"+type+" sfield=store d=$d pt=10.312,-20.556}", "{!"+type+"}"); // diff SpatialQueryable FieldTypes matter for determining final query assertQueryEquals(type, req, "{!"+type+" sfield=point_hash}", "{!"+type+" sfield=point_hash d=109}", "{!"+type+" sfield=point_hash d=$d pt=$pt}", "{!"+type+" sfield=point_hash d=$d pt=10.312,-20.556}"); assertQueryEquals(type, req, "{!"+type+" sfield=point}", "{!"+type+" sfield=point d=109}", "{!"+type+" sfield=point d=$d pt=$pt}", "{!"+type+" sfield=point d=$d pt=10.312,-20.556}"); } finally { req.close(); } } public void testQueryJoin() throws Exception { SolrQueryRequest req = req("myVar", "5", "df","text", "ff","foo_s", "tt", "bar_s"); try { assertQueryEquals("join", req, "{!join from=foo_s to=bar_s}asdf", "{!join from=$ff to=$tt}asdf", "{!join from=$ff to='bar_s'}text:asdf"); } finally { req.close(); } } public void testQuerySurround() throws Exception { assertQueryEquals("surround", "{!surround}and(apache,solr)", "and(apache,solr)", "apache AND solr"); } public void testFuncTestfunc() throws Exception { assertFuncEquals("testfunc(foo_i)","testfunc(field(foo_i))"); assertFuncEquals("testfunc(23)"); assertFuncEquals("testfunc(sum(23,foo_i))", "testfunc(sum(23,field(foo_i)))"); } public void testFuncOrd() throws Exception { assertFuncEquals("ord(foo_s)","ord(foo_s )"); } public void testFuncLiteral() throws Exception { SolrQueryRequest req = req("someVar","a string"); try { assertFuncEquals(req, "literal('a string')","literal(\"a string\")", "literal($someVar)"); } finally { req.close(); } } public void testFuncRord() throws Exception { assertFuncEquals("rord(foo_s)","rord(foo_s )"); } public void testFuncTop() throws Exception { assertFuncEquals("top(sum(3,foo_i))"); } public void testFuncLinear() throws Exception { SolrQueryRequest req = req("someVar","27"); try { assertFuncEquals(req, "linear(foo_i,$someVar,42)", "linear(foo_i, 27, 42)"); } finally { req.close(); } } public void testFuncRecip() throws Exception { SolrQueryRequest req = req("someVar","27"); try { assertFuncEquals(req, "recip(foo_i,$someVar,42, 27 )", "recip(foo_i, 27, 42,$someVar)"); } finally { req.close(); } } public void testFuncScale() throws Exception { SolrQueryRequest req = req("someVar","27"); try { assertFuncEquals(req, "scale(field(foo_i),$someVar,42)", "scale(foo_i, 27, 42)"); } finally { req.close(); } } public void testFuncDiv() throws Exception { assertFuncEquals("div(5,4)", "div(5, 4)"); assertFuncEquals("div(foo_i,4)", "div(foo_i, 4)", "div(field('foo_i'), 4)"); assertFuncEquals("div(foo_i,sub(4,field('bar_i')))", "div(field(foo_i), sub(4,bar_i))"); } public void testFuncMod() throws Exception { assertFuncEquals("mod(5,4)", "mod(5, 4)"); assertFuncEquals("mod(foo_i,4)", "mod(foo_i, 4)", "mod(field('foo_i'), 4)"); assertFuncEquals("mod(foo_i,sub(4,field('bar_i')))", "mod(field(foo_i), sub(4,bar_i))"); } public void testFuncMap() throws Exception { assertFuncEquals("map(field(foo_i), 0, 45, 100)", "map(foo_i, 0.0, 45, 100)"); } public void testFuncSum() throws Exception { assertFuncEquals("sum(5,4)", "add(5, 4)"); assertFuncEquals("sum(5,4,3,2,1)", "add(5, 4, 3, 2, 1)"); assertFuncEquals("sum(foo_i,4)", "sum(foo_i, 4)", "sum(field('foo_i'), 4)"); assertFuncEquals("add(foo_i,sub(4,field('bar_i')))", "sum(field(foo_i), sub(4,bar_i))"); } public void testFuncProduct() throws Exception { assertFuncEquals("product(5,4,3,2,1)", "mul(5, 4, 3, 2, 1)"); assertFuncEquals("product(5,4)", "mul(5, 4)"); assertFuncEquals("product(foo_i,4)", "product(foo_i, 4)", "product(field('foo_i'), 4)"); assertFuncEquals("mul(foo_i,sub(4,field('bar_i')))", "product(field(foo_i), sub(4,bar_i))"); } public void testFuncSub() throws Exception { assertFuncEquals("sub(5,4)", "sub(5, 4)"); assertFuncEquals("sub(foo_i,4)", "sub(foo_i, 4)"); assertFuncEquals("sub(foo_i,sum(4,bar_i))", "sub(foo_i, sum(4,bar_i))"); } public void testFuncVector() throws Exception { assertFuncEquals("vector(5,4, field(foo_i))", "vector(5, 4, foo_i)"); assertFuncEquals("vector(foo_i,4)", "vector(foo_i, 4)"); assertFuncEquals("vector(foo_i,sum(4,bar_i))", "vector(foo_i, sum(4,bar_i))"); } public void testFuncQuery() throws Exception { SolrQueryRequest req = req("myQ","asdf"); try { assertFuncEquals(req, "query($myQ)", "query($myQ,0)", "query({!lucene v=$myQ},0)"); } finally { req.close(); } } public void testFuncBoost() throws Exception { SolrQueryRequest req = req("myQ","asdf"); try { assertFuncEquals(req, "boost($myQ,sum(4,5))", "boost({!lucene v=$myQ},sum(4,5))"); } finally { req.close(); } } public void testFuncJoindf() throws Exception { assertFuncEquals("joindf(foo,bar)"); } public void testFuncGeodist() throws Exception { SolrQueryRequest req = req("pt","10.312,-20.556", "sfield","store"); try { assertFuncEquals(req, "geodist()", "geodist($sfield,$pt)", "geodist(store,$pt)", "geodist(field(store),$pt)", "geodist(store,10.312,-20.556)"); } finally { req.close(); } } public void testFuncHsin() throws Exception { assertFuncEquals("hsin(45,true,0,0,45,45)"); } public void testFuncGhhsin() throws Exception { assertFuncEquals("ghhsin(45,point_hash,'asdf')", "ghhsin(45,field(point_hash),'asdf')"); } public void testFuncGeohash() throws Exception { assertFuncEquals("geohash(45,99)"); } public void testFuncDist() throws Exception { assertFuncEquals("dist(2,45,99,101,111)", "dist(2,vector(45,99),vector(101,111))"); } public void testFuncSqedist() throws Exception { assertFuncEquals("sqedist(45,99,101,111)", "sqedist(vector(45,99),vector(101,111))"); } public void testFuncMin() throws Exception { assertFuncEquals("min(5,4,3,2,1)", "min(5, 4, 3, 2, 1)"); assertFuncEquals("min(foo_i,4)", "min(field('foo_i'), 4)"); assertFuncEquals("min(foo_i,sub(4,field('bar_i')))", "min(field(foo_i), sub(4,bar_i))"); } public void testFuncMax() throws Exception { assertFuncEquals("max(5,4,3,2,1)", "max(5, 4, 3, 2, 1)"); assertFuncEquals("max(foo_i,4)", "max(field('foo_i'), 4)"); assertFuncEquals("max(foo_i,sub(4,field('bar_i')))", "max(field(foo_i), sub(4,bar_i))"); } public void testFuncMs() throws Exception { // Note ms() takes in field name, not field(...) assertFuncEquals("ms()", "ms(NOW)"); assertFuncEquals("ms(2000-01-01T00:00:00Z)", "ms('2000-01-01T00:00:00Z')"); assertFuncEquals("ms(myDateField_dt)", "ms('myDateField_dt')"); assertFuncEquals("ms(2000-01-01T00:00:00Z,myDateField_dt)", "ms('2000-01-01T00:00:00Z','myDateField_dt')"); assertFuncEquals("ms(myDateField_dt, NOW)", "ms('myDateField_dt', NOW)"); } public void testFuncMathConsts() throws Exception { assertFuncEquals("pi()"); assertFuncEquals("e()"); } public void testFuncTerms() throws Exception { SolrQueryRequest req = req("myField","field_t","myTerm","my term"); try { for (final String type : new String[]{"docfreq","termfreq", "totaltermfreq","ttf", "idf","tf"}) { // NOTE: these functions takes a field *name* not a field(..) source assertFuncEquals(req, type + "('field_t','my term')", type + "(field_t,'my term')", type + "(field_t,$myTerm)", type + "(field_t,$myTerm)", type + "($myField,$myTerm)"); } // ttf is an alias for totaltermfreq assertFuncEquals(req, "ttf(field_t,'my term')", "ttf('field_t','my term')", "totaltermfreq(field_t,'my term')"); } finally { req.close(); } } public void testFuncSttf() throws Exception { // sttf is an alias for sumtotaltermfreq assertFuncEquals("sttf(foo_t)", "sttf('foo_t')", "sumtotaltermfreq(foo_t)", "sumtotaltermfreq('foo_t')"); assertFuncEquals("sumtotaltermfreq('foo_t')"); } public void testFuncNorm() throws Exception { assertFuncEquals("norm(foo_t)","norm('foo_t')"); } public void testFuncMaxdoc() throws Exception { assertFuncEquals("maxdoc()"); } public void testFuncNumdocs() throws Exception { assertFuncEquals("numdocs()"); } public void testFuncBools() throws Exception { SolrQueryRequest req = req("myTrue","true","myFalse","false"); try { assertFuncEquals(req, "true","$myTrue"); assertFuncEquals(req, "false","$myFalse"); } finally { req.close(); } } public void testFuncExists() throws Exception { SolrQueryRequest req = req("myField","field_t","myQ","asdf"); try { assertFuncEquals(req, "exists(field_t)", "exists($myField)", "exists(field('field_t'))", "exists(field($myField))"); assertFuncEquals(req, "exists(query($myQ))", "exists(query({!lucene v=$myQ}))"); } finally { req.close(); } } public void testFuncNot() throws Exception { SolrQueryRequest req = req("myField","field_b", "myTrue","true"); try { assertFuncEquals(req, "not(true)", "not($myTrue)"); assertFuncEquals(req, "not(not(true))", "not(not($myTrue))"); assertFuncEquals(req, "not(field_b)", "not($myField)", "not(field('field_b'))", "not(field($myField))"); assertFuncEquals(req, "not(exists(field_b))", "not(exists($myField))", "not(exists(field('field_b')))", "not(exists(field($myField)))"); } finally { req.close(); } } public void testFuncDoubleValueBools() throws Exception { SolrQueryRequest req = req("myField","field_b","myTrue","true"); try { for (final String type : new String[]{"and","or","xor"}) { assertFuncEquals(req, type + "(field_b,true)", type + "(field_b,$myTrue)", type + "(field('field_b'),true)", type + "(field($myField),$myTrue)", type + "($myField,$myTrue)"); } } finally { req.close(); } } public void testFuncIf() throws Exception { SolrQueryRequest req = req("myBoolField","foo_b", "myIntField","bar_i", "myTrue","true"); try { assertFuncEquals(req, "if(foo_b,bar_i,25)", "if($myBoolField,bar_i,25)", "if(field('foo_b'),$myIntField,25)", "if(field($myBoolField),field('bar_i'),25)"); assertFuncEquals(req, "if(true,37,field($myIntField))", "if($myTrue,37,$myIntField)"); } finally { req.close(); } } public void testFuncDef() throws Exception { SolrQueryRequest req = req("myField","bar_f"); try { assertFuncEquals(req, "def(bar_f,25)", "def($myField,25)", "def(field('bar_f'),25)"); assertFuncEquals(req, "def(ceil(bar_f),25)", "def(ceil($myField),25)", "def(ceil(field('bar_f')),25)"); } finally { req.close(); } } public void testFuncSingleValueMathFuncs() throws Exception { SolrQueryRequest req = req("myVal","45", "myField","foo_i"); for (final String func : new String[] {"abs","rad","deg","sqrt","cbrt", "log","ln","exp","sin","cos","tan", "asin","acos","atan", "sinh","cosh","tanh", "ceil","floor","rint"}) { try { assertFuncEquals(req, func + "(field(foo_i))", func + "(foo_i)", func + "($myField)"); assertFuncEquals(req, func + "(45)", func+ "($myVal)"); } finally { req.close(); } } } public void testFuncDoubleValueMathFuncs() throws Exception { SolrQueryRequest req = req("myVal","45", "myOtherVal", "27", "myField","foo_i"); for (final String func : new String[] {"pow","hypot","atan2"}) { try { assertFuncEquals(req, func + "(field(foo_i),$myVal)", func+"(foo_i,$myVal)", func + "($myField,45)"); assertFuncEquals(req, func+"(45,$myOtherVal)", func+"($myVal,27)", func+"($myVal,$myOtherVal)"); } finally { req.close(); } } } public void testFuncStrdist() throws Exception { SolrQueryRequest req = req("myVal","zot", "myOtherVal", "yak", "myField","foo_s1"); try { assertFuncEquals(req, "strdist(\"zot\",literal('yak'),edit)", "strdist(literal(\"zot\"),'yak', edit )", "strdist(literal($myVal),literal($myOtherVal),edit)"); assertFuncEquals(req, "strdist(\"zot\",literal($myOtherVal),ngram)", "strdist(\"zot\",'yak', ngram, 2)"); assertFuncEquals(req, "strdist(field('foo_s1'),literal($myOtherVal),jw)", "strdist(field($myField),\"yak\",jw)", "strdist($myField,'yak', jw)"); } finally { req.close(); } } public void testFuncField() throws Exception { assertFuncEquals("field(\"foo_i\")", "field('foo_i\')", "foo_i"); } public void testFuncCurrency() throws Exception { assertFuncEquals("currency(\"amount\")", "currency('amount\')", "currency(amount)", "currency(amount,USD)", "currency('amount',USD)"); } public void testTestFuncs() throws Exception { assertFuncEquals("sleep(1,5)", "sleep(1,5)"); assertFuncEquals("threadid()", "threadid()"); } // TODO: more tests public void testQueryMaxScore() throws Exception { assertQueryEquals("maxscore", "{!maxscore}A OR B OR C", "A OR B OR C"); assertQueryEquals("maxscore", "{!maxscore}A AND B", "A AND B"); assertQueryEquals("maxscore", "{!maxscore}apache -solr", "apache -solr", "apache -solr "); assertQueryEquals("maxscore", "+apache +solr", "apache AND solr", "+apache +solr"); } /** * this test does not assert anything itself, it simply toggles a static * boolean informing an @AfterClass method to assert that every default * qparser and valuesource parser configured was recorded by * assertQueryEquals and assertFuncEquals. */ public void testParserCoverage() { doAssertParserCoverage = true; } /** * NOTE: defType is not only used to pick the parser, but also to record * the parser being tested for coverage sanity checking * @see #testParserCoverage * @see #assertQueryEquals */ protected void assertQueryEquals(final String defType, final String... inputs) throws Exception { SolrQueryRequest req = req(); try { assertQueryEquals(defType, req, inputs); } finally { req.close(); } } /** * NOTE: defType is not only used to pick the parser, but, if non-null it is * also to record the parser being tested for coverage sanity checking * * @see QueryUtils#check * @see QueryUtils#checkEqual * @see #testParserCoverage */ protected void assertQueryEquals(final String defType, final SolrQueryRequest req, final String... inputs) throws Exception { if (null != defType) qParsersTested.add(defType); final Query[] queries = new Query[inputs.length]; try { SolrQueryResponse rsp = new SolrQueryResponse(); SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req,rsp)); for (int i = 0; i < inputs.length; i++) { queries[i] = (QParser.getParser(inputs[i], defType, req).getQuery()); } } finally { SolrRequestInfo.clearRequestInfo(); } for (int i = 0; i < queries.length; i++) { QueryUtils.check(queries[i]); // yes starting j=0 is redundent, we're making sure every query // is equal to itself, and that the quality checks work regardless // of which caller/callee is used. for (int j = 0; j < queries.length; j++) { QueryUtils.checkEqual(queries[i], queries[j]); } } } /** * the function name for val parser coverage checking is extracted from * the first input * @see #assertQueryEquals * @see #testParserCoverage */ protected void assertFuncEquals(final String... inputs) throws Exception { SolrQueryRequest req = req(); try { assertFuncEquals(req, inputs); } finally { req.close(); } } /** * the function name for val parser coverage checking is extracted from * the first input * @see #assertQueryEquals * @see #testParserCoverage */ protected void assertFuncEquals(final SolrQueryRequest req, final String... inputs) throws Exception { // pull out the function name final String funcName = (new QueryParsing.StrParser(inputs[0])).getId(); valParsersTested.add(funcName); assertQueryEquals(FunctionQParserPlugin.NAME, req, inputs); } }
solr/core/src/test/org/apache/solr/search/QueryEqualityTest.java
package org.apache.solr.search; /* * 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. */ import java.util.HashSet; import java.util.Set; import org.apache.lucene.search.Query; import org.apache.lucene.search.QueryUtils; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrRequestInfo; import org.apache.solr.response.SolrQueryResponse; import org.junit.AfterClass; import org.junit.BeforeClass; /** * Sanity checks that queries (generated by the QParser and ValueSourceParser * framework) are appropraitely {@link Object#equals} and * {@link Object#hashCode()} equivilent. If you are adding a new default * QParser or ValueSourceParser, you will most likely get a failure from * {@link #testParserCoverage} until you add a new test method to this class. * * @see ValueSourceParser#standardValueSourceParsers * @see QParserPlugin#standardPlugins * @see QueryUtils **/ public class QueryEqualityTest extends SolrTestCaseJ4 { @BeforeClass public static void beforeClass() throws Exception { initCore("solrconfig.xml","schema15.xml"); } /** @see #testParserCoverage */ @AfterClass public static void afterClassParserCoverageTest() { if ( ! doAssertParserCoverage) return; for (int i=0; i < QParserPlugin.standardPlugins.length; i+=2) { assertTrue("qparser #"+i+" name not a string", QParserPlugin.standardPlugins[i] instanceof String); final String name = (String)QParserPlugin.standardPlugins[i]; assertTrue("testParserCoverage was run w/o any other method explicitly testing qparser: " + name, qParsersTested.contains(name)); } for (final String name : ValueSourceParser.standardValueSourceParsers.keySet()) { assertTrue("testParserCoverage was run w/o any other method explicitly testing val parser: " + name, valParsersTested.contains(name)); } } /** @see #testParserCoverage */ private static boolean doAssertParserCoverage = false; /** @see #testParserCoverage */ private static final Set<String> qParsersTested = new HashSet<String>(); /** @see #testParserCoverage */ private static final Set<String> valParsersTested = new HashSet<String>(); public void testDateMathParsingEquality() throws Exception { // regardless of parser, these should all be equivilent queries assertQueryEquals (null ,"{!lucene}f_tdt:2013-09-11T00\\:00\\:00Z" ,"{!lucene}f_tdt:2013-03-08T00\\:46\\:15Z/DAY+6MONTHS+3DAYS" ,"{!lucene}f_tdt:\"2013-03-08T00:46:15Z/DAY+6MONTHS+3DAYS\"" ,"{!field f=f_tdt}2013-03-08T00:46:15Z/DAY+6MONTHS+3DAYS" ,"{!field f=f_tdt}2013-09-11T00:00:00Z" ,"{!term f=f_tdt}2013-03-08T00:46:15Z/DAY+6MONTHS+3DAYS" ,"{!term f=f_tdt}2013-09-11T00:00:00Z" ); } public void testQueryLucene() throws Exception { assertQueryEquals("lucene", "{!lucene}apache solr", "apache solr", "apache solr "); assertQueryEquals("lucene", "+apache +solr", "apache AND solr", " +apache +solr"); } public void testQueryLucenePlusSort() throws Exception { assertQueryEquals("lucenePlusSort", "apache solr", "apache solr", "apache solr ; score desc"); assertQueryEquals("lucenePlusSort", "+apache +solr", "apache AND solr", " +apache +solr; score desc"); } public void testQueryPrefix() throws Exception { SolrQueryRequest req = req("myField","foo_s"); try { assertQueryEquals("prefix", req, "{!prefix f=$myField}asdf", "{!prefix f=foo_s}asdf"); } finally { req.close(); } } public void testQueryBoost() throws Exception { SolrQueryRequest req = req("df","foo_s","myBoost","sum(3,foo_i)"); try { assertQueryEquals("boost", req, "{!boost b=$myBoost}asdf", "{!boost b=$myBoost v=asdf}", "{!boost b=sum(3,foo_i)}foo_s:asdf"); } finally { req.close(); } } public void testQuerySwitch() throws Exception { SolrQueryRequest req = req("myXXX", "XXX", "myField", "foo_s", "myQ", "{!prefix f=$myField}asdf"); try { assertQueryEquals("switch", req, "{!switch case.foo=XXX case.bar=zzz case.yak=qqq}foo", "{!switch case.foo=qqq case.bar=XXX case.yak=zzz} bar ", "{!switch case.foo=qqq case.bar=XXX case.yak=zzz v=' bar '}", "{!switch default=XXX case.foo=qqq case.bar=zzz}asdf", "{!switch default=$myXXX case.foo=qqq case.bar=zzz}asdf", "{!switch case=XXX case.bar=zzz case.yak=qqq v=''}", "{!switch case.bar=zzz case=XXX case.yak=qqq v=''}", "{!switch case=XXX case.bar=zzz case.yak=qqq}", "{!switch case=XXX case.bar=zzz case.yak=qqq} ", "{!switch case=$myXXX case.bar=zzz case.yak=qqq} "); assertQueryEquals("switch", req, "{!switch case.foo=$myQ case.bar=zzz case.yak=qqq}foo", "{!query v=$myQ}"); } finally { req.close(); } } public void testQueryDismax() throws Exception { for (final String type : new String[]{"dismax","edismax"}) { assertQueryEquals(type, "{!"+type+"}apache solr", "apache solr", "apache solr", "apache solr "); assertQueryEquals(type, "+apache +solr", "apache AND solr", " +apache +solr"); } } public void testField() throws Exception { SolrQueryRequest req = req("myField","foo_s"); try { assertQueryEquals("field", req, "{!field f=$myField}asdf", "{!field f=$myField v=asdf}", "{!field f=foo_s}asdf"); } finally { req.close(); } } public void testQueryRaw() throws Exception { SolrQueryRequest req = req("myField","foo_s"); try { assertQueryEquals("raw", req, "{!raw f=$myField}asdf", "{!raw f=$myField v=asdf}", "{!raw f=foo_s}asdf"); } finally { req.close(); } } public void testQueryTerm() throws Exception { SolrQueryRequest req = req("myField","foo_s"); try { assertQueryEquals("term", req, "{!term f=$myField}asdf", "{!term f=$myField v=asdf}", "{!term f=foo_s}asdf"); } finally { req.close(); } } public void testQueryNested() throws Exception { SolrQueryRequest req = req("df", "foo_s"); try { assertQueryEquals("query", req, "{!query defType=lucene}asdf", "{!query v='foo_s:asdf'}", "{!query}foo_s:asdf", "{!query}asdf"); } finally { req.close(); } } public void testQueryFunc() throws Exception { // more involved tests of specific functions in other methods SolrQueryRequest req = req("myVar", "5", "myField","foo_i", "myInner","product(4,foo_i)"); try { assertQueryEquals("func", req, "{!func}sum(4,5)", "{!func}sum(4,$myVar)", "sum(4,5)"); assertQueryEquals("func", req, "{!func}sum(1,2,3,4,5)", "{!func}sum(1,2,3,4,$myVar)", "sum(1,2,3,4,5)"); assertQueryEquals("func", req, "{!func}sum(4,$myInner)", "{!func}sum(4,product(4,foo_i))", "{!func}sum(4,product(4,$myField))", "{!func}sum(4,product(4,field(foo_i)))"); } finally { req.close(); } } public void testQueryFrange() throws Exception { SolrQueryRequest req = req("myVar", "5", "low","0.2", "high", "20.4", "myField","foo_i", "myInner","product(4,foo_i)"); try { assertQueryEquals("frange", req, "{!frange l=0.2 h=20.4}sum(4,5)", "{!frange l=$low h=$high}sum(4,$myVar)"); } finally { req.close(); } } public void testQueryGeofilt() throws Exception { checkQuerySpatial("geofilt"); } public void testQueryBbox() throws Exception { checkQuerySpatial("bbox"); } private void checkQuerySpatial(final String type) throws Exception { SolrQueryRequest req = req("myVar", "5", "d","109", "pt","10.312,-20.556", "sfield","store"); try { assertQueryEquals(type, req, "{!"+type+" d=109}", "{!"+type+" sfield=$sfield}", "{!"+type+" sfield=store d=109}", "{!"+type+" sfield=store d=$d pt=$pt}", "{!"+type+" sfield=store d=$d pt=10.312,-20.556}", "{!"+type+"}"); // diff SpatialQueryable FieldTypes matter for determining final query assertQueryEquals(type, req, "{!"+type+" sfield=point_hash}", "{!"+type+" sfield=point_hash d=109}", "{!"+type+" sfield=point_hash d=$d pt=$pt}", "{!"+type+" sfield=point_hash d=$d pt=10.312,-20.556}"); assertQueryEquals(type, req, "{!"+type+" sfield=point}", "{!"+type+" sfield=point d=109}", "{!"+type+" sfield=point d=$d pt=$pt}", "{!"+type+" sfield=point d=$d pt=10.312,-20.556}"); } finally { req.close(); } } public void testQueryJoin() throws Exception { SolrQueryRequest req = req("myVar", "5", "df","text", "ff","foo_s", "tt", "bar_s"); try { assertQueryEquals("join", req, "{!join from=foo_s to=bar_s}asdf", "{!join from=$ff to=$tt}asdf", "{!join from=$ff to='bar_s'}text:asdf"); } finally { req.close(); } } public void testQuerySurround() throws Exception { assertQueryEquals("surround", "{!surround}and(apache,solr)", "and(apache,solr)", "apache AND solr"); } public void testFuncTestfunc() throws Exception { assertFuncEquals("testfunc(foo_i)","testfunc(field(foo_i))"); assertFuncEquals("testfunc(23)"); assertFuncEquals("testfunc(sum(23,foo_i))", "testfunc(sum(23,field(foo_i)))"); } public void testFuncOrd() throws Exception { assertFuncEquals("ord(foo_s)","ord(foo_s )"); } public void testFuncLiteral() throws Exception { SolrQueryRequest req = req("someVar","a string"); try { assertFuncEquals(req, "literal('a string')","literal(\"a string\")", "literal($someVar)"); } finally { req.close(); } } public void testFuncRord() throws Exception { assertFuncEquals("rord(foo_s)","rord(foo_s )"); } public void testFuncTop() throws Exception { assertFuncEquals("top(sum(3,foo_i))"); } public void testFuncLinear() throws Exception { SolrQueryRequest req = req("someVar","27"); try { assertFuncEquals(req, "linear(foo_i,$someVar,42)", "linear(foo_i, 27, 42)"); } finally { req.close(); } } public void testFuncRecip() throws Exception { SolrQueryRequest req = req("someVar","27"); try { assertFuncEquals(req, "recip(foo_i,$someVar,42, 27 )", "recip(foo_i, 27, 42,$someVar)"); } finally { req.close(); } } public void testFuncScale() throws Exception { SolrQueryRequest req = req("someVar","27"); try { assertFuncEquals(req, "scale(field(foo_i),$someVar,42)", "scale(foo_i, 27, 42)"); } finally { req.close(); } } public void testFuncDiv() throws Exception { assertFuncEquals("div(5,4)", "div(5, 4)"); assertFuncEquals("div(foo_i,4)", "div(foo_i, 4)", "div(field('foo_i'), 4)"); assertFuncEquals("div(foo_i,sub(4,field('bar_i')))", "div(field(foo_i), sub(4,bar_i))"); } public void testFuncMod() throws Exception { assertFuncEquals("mod(5,4)", "mod(5, 4)"); assertFuncEquals("mod(foo_i,4)", "mod(foo_i, 4)", "mod(field('foo_i'), 4)"); assertFuncEquals("mod(foo_i,sub(4,field('bar_i')))", "mod(field(foo_i), sub(4,bar_i))"); } public void testFuncMap() throws Exception { assertFuncEquals("map(field(foo_i), 0, 45, 100)", "map(foo_i, 0.0, 45, 100)"); } public void testFuncSum() throws Exception { assertFuncEquals("sum(5,4)", "add(5, 4)"); assertFuncEquals("sum(5,4,3,2,1)", "add(5, 4, 3, 2, 1)"); assertFuncEquals("sum(foo_i,4)", "sum(foo_i, 4)", "sum(field('foo_i'), 4)"); assertFuncEquals("add(foo_i,sub(4,field('bar_i')))", "sum(field(foo_i), sub(4,bar_i))"); } public void testFuncProduct() throws Exception { assertFuncEquals("product(5,4,3,2,1)", "mul(5, 4, 3, 2, 1)"); assertFuncEquals("product(5,4)", "mul(5, 4)"); assertFuncEquals("product(foo_i,4)", "product(foo_i, 4)", "product(field('foo_i'), 4)"); assertFuncEquals("mul(foo_i,sub(4,field('bar_i')))", "product(field(foo_i), sub(4,bar_i))"); } public void testFuncSub() throws Exception { assertFuncEquals("sub(5,4)", "sub(5, 4)"); assertFuncEquals("sub(foo_i,4)", "sub(foo_i, 4)"); assertFuncEquals("sub(foo_i,sum(4,bar_i))", "sub(foo_i, sum(4,bar_i))"); } public void testFuncVector() throws Exception { assertFuncEquals("vector(5,4, field(foo_i))", "vector(5, 4, foo_i)"); assertFuncEquals("vector(foo_i,4)", "vector(foo_i, 4)"); assertFuncEquals("vector(foo_i,sum(4,bar_i))", "vector(foo_i, sum(4,bar_i))"); } public void testFuncQuery() throws Exception { SolrQueryRequest req = req("myQ","asdf"); try { assertFuncEquals(req, "query($myQ)", "query($myQ,0)", "query({!lucene v=$myQ},0)"); } finally { req.close(); } } public void testFuncBoost() throws Exception { SolrQueryRequest req = req("myQ","asdf"); try { assertFuncEquals(req, "boost($myQ,sum(4,5))", "boost({!lucene v=$myQ},sum(4,5))"); } finally { req.close(); } } public void testFuncJoindf() throws Exception { assertFuncEquals("joindf(foo,bar)"); } public void testFuncGeodist() throws Exception { SolrQueryRequest req = req("pt","10.312,-20.556", "sfield","store"); try { assertFuncEquals(req, "geodist()", "geodist($sfield,$pt)", "geodist(store,$pt)", "geodist(field(store),$pt)", "geodist(store,10.312,-20.556)"); } finally { req.close(); } } public void testFuncHsin() throws Exception { assertFuncEquals("hsin(45,true,0,0,45,45)"); } public void testFuncGhhsin() throws Exception { assertFuncEquals("ghhsin(45,point_hash,'asdf')", "ghhsin(45,field(point_hash),'asdf')"); } public void testFuncGeohash() throws Exception { assertFuncEquals("geohash(45,99)"); } public void testFuncDist() throws Exception { assertFuncEquals("dist(2,45,99,101,111)", "dist(2,vector(45,99),vector(101,111))"); } public void testFuncSqedist() throws Exception { assertFuncEquals("sqedist(45,99,101,111)", "sqedist(vector(45,99),vector(101,111))"); } public void testFuncMin() throws Exception { assertFuncEquals("min(5,4,3,2,1)", "min(5, 4, 3, 2, 1)"); assertFuncEquals("min(foo_i,4)", "min(field('foo_i'), 4)"); assertFuncEquals("min(foo_i,sub(4,field('bar_i')))", "min(field(foo_i), sub(4,bar_i))"); } public void testFuncMax() throws Exception { assertFuncEquals("max(5,4,3,2,1)", "max(5, 4, 3, 2, 1)"); assertFuncEquals("max(foo_i,4)", "max(field('foo_i'), 4)"); assertFuncEquals("max(foo_i,sub(4,field('bar_i')))", "max(field(foo_i), sub(4,bar_i))"); } public void testFuncMs() throws Exception { // Note ms() takes in field name, not field(...) assertFuncEquals("ms()", "ms(NOW)"); assertFuncEquals("ms(2000-01-01T00:00:00Z)", "ms('2000-01-01T00:00:00Z')"); assertFuncEquals("ms(myDateField_dt)", "ms('myDateField_dt')"); assertFuncEquals("ms(2000-01-01T00:00:00Z,myDateField_dt)", "ms('2000-01-01T00:00:00Z','myDateField_dt')"); assertFuncEquals("ms(myDateField_dt, NOW)", "ms('myDateField_dt', NOW)"); } public void testFuncMathConsts() throws Exception { assertFuncEquals("pi()"); assertFuncEquals("e()"); } public void testFuncTerms() throws Exception { SolrQueryRequest req = req("myField","field_t","myTerm","my term"); try { for (final String type : new String[]{"docfreq","termfreq", "totaltermfreq","ttf", "idf","tf"}) { // NOTE: these functions takes a field *name* not a field(..) source assertFuncEquals(req, type + "('field_t','my term')", type + "(field_t,'my term')", type + "(field_t,$myTerm)", type + "(field_t,$myTerm)", type + "($myField,$myTerm)"); } // ttf is an alias for totaltermfreq assertFuncEquals(req, "ttf(field_t,'my term')", "ttf('field_t','my term')", "totaltermfreq(field_t,'my term')"); } finally { req.close(); } } public void testFuncSttf() throws Exception { // sttf is an alias for sumtotaltermfreq assertFuncEquals("sttf(foo_t)", "sttf('foo_t')", "sumtotaltermfreq(foo_t)", "sumtotaltermfreq('foo_t')"); assertFuncEquals("sumtotaltermfreq('foo_t')"); } public void testFuncNorm() throws Exception { assertFuncEquals("norm(foo_t)","norm('foo_t')"); } public void testFuncMaxdoc() throws Exception { assertFuncEquals("maxdoc()"); } public void testFuncNumdocs() throws Exception { assertFuncEquals("numdocs()"); } public void testFuncBools() throws Exception { SolrQueryRequest req = req("myTrue","true","myFalse","false"); try { assertFuncEquals(req, "true","$myTrue"); assertFuncEquals(req, "false","$myFalse"); } finally { req.close(); } } public void testFuncExists() throws Exception { SolrQueryRequest req = req("myField","field_t","myQ","asdf"); try { assertFuncEquals(req, "exists(field_t)", "exists($myField)", "exists(field('field_t'))", "exists(field($myField))"); assertFuncEquals(req, "exists(query($myQ))", "exists(query({!lucene v=$myQ}))"); } finally { req.close(); } } public void testFuncNot() throws Exception { SolrQueryRequest req = req("myField","field_b", "myTrue","true"); try { assertFuncEquals(req, "not(true)", "not($myTrue)"); assertFuncEquals(req, "not(not(true))", "not(not($myTrue))"); assertFuncEquals(req, "not(field_b)", "not($myField)", "not(field('field_b'))", "not(field($myField))"); assertFuncEquals(req, "not(exists(field_b))", "not(exists($myField))", "not(exists(field('field_b')))", "not(exists(field($myField)))"); } finally { req.close(); } } public void testFuncDoubleValueBools() throws Exception { SolrQueryRequest req = req("myField","field_b","myTrue","true"); try { for (final String type : new String[]{"and","or","xor"}) { assertFuncEquals(req, type + "(field_b,true)", type + "(field_b,$myTrue)", type + "(field('field_b'),true)", type + "(field($myField),$myTrue)", type + "($myField,$myTrue)"); } } finally { req.close(); } } public void testFuncIf() throws Exception { SolrQueryRequest req = req("myBoolField","foo_b", "myIntField","bar_i", "myTrue","true"); try { assertFuncEquals(req, "if(foo_b,bar_i,25)", "if($myBoolField,bar_i,25)", "if(field('foo_b'),$myIntField,25)", "if(field($myBoolField),field('bar_i'),25)"); assertFuncEquals(req, "if(true,37,field($myIntField))", "if($myTrue,37,$myIntField)"); } finally { req.close(); } } public void testFuncDef() throws Exception { SolrQueryRequest req = req("myField","bar_f"); try { assertFuncEquals(req, "def(bar_f,25)", "def($myField,25)", "def(field('bar_f'),25)"); assertFuncEquals(req, "def(ceil(bar_f),25)", "def(ceil($myField),25)", "def(ceil(field('bar_f')),25)"); } finally { req.close(); } } public void testFuncSingleValueMathFuncs() throws Exception { SolrQueryRequest req = req("myVal","45", "myField","foo_i"); for (final String func : new String[] {"abs","rad","deg","sqrt","cbrt", "log","ln","exp","sin","cos","tan", "asin","acos","atan", "sinh","cosh","tanh", "ceil","floor","rint"}) { try { assertFuncEquals(req, func + "(field(foo_i))", func + "(foo_i)", func + "($myField)"); assertFuncEquals(req, func + "(45)", func+ "($myVal)"); } finally { req.close(); } } } public void testFuncDoubleValueMathFuncs() throws Exception { SolrQueryRequest req = req("myVal","45", "myOtherVal", "27", "myField","foo_i"); for (final String func : new String[] {"pow","hypot","atan2"}) { try { assertFuncEquals(req, func + "(field(foo_i),$myVal)", func+"(foo_i,$myVal)", func + "($myField,45)"); assertFuncEquals(req, func+"(45,$myOtherVal)", func+"($myVal,27)", func+"($myVal,$myOtherVal)"); } finally { req.close(); } } } public void testFuncStrdist() throws Exception { SolrQueryRequest req = req("myVal","zot", "myOtherVal", "yak", "myField","foo_s1"); try { assertFuncEquals(req, "strdist(\"zot\",literal('yak'),edit)", "strdist(literal(\"zot\"),'yak', edit )", "strdist(literal($myVal),literal($myOtherVal),edit)"); assertFuncEquals(req, "strdist(\"zot\",literal($myOtherVal),ngram)", "strdist(\"zot\",'yak', ngram, 2)"); assertFuncEquals(req, "strdist(field('foo_s1'),literal($myOtherVal),jw)", "strdist(field($myField),\"yak\",jw)", "strdist($myField,'yak', jw)"); } finally { req.close(); } } public void testFuncField() throws Exception { assertFuncEquals("field(\"foo_i\")", "field('foo_i\')", "foo_i"); } public void testFuncCurrency() throws Exception { assertFuncEquals("currency(\"amount\")", "currency('amount\')", "currency(amount)", "currency(amount,USD)", "currency('amount',USD)"); } public void testTestFuncs() throws Exception { assertFuncEquals("sleep(1,5)", "sleep(1,5)"); assertFuncEquals("threadid()", "threadid()"); } /** * this test does not assert anything itself, it simply toggles a static * boolean informing an @AfterClass method to assert that every default * qparser and valuesource parser configured was recorded by * assertQueryEquals and assertFuncEquals. */ public void testParserCoverage() { doAssertParserCoverage = true; } /** * NOTE: defType is not only used to pick the parser, but also to record * the parser being tested for coverage sanity checking * @see #testParserCoverage * @see #assertQueryEquals */ protected void assertQueryEquals(final String defType, final String... inputs) throws Exception { SolrQueryRequest req = req(); try { assertQueryEquals(defType, req, inputs); } finally { req.close(); } } /** * NOTE: defType is not only used to pick the parser, but, if non-null it is * also to record the parser being tested for coverage sanity checking * * @see QueryUtils#check * @see QueryUtils#checkEqual * @see #testParserCoverage */ protected void assertQueryEquals(final String defType, final SolrQueryRequest req, final String... inputs) throws Exception { if (null != defType) qParsersTested.add(defType); final Query[] queries = new Query[inputs.length]; try { SolrQueryResponse rsp = new SolrQueryResponse(); SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req,rsp)); for (int i = 0; i < inputs.length; i++) { queries[i] = (QParser.getParser(inputs[i], defType, req).getQuery()); } } finally { SolrRequestInfo.clearRequestInfo(); } for (int i = 0; i < queries.length; i++) { QueryUtils.check(queries[i]); // yes starting j=0 is redundent, we're making sure every query // is equal to itself, and that the quality checks work regardless // of which caller/callee is used. for (int j = 0; j < queries.length; j++) { QueryUtils.checkEqual(queries[i], queries[j]); } } } /** * the function name for val parser coverage checking is extracted from * the first input * @see #assertQueryEquals * @see #testParserCoverage */ protected void assertFuncEquals(final String... inputs) throws Exception { SolrQueryRequest req = req(); try { assertFuncEquals(req, inputs); } finally { req.close(); } } /** * the function name for val parser coverage checking is extracted from * the first input * @see #assertQueryEquals * @see #testParserCoverage */ protected void assertFuncEquals(final SolrQueryRequest req, final String... inputs) throws Exception { // pull out the function name final String funcName = (new QueryParsing.StrParser(inputs[0])).getId(); valParsersTested.add(funcName); assertQueryEquals(FunctionQParserPlugin.NAME, req, inputs); } }
SOLR-4785: add gbowyer's tests to unbreak build git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1481977 13f79535-47bb-0310-9956-ffa450edef68
solr/core/src/test/org/apache/solr/search/QueryEqualityTest.java
SOLR-4785: add gbowyer's tests to unbreak build
Java
apache-2.0
444e20b62b45b172d5882714a91e455f2d47d4f3
0
wreckJ/intellij-community,diorcety/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,allotria/intellij-community,holmes/intellij-community,tmpgit/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,supersven/intellij-community,kool79/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,slisson/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,kool79/intellij-community,xfournet/intellij-community,diorcety/intellij-community,jagguli/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,dslomov/intellij-community,signed/intellij-community,blademainer/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,izonder/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,supersven/intellij-community,kool79/intellij-community,amith01994/intellij-community,clumsy/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,semonte/intellij-community,Lekanich/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,asedunov/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,adedayo/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,da1z/intellij-community,jagguli/intellij-community,caot/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,ibinti/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,caot/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,izonder/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,slisson/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,supersven/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,FHannes/intellij-community,jagguli/intellij-community,izonder/intellij-community,diorcety/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,izonder/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,apixandru/intellij-community,signed/intellij-community,semonte/intellij-community,caot/intellij-community,apixandru/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,da1z/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,adedayo/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,ol-loginov/intellij-community,caot/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,ibinti/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,allotria/intellij-community,robovm/robovm-studio,kdwink/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,hurricup/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,da1z/intellij-community,jagguli/intellij-community,diorcety/intellij-community,robovm/robovm-studio,blademainer/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,samthor/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,da1z/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,dslomov/intellij-community,samthor/intellij-community,ryano144/intellij-community,asedunov/intellij-community,ryano144/intellij-community,samthor/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,kdwink/intellij-community,holmes/intellij-community,caot/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,ibinti/intellij-community,samthor/intellij-community,signed/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,da1z/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,xfournet/intellij-community,izonder/intellij-community,xfournet/intellij-community,holmes/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,semonte/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,signed/intellij-community,nicolargo/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,amith01994/intellij-community,semonte/intellij-community,caot/intellij-community,vladmm/intellij-community,robovm/robovm-studio,ryano144/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,vladmm/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,supersven/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,retomerz/intellij-community,slisson/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,fnouama/intellij-community,holmes/intellij-community,samthor/intellij-community,semonte/intellij-community,ryano144/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,samthor/intellij-community,petteyg/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,fitermay/intellij-community,blademainer/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,vladmm/intellij-community,fnouama/intellij-community,allotria/intellij-community,fitermay/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,da1z/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,signed/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,caot/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,fnouama/intellij-community,ibinti/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,izonder/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,clumsy/intellij-community,da1z/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,da1z/intellij-community,diorcety/intellij-community,ryano144/intellij-community,holmes/intellij-community,FHannes/intellij-community,izonder/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,petteyg/intellij-community,petteyg/intellij-community,vladmm/intellij-community,caot/intellij-community,apixandru/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,kool79/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,robovm/robovm-studio,kool79/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,kool79/intellij-community,akosyakov/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,samthor/intellij-community,da1z/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,holmes/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,slisson/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,semonte/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,caot/intellij-community,caot/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,clumsy/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,amith01994/intellij-community,fitermay/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,suncycheng/intellij-community,supersven/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,dslomov/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,caot/intellij-community,signed/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,signed/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,allotria/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,allotria/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,signed/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,clumsy/intellij-community,hurricup/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,jagguli/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,diorcety/intellij-community,dslomov/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,allotria/intellij-community,slisson/intellij-community,hurricup/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,vvv1559/intellij-community,holmes/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,kdwink/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,slisson/intellij-community,suncycheng/intellij-community,izonder/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community
/* * Copyright 2000-2013 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.remoteServer.agent.util.log; import com.intellij.remoteServer.agent.util.CloudAgentLogger; import com.intellij.remoteServer.agent.util.CloudAgentLoggingHandler; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * @author michael.golubev */ public abstract class LogPipe { private final String myDeploymentName; private final String myLogPipeName; private final CloudAgentLogger myLogger; private final CloudAgentLoggingHandler myLoggingHandler; private boolean myClosed; private int myTotalLines; private int myLines2Skip; public LogPipe(String deploymentName, String logPipeName, CloudAgentLogger logger, CloudAgentLoggingHandler loggingHandler) { myDeploymentName = deploymentName; myLogPipeName = logPipeName; myLogger = logger; myLoggingHandler = loggingHandler; myClosed = false; } public void open() { InputStream inputStream = createInputStream(myDeploymentName); if (inputStream == null) { return; } InputStreamReader streamReader = new InputStreamReader(inputStream); final BufferedReader bufferedReader = new BufferedReader(streamReader); myTotalLines = 0; myLines2Skip = 0; new Thread() { @Override public void run() { try { while (true) { String line = bufferedReader.readLine(); if (myClosed) { myLogger.debug("log pipe closed for: " + myDeploymentName); break; } if (line == null) { myLogger.debug("end of log stream for: " + myDeploymentName); break; } if (myLines2Skip == 0) { getLogListener().lineLogged(line); myTotalLines++; } else { myLines2Skip--; } } } catch (IOException e) { myLoggingHandler.println(e.toString()); } } }.start(); } public void close() { myClosed = true; } protected final void cutTail() { myLines2Skip = myTotalLines; } protected final boolean isClosed() { return myClosed; } protected abstract InputStream createInputStream(String deploymentName); protected LogListener getLogListener() { return myLoggingHandler.getOrCreateLogListener(myLogPipeName); } }
platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipe.java
/* * Copyright 2000-2013 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.remoteServer.agent.util.log; import com.intellij.remoteServer.agent.util.ILogger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * @author michael.golubev */ public abstract class LogPipe { private final ILogger myLog; private final String myDeploymentName; private boolean myClosed; private int myTotalLines; private int myLines2Skip; public LogPipe(String deploymentName, ILogger log) { myDeploymentName = deploymentName; myLog = log; myClosed = false; } public void open() { InputStream inputStream = createInputStream(myDeploymentName); if (inputStream == null) { return; } InputStreamReader streamReader = new InputStreamReader(inputStream); final BufferedReader bufferedReader = new BufferedReader(streamReader); myTotalLines = 0; myLines2Skip = 0; new Thread() { @Override public void run() { try { while (true) { String line = bufferedReader.readLine(); if (myClosed) { myLog.debug("log pipe closed for: " + myDeploymentName); break; } if (line == null) { myLog.debug("end of log stream for: " + myDeploymentName); break; } if (myLines2Skip == 0) { getLogListener().lineLogged(line); myTotalLines++; } else { myLines2Skip--; } } } catch (IOException e) { myLog.errorEx(e); } } }.start(); } public void close() { myClosed = true; } protected final void cutTail() { myLines2Skip = myTotalLines; } protected final boolean isClosed() { return myClosed; } protected abstract InputStream createInputStream(String deploymentName); protected abstract LogListener getLogListener(); }
Clouds - refactor logs
platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipe.java
Clouds - refactor logs
Java
apache-2.0
a52a5b31bfde42fd414f2d280981adfbe6a654e6
0
youdonghai/intellij-community,da1z/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,robovm/robovm-studio,clumsy/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,FHannes/intellij-community,kdwink/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,ahb0327/intellij-community,samthor/intellij-community,joewalnes/idea-community,apixandru/intellij-community,hurricup/intellij-community,hurricup/intellij-community,jexp/idea2,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,samthor/intellij-community,fnouama/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,signed/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,clumsy/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,izonder/intellij-community,slisson/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,samthor/intellij-community,orekyuu/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,retomerz/intellij-community,kdwink/intellij-community,joewalnes/idea-community,kool79/intellij-community,signed/intellij-community,blademainer/intellij-community,fnouama/intellij-community,da1z/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,izonder/intellij-community,caot/intellij-community,semonte/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,petteyg/intellij-community,adedayo/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,jexp/idea2,retomerz/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,salguarnieri/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,caot/intellij-community,robovm/robovm-studio,amith01994/intellij-community,ernestp/consulo,youdonghai/intellij-community,asedunov/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,allotria/intellij-community,supersven/intellij-community,diorcety/intellij-community,ibinti/intellij-community,blademainer/intellij-community,allotria/intellij-community,diorcety/intellij-community,apixandru/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,slisson/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,supersven/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,caot/intellij-community,wreckJ/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,allotria/intellij-community,kool79/intellij-community,da1z/intellij-community,signed/intellij-community,slisson/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,caot/intellij-community,kool79/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,retomerz/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,supersven/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,fitermay/intellij-community,samthor/intellij-community,kdwink/intellij-community,blademainer/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,kdwink/intellij-community,da1z/intellij-community,tmpgit/intellij-community,slisson/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,consulo/consulo,asedunov/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,dslomov/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,ernestp/consulo,adedayo/intellij-community,samthor/intellij-community,fitermay/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,allotria/intellij-community,wreckJ/intellij-community,slisson/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,samthor/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,adedayo/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,signed/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,consulo/consulo,ahb0327/intellij-community,allotria/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,allotria/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,allotria/intellij-community,signed/intellij-community,petteyg/intellij-community,amith01994/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,izonder/intellij-community,jexp/idea2,vladmm/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,adedayo/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,caot/intellij-community,fnouama/intellij-community,asedunov/intellij-community,FHannes/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,da1z/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,izonder/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,petteyg/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,blademainer/intellij-community,caot/intellij-community,jexp/idea2,slisson/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,jagguli/intellij-community,caot/intellij-community,blademainer/intellij-community,caot/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,kool79/intellij-community,kool79/intellij-community,hurricup/intellij-community,signed/intellij-community,clumsy/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,kool79/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,signed/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,holmes/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,supersven/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,allotria/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,ryano144/intellij-community,jagguli/intellij-community,da1z/intellij-community,vvv1559/intellij-community,jexp/idea2,youdonghai/intellij-community,izonder/intellij-community,jagguli/intellij-community,consulo/consulo,retomerz/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ibinti/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,holmes/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,semonte/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,amith01994/intellij-community,jexp/idea2,FHannes/intellij-community,dslomov/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,semonte/intellij-community,slisson/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,kdwink/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,kool79/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,signed/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,adedayo/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,izonder/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,Lekanich/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,asedunov/intellij-community,semonte/intellij-community,FHannes/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,da1z/intellij-community,fitermay/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,fnouama/intellij-community,semonte/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,jagguli/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,ernestp/consulo,youdonghai/intellij-community,ryano144/intellij-community,robovm/robovm-studio,kool79/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,jexp/idea2,pwoodworth/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,petteyg/intellij-community,da1z/intellij-community,allotria/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,supersven/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,caot/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,signed/intellij-community,consulo/consulo,asedunov/intellij-community,xfournet/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,blademainer/intellij-community,supersven/intellij-community,robovm/robovm-studio,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,supersven/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,amith01994/intellij-community,signed/intellij-community,retomerz/intellij-community,consulo/consulo,consulo/consulo,MER-GROUP/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,allotria/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,apixandru/intellij-community,holmes/intellij-community,xfournet/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,caot/intellij-community,FHannes/intellij-community,apixandru/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ernestp/consulo,pwoodworth/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,dslomov/intellij-community,asedunov/intellij-community,izonder/intellij-community,ernestp/consulo,jexp/idea2,akosyakov/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,signed/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,amith01994/intellij-community
/* * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers * * 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.siyeh.ig.junit; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.psiutils.ClassUtils; import com.siyeh.ig.psiutils.MethodCallUtils; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class SimplifiableJUnitAssertionInspection extends BaseInspection { public String getDisplayName() { return InspectionGadgetsBundle.message( "simplifiable.junit.assertion.display.name"); } @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "simplifiable.junit.assertion.problem.descriptor"); } public InspectionGadgetsFix buildFix(PsiElement location) { return new SimplifyJUnitAssertFix(); } private static class SimplifyJUnitAssertFix extends InspectionGadgetsFix { public String getName() { return InspectionGadgetsBundle.message( "simplify.j.unit.assertion.simplify.quickfix"); } public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement methodNameIdentifier = descriptor.getPsiElement(); final PsiElement parent = methodNameIdentifier.getParent(); assert parent != null; final PsiMethodCallExpression callExpression = (PsiMethodCallExpression)parent.getParent(); if (isAssertTrueThatCouldBeAssertSame(callExpression)) { replaceAssertTrueWithAssertSame(callExpression, project); return; } if (isAssertTrueThatCouldBeAssertEquality(callExpression)) { replaceAssertTrueWithAssertEquals(callExpression, project); } else if (isAssertEqualsThatCouldBeAssertLiteral(callExpression)) { replaceAssertEqualsWithAssertLiteral(callExpression, project); } else if (isAssertThatCouldBeFail(callExpression)) { replaceAssertWithFail(callExpression); } } private static void replaceAssertWithFail( PsiMethodCallExpression callExpression) throws IncorrectOperationException { final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); assert method != null; final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); final PsiExpressionList argumentList = callExpression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); final PsiExpression message; if (parameters.length == 2) { message = arguments[0]; } else { message = null; } @NonNls final StringBuilder newExpression = new StringBuilder(); final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(callExpression, PsiMethod.class); if (containingMethod != null && AnnotationUtil.isAnnotated(containingMethod, "org.junit.Test", true)) { newExpression.append("org.junit.Assert."); } newExpression.append("fail("); if (message != null) { newExpression.append(message.getText()); } newExpression.append(')'); replaceExpressionAndShorten(callExpression, newExpression.toString()); } private static void replaceAssertTrueWithAssertEquals( PsiMethodCallExpression callExpression, Project project) throws IncorrectOperationException { final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); assert method != null; final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); final PsiManager psiManager = callExpression.getManager(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final PsiExpressionList argumentList = callExpression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final int testPosition; final PsiExpression message; if (paramType1.equals(stringType) && parameters.length >= 2) { testPosition = 1; message = args[0]; } else { testPosition = 0; message = null; } final PsiExpression testArg = args[testPosition]; PsiExpression lhs = null; PsiExpression rhs = null; if (testArg instanceof PsiBinaryExpression) { lhs = ((PsiBinaryExpression)testArg).getLOperand(); rhs = ((PsiBinaryExpression)testArg).getROperand(); } else if (testArg instanceof PsiMethodCallExpression) { final PsiMethodCallExpression call = (PsiMethodCallExpression)testArg; final PsiReferenceExpression equalityMethodExpression = call.getMethodExpression(); final PsiExpressionList equalityArgumentList = call.getArgumentList(); final PsiExpression[] equalityArgs = equalityArgumentList.getExpressions(); rhs = equalityArgs[0]; lhs = equalityMethodExpression.getQualifierExpression(); } if (!(lhs instanceof PsiLiteralExpression) && rhs instanceof PsiLiteralExpression) { final PsiExpression temp = lhs; lhs = rhs; rhs = temp; } @NonNls final StringBuilder newExpression = new StringBuilder(); final PsiMethod containingMethod = PsiTreeUtil.getParentOfType( callExpression, PsiMethod.class); if (containingMethod != null && AnnotationUtil.isAnnotated( containingMethod, "org.junit.Test", true)) { newExpression.append("org.junit.Assert."); } newExpression.append("assertEquals("); if (message != null) { newExpression.append(message.getText()); newExpression.append(','); } assert lhs != null; newExpression.append(lhs.getText()); newExpression.append(','); assert rhs != null; newExpression.append(rhs.getText()); if (isFloatingPoint(lhs) || isFloatingPoint(rhs)) { newExpression.append(",0.0"); } newExpression.append(')'); replaceExpressionAndShorten(callExpression, newExpression.toString()); } private static void replaceAssertTrueWithAssertSame( PsiMethodCallExpression callExpression, Project project) throws IncorrectOperationException { final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); assert method != null; final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); final PsiManager psiManager = callExpression.getManager(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final PsiExpressionList argumentList = callExpression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final int testPosition; final PsiExpression message; if (paramType1.equals(stringType) && parameters.length >= 2) { testPosition = 1; message = args[0]; } else { testPosition = 0; message = null; } final PsiExpression testArg = args[testPosition]; PsiExpression lhs = null; PsiExpression rhs = null; if (testArg instanceof PsiBinaryExpression) { lhs = ((PsiBinaryExpression)testArg).getLOperand(); rhs = ((PsiBinaryExpression)testArg).getROperand(); } else if (testArg instanceof PsiMethodCallExpression) { final PsiMethodCallExpression call = (PsiMethodCallExpression)testArg; final PsiReferenceExpression equalityMethodExpression = call.getMethodExpression(); final PsiExpressionList equalityArgumentList = call.getArgumentList(); final PsiExpression[] equalityArgs = equalityArgumentList.getExpressions(); rhs = equalityArgs[0]; lhs = equalityMethodExpression.getQualifierExpression(); } if (!(lhs instanceof PsiLiteralExpression) && rhs instanceof PsiLiteralExpression) { final PsiExpression temp = lhs; lhs = rhs; rhs = temp; } @NonNls final StringBuilder newExpression = new StringBuilder(); final PsiMethod containingMethod = PsiTreeUtil.getParentOfType( callExpression, PsiMethod.class); if (containingMethod != null && AnnotationUtil.isAnnotated( containingMethod, "org.junit.Test", true)) { newExpression.append("org.junit.Assert."); } newExpression.append("assertSame("); if (message != null) { newExpression.append(message.getText()); newExpression.append(','); } assert lhs != null; newExpression.append(lhs.getText()); newExpression.append(','); assert rhs != null; newExpression.append(rhs.getText()); newExpression.append(')'); replaceExpressionAndShorten(callExpression, newExpression.toString()); } private static void replaceAssertEqualsWithAssertLiteral( PsiMethodCallExpression callExpression, Project project) throws IncorrectOperationException { final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); assert method != null; final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); final PsiManager psiManager = callExpression.getManager(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final PsiExpressionList argumentList = callExpression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final int firstTestPosition; final int secondTestPosition; final PsiExpression message; if (paramType1.equals(stringType) && parameters.length >= 3) { firstTestPosition = 1; secondTestPosition = 2; message = args[0]; } else { firstTestPosition = 0; secondTestPosition = 1; message = null; } final PsiExpression firstTestArg = args[firstTestPosition]; final PsiExpression secondTestArg = args[secondTestPosition]; final String literalValue; final String compareValue; if (isSimpleLiteral(firstTestArg)) { literalValue = firstTestArg.getText(); compareValue = secondTestArg.getText(); } else { literalValue = secondTestArg.getText(); compareValue = firstTestArg.getText(); } final String uppercaseLiteralValue = Character.toUpperCase(literalValue.charAt(0)) + literalValue.substring(1); @NonNls final StringBuilder newExpression = new StringBuilder(); final PsiMethod containingMethod = PsiTreeUtil.getParentOfType( callExpression, PsiMethod.class); if (containingMethod != null && AnnotationUtil.isAnnotated( containingMethod, "org.junit.Test", true)) { newExpression.append("org.junit.Assert."); } newExpression.append("assert"); newExpression.append(uppercaseLiteralValue); newExpression.append('('); if (message != null) { newExpression.append(message.getText()); newExpression.append(','); } newExpression.append(compareValue); newExpression.append(')'); replaceExpressionAndShorten(callExpression, newExpression.toString()); } private static boolean isFloatingPoint(PsiExpression expression) { final PsiType type = expression.getType(); return PsiType.FLOAT.equals(type) || PsiType.DOUBLE.equals(type); } } public BaseInspectionVisitor buildVisitor() { return new SimplifiableJUnitAssertionVisitor(); } private static class SimplifiableJUnitAssertionVisitor extends BaseInspectionVisitor { public void visitMethodCallExpression( @NotNull PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); if (isAssertTrueThatCouldBeAssertSame(expression)) { registerMethodCallError(expression); return; } if (isAssertTrueThatCouldBeAssertEquality(expression)) { registerMethodCallError(expression); } else if (isAssertEqualsThatCouldBeAssertLiteral(expression)) { registerMethodCallError(expression); } else if (isAssertThatCouldBeFail(expression)) { registerMethodCallError(expression); } } } static boolean isAssertTrueThatCouldBeAssertEquality( PsiMethodCallExpression expression) { if (!isAssertTrue(expression)) { return false; } final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length < 1) { return false; } final PsiManager psiManager = expression.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final int testPosition; if (paramType1.equals(stringType) && parameters.length > 1) { testPosition = 1; } else { testPosition = 0; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final PsiExpression testArg = args[testPosition]; return testArg != null && isEqualityComparison(testArg); } static boolean isAssertTrueThatCouldBeAssertSame( PsiMethodCallExpression expression) { if (!isAssertTrue(expression)) { return false; } final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length < 1) { return false; } final PsiManager psiManager = expression.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final int testPosition; if (paramType1.equals(stringType) && parameters.length > 1) { testPosition = 1; } else { testPosition = 0; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final PsiExpression testArg = args[testPosition]; return testArg != null && isIdentityComparison(testArg); } static boolean isAssertThatCouldBeFail(PsiMethodCallExpression expression) { final boolean checkTrue; if (isAssertFalse(expression)) { checkTrue = true; } else if (isAssertTrue(expression)) { checkTrue = false; } else { return false; } final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length < 1) { return false; } final PsiManager psiManager = expression.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final int testPosition; if (paramType1.equals(stringType) && parameters.length > 1) { testPosition = 1; } else { testPosition = 0; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); final PsiExpression testArgument = arguments[testPosition]; if (testArgument == null) { return false; } final String testArgumentText = testArgument.getText(); if (checkTrue) { return PsiKeyword.TRUE.equals(testArgumentText); } else { return PsiKeyword.FALSE.equals(testArgumentText); } } static boolean isAssertEqualsThatCouldBeAssertLiteral( PsiMethodCallExpression expression) { if (!isAssertEquals(expression)) { return false; } final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length < 2) { return false; } final PsiManager psiManager = expression.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final int firstTestPosition; final int secondTestPosition; if (paramType1.equals(stringType) && parameters.length > 2) { firstTestPosition = 1; secondTestPosition = 2; } else { firstTestPosition = 0; secondTestPosition = 1; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final PsiExpression firstTestArg = args[firstTestPosition]; final PsiExpression secondTestArg = args[secondTestPosition]; if (firstTestArg == null) { return false; } return secondTestArg != null && (isSimpleLiteral(firstTestArg) || isSimpleLiteral(secondTestArg)); } static boolean isSimpleLiteral(PsiExpression arg) { if (!(arg instanceof PsiLiteralExpression)) { return false; } final String text = arg.getText(); return PsiKeyword.NULL.equals(text) || PsiKeyword.TRUE.equals(text) || PsiKeyword.FALSE.equals(text); } private static boolean isEqualityComparison(PsiExpression testArg) { if (testArg instanceof PsiBinaryExpression) { final PsiJavaToken sign = ((PsiBinaryExpression)testArg).getOperationSign(); final IElementType tokenType = sign.getTokenType(); if (!tokenType.equals(JavaTokenType.EQEQ)) { return false; } final PsiExpression lhs = ((PsiBinaryExpression)testArg).getLOperand(); final PsiExpression rhs = ((PsiBinaryExpression)testArg).getROperand(); if (rhs == null) { return false; } final PsiType type = lhs.getType(); return type != null && ClassUtils.isPrimitive(type); } else if (testArg instanceof PsiMethodCallExpression) { final PsiMethodCallExpression call = (PsiMethodCallExpression)testArg; if (!MethodCallUtils.isEqualsCall(call)) { return false; } final PsiReferenceExpression methodExpression = call.getMethodExpression(); return methodExpression.getQualifierExpression() != null; } return false; } private static boolean isIdentityComparison(PsiExpression testArg) { if (testArg instanceof PsiBinaryExpression) { final PsiBinaryExpression expression = (PsiBinaryExpression)testArg; final IElementType tokenType = expression.getOperationTokenType(); if (!tokenType.equals(JavaTokenType.EQEQ)) { return false; } final PsiExpression rhs = expression.getROperand(); return rhs != null; } return false; } private static boolean isAssertTrue( @NotNull PsiMethodCallExpression expression) { return isAssertMethodCall(expression, "assertTrue"); } private static boolean isAssertFalse( @NotNull PsiMethodCallExpression expression) { return isAssertMethodCall(expression, "assertFalse"); } private static boolean isAssertEquals( @NotNull PsiMethodCallExpression expression) { return isAssertMethodCall(expression, "assertEquals"); } private static boolean isAssertMethodCall( @NotNull PsiMethodCallExpression expression, @NotNull String assertMethodName) { final PsiReferenceExpression methodExpression = expression.getMethodExpression(); @NonNls final String methodName = methodExpression.getReferenceName(); if (!assertMethodName.equals(methodName)) { return false; } final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiClass targetClass = method.getContainingClass(); if (targetClass == null) { return false; } return ClassUtils.isSubclass(targetClass, "junit.framework.Assert") || ClassUtils.isSubclass(targetClass, "org.junit.Assert"); } }
plugins/InspectionGadgets/src/com/siyeh/ig/junit/SimplifiableJUnitAssertionInspection.java
/* * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers * * 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.siyeh.ig.junit; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.psiutils.ClassUtils; import com.siyeh.ig.psiutils.MethodCallUtils; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class SimplifiableJUnitAssertionInspection extends BaseInspection { public String getDisplayName() { return InspectionGadgetsBundle.message( "simplifiable.junit.assertion.display.name"); } @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "simplifiable.junit.assertion.problem.descriptor"); } public InspectionGadgetsFix buildFix(PsiElement location) { return new SimplifyJUnitAssertFix(); } private static class SimplifyJUnitAssertFix extends InspectionGadgetsFix { public String getName() { return InspectionGadgetsBundle.message( "simplify.j.unit.assertion.simplify.quickfix"); } public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement methodNameIdentifier = descriptor.getPsiElement(); final PsiElement parent = methodNameIdentifier.getParent(); assert parent != null; final PsiMethodCallExpression callExpression = (PsiMethodCallExpression)parent.getParent(); if (isAssertTrueThatCouldBeAssertSame(callExpression)) { replaceAssertTrueWithAssertSame(callExpression, project); return; } if (isAssertTrueThatCouldBeAssertEquality(callExpression)) { replaceAssertTrueWithAssertEquals(callExpression, project); } else if (isAssertEqualsThatCouldBeAssertLiteral(callExpression)) { replaceAssertEqualsWithAssertLiteral(callExpression, project); } else if (isAssertTrueThatCouldBeFail(callExpression)) { replaceAssertWithFail(callExpression); } else if (isAssertFalseThatCouldBeFail(callExpression)) { replaceAssertWithFail(callExpression); } } private static void replaceAssertWithFail( PsiMethodCallExpression callExpression) throws IncorrectOperationException { final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); assert method != null; final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); final PsiExpressionList argumentList = callExpression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final PsiExpression message; if (parameters.length == 2) { message = args[0]; } else { message = null; } @NonNls final StringBuilder newExpression = new StringBuilder(); final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(callExpression, PsiMethod.class); if (containingMethod != null && AnnotationUtil.isAnnotated(containingMethod, "org.junit.Test", true)) { newExpression.append("org.junit.Assert."); } newExpression.append("fail("); if (message != null) { newExpression.append(message.getText()); } newExpression.append(')'); replaceExpressionAndShorten(callExpression, newExpression.toString()); } private static void replaceAssertTrueWithAssertEquals( PsiMethodCallExpression callExpression, Project project) throws IncorrectOperationException { final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); assert method != null; final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); final PsiManager psiManager = callExpression.getManager(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final PsiExpressionList argumentList = callExpression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final int testPosition; final PsiExpression message; if (paramType1.equals(stringType) && parameters.length >= 2) { testPosition = 1; message = args[0]; } else { testPosition = 0; message = null; } final PsiExpression testArg = args[testPosition]; PsiExpression lhs = null; PsiExpression rhs = null; if (testArg instanceof PsiBinaryExpression) { lhs = ((PsiBinaryExpression)testArg).getLOperand(); rhs = ((PsiBinaryExpression)testArg).getROperand(); } else if (testArg instanceof PsiMethodCallExpression) { final PsiMethodCallExpression call = (PsiMethodCallExpression)testArg; final PsiReferenceExpression equalityMethodExpression = call.getMethodExpression(); final PsiExpressionList equalityArgumentList = call.getArgumentList(); final PsiExpression[] equalityArgs = equalityArgumentList.getExpressions(); rhs = equalityArgs[0]; lhs = equalityMethodExpression.getQualifierExpression(); } if (!(lhs instanceof PsiLiteralExpression) && rhs instanceof PsiLiteralExpression) { final PsiExpression temp = lhs; lhs = rhs; rhs = temp; } @NonNls final StringBuilder newExpression = new StringBuilder(); final PsiMethod containingMethod = PsiTreeUtil.getParentOfType( callExpression, PsiMethod.class); if (containingMethod != null && AnnotationUtil.isAnnotated( containingMethod, "org.junit.Test", true)) { newExpression.append("org.junit.Assert."); } newExpression.append("assertEquals("); if (message != null) { newExpression.append(message.getText()); newExpression.append(','); } assert lhs != null; newExpression.append(lhs.getText()); newExpression.append(','); assert rhs != null; newExpression.append(rhs.getText()); if (isFloatingPoint(lhs) || isFloatingPoint(rhs)) { newExpression.append(",0.0"); } newExpression.append(')'); replaceExpressionAndShorten(callExpression, newExpression.toString()); } private static void replaceAssertTrueWithAssertSame( PsiMethodCallExpression callExpression, Project project) throws IncorrectOperationException { final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); assert method != null; final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); final PsiManager psiManager = callExpression.getManager(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final PsiExpressionList argumentList = callExpression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final int testPosition; final PsiExpression message; if (paramType1.equals(stringType) && parameters.length >= 2) { testPosition = 1; message = args[0]; } else { testPosition = 0; message = null; } final PsiExpression testArg = args[testPosition]; PsiExpression lhs = null; PsiExpression rhs = null; if (testArg instanceof PsiBinaryExpression) { lhs = ((PsiBinaryExpression)testArg).getLOperand(); rhs = ((PsiBinaryExpression)testArg).getROperand(); } else if (testArg instanceof PsiMethodCallExpression) { final PsiMethodCallExpression call = (PsiMethodCallExpression)testArg; final PsiReferenceExpression equalityMethodExpression = call.getMethodExpression(); final PsiExpressionList equalityArgumentList = call.getArgumentList(); final PsiExpression[] equalityArgs = equalityArgumentList.getExpressions(); rhs = equalityArgs[0]; lhs = equalityMethodExpression.getQualifierExpression(); } if (!(lhs instanceof PsiLiteralExpression) && rhs instanceof PsiLiteralExpression) { final PsiExpression temp = lhs; lhs = rhs; rhs = temp; } @NonNls final StringBuilder newExpression = new StringBuilder(); final PsiMethod containingMethod = PsiTreeUtil.getParentOfType( callExpression, PsiMethod.class); if (containingMethod != null && AnnotationUtil.isAnnotated( containingMethod, "org.junit.Test", true)) { newExpression.append("org.junit.Assert."); } newExpression.append("assertSame("); if (message != null) { newExpression.append(message.getText()); newExpression.append(','); } assert lhs != null; newExpression.append(lhs.getText()); newExpression.append(','); assert rhs != null; newExpression.append(rhs.getText()); newExpression.append(')'); replaceExpressionAndShorten(callExpression, newExpression.toString()); } private static void replaceAssertEqualsWithAssertLiteral( PsiMethodCallExpression callExpression, Project project) throws IncorrectOperationException { final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); assert method != null; final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); final PsiManager psiManager = callExpression.getManager(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final PsiExpressionList argumentList = callExpression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final int firstTestPosition; final int secondTestPosition; final PsiExpression message; if (paramType1.equals(stringType) && parameters.length >= 3) { firstTestPosition = 1; secondTestPosition = 2; message = args[0]; } else { firstTestPosition = 0; secondTestPosition = 1; message = null; } final PsiExpression firstTestArg = args[firstTestPosition]; final PsiExpression secondTestArg = args[secondTestPosition]; final String literalValue; final String compareValue; if (isSimpleLiteral(firstTestArg)) { literalValue = firstTestArg.getText(); compareValue = secondTestArg.getText(); } else { literalValue = secondTestArg.getText(); compareValue = firstTestArg.getText(); } final String uppercaseLiteralValue = Character.toUpperCase(literalValue.charAt(0)) + literalValue.substring(1); @NonNls final StringBuilder newExpression = new StringBuilder(); final PsiMethod containingMethod = PsiTreeUtil.getParentOfType( callExpression, PsiMethod.class); if (containingMethod != null && AnnotationUtil.isAnnotated( containingMethod, "org.junit.Test", true)) { newExpression.append("org.junit.Assert."); } newExpression.append("assert"); newExpression.append(uppercaseLiteralValue); newExpression.append('('); if (message != null) { newExpression.append(message.getText()); newExpression.append(','); } newExpression.append(compareValue); newExpression.append(')'); replaceExpressionAndShorten(callExpression, newExpression.toString()); } private static boolean isFloatingPoint(PsiExpression expression) { final PsiType type = expression.getType(); return PsiType.FLOAT.equals(type) || PsiType.DOUBLE.equals(type); } } public BaseInspectionVisitor buildVisitor() { return new SimplifiableJUnitAssertionVisitor(); } private static class SimplifiableJUnitAssertionVisitor extends BaseInspectionVisitor { public void visitMethodCallExpression( @NotNull PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); if (isAssertTrueThatCouldBeAssertSame(expression)) { registerMethodCallError(expression); return; } if (isAssertTrueThatCouldBeAssertEquality(expression)) { registerMethodCallError(expression); } else if (isAssertEqualsThatCouldBeAssertLiteral(expression)) { registerMethodCallError(expression); } else if (isAssertTrueThatCouldBeFail(expression)) { registerMethodCallError(expression); } else if (isAssertFalseThatCouldBeFail(expression)) { registerMethodCallError(expression); } } } static boolean isAssertTrueThatCouldBeAssertEquality( PsiMethodCallExpression expression) { if (!isAssertTrue(expression)) { return false; } final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length < 1) { return false; } final PsiManager psiManager = expression.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final int testPosition; if (paramType1.equals(stringType) && parameters.length > 1) { testPosition = 1; } else { testPosition = 0; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final PsiExpression testArg = args[testPosition]; return testArg != null && isEqualityComparison(testArg); } static boolean isAssertTrueThatCouldBeAssertSame( PsiMethodCallExpression expression) { if (!isAssertTrue(expression)) { return false; } final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length < 1) { return false; } final PsiManager psiManager = expression.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final int testPosition; if (paramType1.equals(stringType) && parameters.length > 1) { testPosition = 1; } else { testPosition = 0; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final PsiExpression testArg = args[testPosition]; return testArg != null && isIdentityComparison(testArg); } static boolean isAssertTrueThatCouldBeFail( PsiMethodCallExpression expression) { if (!isAssertTrue(expression)) { return false; } final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length < 1) { return false; } final PsiManager psiManager = expression.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final int testPosition; if (paramType1.equals(stringType) && parameters.length > 1) { testPosition = 1; } else { testPosition = 0; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final PsiExpression testArg = args[testPosition]; return testArg != null && PsiKeyword.FALSE.equals(testArg.getText()); } static boolean isAssertFalseThatCouldBeFail( PsiMethodCallExpression expression) { if (!isAssertFalse(expression)) { return false; } final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length < 1) { return false; } final PsiManager psiManager = expression.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final int testPosition; if (paramType1.equals(stringType) && parameters.length > 1) { testPosition = 1; } else { testPosition = 0; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final PsiExpression testArg = args[testPosition]; return testArg != null && PsiKeyword.TRUE.equals(testArg.getText()); } static boolean isAssertEqualsThatCouldBeAssertLiteral( PsiMethodCallExpression expression) { if (!isAssertEquals(expression)) { return false; } final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length < 2) { return false; } final PsiManager psiManager = expression.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiType stringType = PsiType.getJavaLangString(psiManager, scope); final PsiType paramType1 = parameters[0].getType(); final int firstTestPosition; final int secondTestPosition; if (paramType1.equals(stringType) && parameters.length > 2) { firstTestPosition = 1; secondTestPosition = 2; } else { firstTestPosition = 0; secondTestPosition = 1; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] args = argumentList.getExpressions(); final PsiExpression firstTestArg = args[firstTestPosition]; final PsiExpression secondTestArg = args[secondTestPosition]; if (firstTestArg == null) { return false; } return secondTestArg != null && (isSimpleLiteral(firstTestArg) || isSimpleLiteral(secondTestArg)); } static boolean isSimpleLiteral(PsiExpression arg) { if (!(arg instanceof PsiLiteralExpression)) { return false; } final String text = arg.getText(); return PsiKeyword.NULL.equals(text) || PsiKeyword.TRUE.equals(text) || PsiKeyword.FALSE.equals(text); } private static boolean isEqualityComparison(PsiExpression testArg) { if (testArg instanceof PsiBinaryExpression) { final PsiJavaToken sign = ((PsiBinaryExpression)testArg).getOperationSign(); final IElementType tokenType = sign.getTokenType(); if (!tokenType.equals(JavaTokenType.EQEQ)) { return false; } final PsiExpression lhs = ((PsiBinaryExpression)testArg).getLOperand(); final PsiExpression rhs = ((PsiBinaryExpression)testArg).getROperand(); if (rhs == null) { return false; } final PsiType type = lhs.getType(); return type != null && ClassUtils.isPrimitive(type); } else if (testArg instanceof PsiMethodCallExpression) { final PsiMethodCallExpression call = (PsiMethodCallExpression)testArg; if (!MethodCallUtils.isEqualsCall(call)) { return false; } final PsiReferenceExpression methodExpression = call.getMethodExpression(); return methodExpression.getQualifierExpression() != null; } return false; } private static boolean isIdentityComparison(PsiExpression testArg) { if (testArg instanceof PsiBinaryExpression) { final PsiBinaryExpression expression = (PsiBinaryExpression)testArg; final IElementType tokenType = expression.getOperationTokenType(); if (!tokenType.equals(JavaTokenType.EQEQ)) { return false; } final PsiExpression rhs = expression.getROperand(); return rhs != null; } return false; } private static boolean isAssertTrue(PsiMethodCallExpression expression) { final PsiReferenceExpression methodExpression = expression.getMethodExpression(); @NonNls final String methodName = methodExpression.getReferenceName(); if (!"assertTrue".equals(methodName)) { return false; } final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiClass targetClass = method.getContainingClass(); if (targetClass == null) { return false; } return ClassUtils.isSubclass(targetClass, "junit.framework.Assert") || ClassUtils.isSubclass(targetClass, "org.junit.Assert"); } private static boolean isAssertFalse(PsiMethodCallExpression expression) { final PsiReferenceExpression methodExpression = expression.getMethodExpression(); @NonNls final String methodName = methodExpression.getReferenceName(); if (!"assertFalse".equals(methodName)) { return false; } final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiClass targetClass = method.getContainingClass(); if (targetClass == null) { return false; } return ClassUtils.isSubclass(targetClass, "junit.framework.Assert") || ClassUtils.isSubclass(targetClass, "org.junit.Assert"); } private static boolean isAssertEquals(PsiMethodCallExpression expression) { final PsiReferenceExpression methodExpression = expression.getMethodExpression(); @NonNls final String methodName = methodExpression.getReferenceName(); if (!"assertEquals".equals(methodName)) { return false; } final PsiMethod method = (PsiMethod)methodExpression.resolve(); if (method == null) { return false; } final PsiClass targetClass = method.getContainingClass(); if (targetClass == null) { return false; } return ClassUtils.isSubclass(targetClass, "junit.framework.Assert") || ClassUtils.isSubclass(targetClass, "org.junit.Assert"); } }
cleanup
plugins/InspectionGadgets/src/com/siyeh/ig/junit/SimplifiableJUnitAssertionInspection.java
cleanup
Java
apache-2.0
5a2ed8f10403c1b6a2af0dfd9ac5e3a35a5fcd5b
0
visp-streaming/topologyParser
package ac.at.tuwien.infosys.visp.topologyParser.antlr.listener; import ac.at.tuwien.infosys.visp.common.operators.Operator; import ac.at.tuwien.infosys.visp.common.operators.ProcessingOperator; import ac.at.tuwien.infosys.visp.common.operators.Sink; import ac.at.tuwien.infosys.visp.common.operators.Split; import ac.at.tuwien.infosys.visp.common.operators.Join; import ac.at.tuwien.infosys.visp.common.operators.Source; import ac.at.tuwien.infosys.visp.topologyParser.antlr.VispBaseListener; import ac.at.tuwien.infosys.visp.topologyParser.antlr.VispParser; import org.antlr.v4.runtime.tree.TerminalNode; import org.apache.log4j.Logger; import java.io.*; import java.util.*; public class TopologyListener extends VispBaseListener { public VispParser parser; public List<String> linesToWriteToGraphViz; public List<String> linesToWriteToFlux; private static final Logger LOG = Logger.getLogger(TopologyListener.class); public String currentNodeName = ""; public Operator newOperator; private Map<String, Operator> topology = new LinkedHashMap<>(); // the following fields MUST be set, otherwise the input is not accepted: public boolean typeIsSet, allowedLocationsIsSet, statefulIsSet, concreteLocationIsSet, pathOrderIsSet; public TopologyListener(VispParser parser) { this.parser = parser; linesToWriteToGraphViz = new ArrayList<String>(); linesToWriteToGraphViz.add("\ndigraph {\n"); linesToWriteToFlux = new ArrayList<String>(); } public Map<String, Operator> getTopology() { return topology; } public void writeGraphvizFile(String filename) throws IOException { LOG.info("in writeGraphvizFile for filename " + filename); linesToWriteToGraphViz.add("\n}"); try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(filename), "utf-8"))) { for (String s : linesToWriteToGraphViz) { writer.write("\t" + s); } } } public void writeFluxFile(String filename) throws IOException { LOG.info("in writeFluxFile for filename " + filename); linesToWriteToFlux.add("name: \"visp-topology\"\nconfig:\n\ttopology.workers: 1\n\n"); linesToWriteToFlux.add("# spout definitions\n"); linesToWriteToFlux.add("spouts:\n"); for (String operatorId : topology.keySet()) { if (topology.get(operatorId) instanceof Source) { printOperatorFlux(operatorId, linesToWriteToFlux); } } linesToWriteToFlux.add("\n# bolt definitions\n"); linesToWriteToFlux.add("bolts:\n"); for (String operatorId : topology.keySet()) { if (topology.get(operatorId) instanceof ProcessingOperator || topology.get(operatorId) instanceof Sink) { printOperatorFlux(operatorId, linesToWriteToFlux); } } linesToWriteToFlux.add("\n# stream definitions\n"); linesToWriteToFlux.add("streams:\n"); for (String operatorId : topology.keySet()) { if (topology.get(operatorId) instanceof ProcessingOperator || topology.get(operatorId) instanceof Sink) { printStreamFlux(operatorId, linesToWriteToFlux); } } try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(filename), "utf-8"))) { for (String s : linesToWriteToFlux) { writer.write(s); } } } private void printOperatorFlux(String operatorId, List<String> linesToWriteToFlux) { linesToWriteToFlux.add(" - id: \"" + operatorId + "\"\n"); linesToWriteToFlux.add(" className: \"" + topology.get(operatorId).getType() + "\"\n"); linesToWriteToFlux.add(" parallelism: 1\n"); } private void printStreamFlux(String operatorId, List<String> linesToWriteToFlux) { Operator op = topology.get(operatorId); for(Operator source : op.getSources()) { if(source == null) { LOG.warn("Source of operator " + op.getName() + " is null..."); continue; } if(source instanceof Join) { // skip Join and treat its sources as sources for current operator for(Operator grandSource : source.getSources()) { helpPrintStreamFlux(grandSource, op, linesToWriteToFlux); } } else if(source instanceof Split) { // skip Split and treat its sources as sources for current operator for(Operator grandSource : source.getSources()) { helpPrintStreamFlux(grandSource, op, linesToWriteToFlux); } } else { helpPrintStreamFlux(source, op, linesToWriteToFlux); } } } private void helpPrintStreamFlux(Operator source, Operator op, List<String> linesToWriteToFlux) { linesToWriteToFlux.add(" - name: \"" + source.getName() + " --> " + op.getName() + "\"\n"); linesToWriteToFlux.add(" from: \"" + source.getName() + "\"\n"); linesToWriteToFlux.add(" to: \"" + op.getName() + "\"\n"); linesToWriteToFlux.add(" grouping:\n"); linesToWriteToFlux.add(" type: SHUFFLE\n"); // TODO } @Override public void enterConfigfile(VispParser.ConfigfileContext ctx) { // this method is called when the parser begins reading the config file } @Override public void enterNodeBlock(VispParser.NodeBlockContext ctx) { // this method is called in the beginning of each node block typeIsSet = false; allowedLocationsIsSet = false; statefulIsSet = false; concreteLocationIsSet = false; } @Override public void exitNodeBlock(VispParser.NodeBlockContext ctx) { // this method is called when the parsing of a certain node is completed // now it is time to create the corresponding object and // add it to the topology if (newOperator instanceof Join) { finishOperatorCreation(); return; } if (newOperator instanceof Split) { if (!pathOrderIsSet) { throw new RuntimeException("Path order not set for split operator " + currentNodeName); } else { finishOperatorCreation(); return; } } if (newOperator instanceof ProcessingOperator) { if (!typeIsSet) { throw new RuntimeException("Type not set for operator " + currentNodeName); } if (newOperator.getSourcesText().size() == 0) { throw new RuntimeException("No sources set for operator " + currentNodeName); } if (!allowedLocationsIsSet) { throw new RuntimeException("Allowed locations not set for operator " + currentNodeName); } if (!statefulIsSet) { throw new RuntimeException("Stateful not set for operator " + currentNodeName); } } else { if (typeIsSet) { // all required fields are there if (newOperator instanceof Sink) { if (newOperator.getSourcesText().size() == 0) { throw new RuntimeException("No sources set for sink " + currentNodeName); } } } else { throw new RuntimeException("Type missing for node " + currentNodeName); } } if (!concreteLocationIsSet) { // concrete location was not explicitly set if (newOperator instanceof Source || newOperator instanceof Sink) { throw new RuntimeException("No concreteLocation set for source/sink " + currentNodeName); } // pick one randomly from allowed ones Operator.Location locationToClone = newOperator.getAllowedLocationsList().get( new Random().nextInt(newOperator.getAllowedLocationsList().size())); Operator.Location newLocation = new Operator.Location(locationToClone.getIpAddress(), locationToClone.getResourcePool()); newOperator.setConcreteLocation(newLocation); LOG.info("concrete location was not specified - " + "picked concrete location to be " + newOperator.getConcreteLocation().getIpAddress() + "/" + newOperator.getConcreteLocation().getResourcePool()); } finishOperatorCreation(); } private void finishOperatorCreation() { newOperator.setName(currentNodeName); topology.put(currentNodeName, newOperator); String color = ""; if (newOperator instanceof Source) { color = "beige"; } else if (newOperator instanceof ProcessingOperator) { color = "skyblue"; } else { color = "springgreen"; } String toWrite = "\"" + currentNodeName + "\" [style=filled, fontname=\"helvetica\", shape=box, fillcolor=" + color + ", label=<" + currentNodeName + "<BR />\n" + "\t<FONT POINT-SIZE=\"10\">" + newOperator.getConcreteLocation() + (newOperator.getSize() != null ? "<BR />\nSize: " + newOperator.getSize().toString().toLowerCase() : "") + "</FONT>>" + "]"; this.linesToWriteToGraphViz.add("\t" + toWrite + "\n"); } @Override public void enterNewNodeId(VispParser.NewNodeIdContext ctx) { LOG.debug("define a new node with the id " + ctx.getText()); currentNodeName = ctx.getText().substring(1); // remove the dollar sign } @Override public void enterSourceNode(VispParser.SourceNodeContext ctx) { LOG.debug("add node " + ctx.getText() + " as a source for node " + currentNodeName); newOperator.getSourcesText().add(ctx.getText().substring(1)); // remove dollar sign linesToWriteToGraphViz.add("\"" + ctx.getText().substring(1) + "\" -> \"" + currentNodeName + "\"\n"); } @Override public void enterAllowedLocationsStmt(VispParser.AllowedLocationsStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("allowedLocations statement has no effect for operator type Source/Sink"); return; } List<Operator.Location> allowedLocations = new ArrayList<>(); allowedLocationsIsSet = true; for (TerminalNode location : ctx.LOCATION()) { Operator.Location operatorLocation = new Operator.Location(getIpAddress(location.getText()), getResourcePool(location.getText())); allowedLocations.add(operatorLocation); } newOperator.setAllowedLocationsList(allowedLocations); LOG.info("Setting allowed locations to : " + allowedLocations); } private String getResourcePool(String text) { String[] splitted = text.split("/"); return splitted[1]; } private String getIpAddress(String text) { String[] splitted = text.split("/"); return splitted[0]; } @Override public void enterInputFormatStmt(VispParser.InputFormatStmtContext ctx) { List<String> inputFormats = new ArrayList<>(); for (TerminalNode n : ctx.STRING()) { inputFormats.add(stringRemoveQuotes(n.getText())); } newOperator.setInputFormat(inputFormats); } @Override public void enterStatefulStmt(VispParser.StatefulStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("stateful statement has no effect for operator type Source/Sink"); return; } statefulIsSet = true; newOperator.setStateful(ctx.BOOLEAN().getText().toLowerCase().equals("true")); } @Override public void enterTypeStmt(VispParser.TypeStmtContext ctx) { typeIsSet = true; newOperator.setType(stringRemoveQuotes(ctx.STRING().getText())); } @Override public void enterPathOrderStmt(VispParser.PathOrderStmtContext ctx) { if (newOperator instanceof Split) { pathOrderIsSet = true; List<String> pathOrder = new ArrayList<>(); for (TerminalNode t : ctx.ID()) { pathOrder.add(t.toString().substring(1)); // remove dollar sign } ((Split) newOperator).setPathOrder(pathOrder); } else { LOG.warn("Ignoring pathOrder statement for operator " + currentNodeName + " (not applicable for operator type)"); } } @Override public void enterOutputFormatStmt(VispParser.OutputFormatStmtContext ctx) { if (newOperator instanceof Sink) { LOG.warn("output format statement has no effect for operator type Sink"); return; } newOperator.setOutputFormat(stringRemoveQuotes(ctx.STRING().getText())); } private String stringRemoveQuotes(String input) { if (input.charAt(0) == '"' && input.charAt(input.length() - 1) == '"') { return input.substring(1, input.length() - 1); } else { return input; } } @Override public void enterNodeType(VispParser.NodeTypeContext ctx) { LOG.debug("Node " + currentNodeName + " has nodeType " + ctx.getText()); switch (ctx.getText()) { case "Source": newOperator = new Source(); break; case "Operator": newOperator = new ProcessingOperator(); break; case "Sink": newOperator = new Sink(); break; case "Split": newOperator = new Split(); break; case "Join": newOperator = new Join(); break; default: throw new RuntimeException("Invalid node type: " + ctx.getText()); } initOperator(); } @Override public void enterConcreteLocationStmt(VispParser.ConcreteLocationStmtContext ctx) { concreteLocationIsSet = true; newOperator.setConcreteLocation(new Operator.Location(getIpAddress(ctx.LOCATION().getText()), getResourcePool(ctx.LOCATION().getText()))); // TODO: add check whether concrete concreteLocation is in allowed locations } @Override public void enterSizeStmt(VispParser.SizeStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("size statement has no effect for operator type Source/Sink"); return; } String sizeString = ctx.sizeType().getText(); switch (sizeString) { case "small": newOperator.setSize(Operator.Size.SMALL); break; case "medium": newOperator.setSize(Operator.Size.MEDIUM); break; case "large": newOperator.setSize(Operator.Size.LARGE); break; case "unknown": newOperator.setSize(Operator.Size.UNKNOWN); break; default: throw new RuntimeException("Unknown operator size: " + sizeString); } } @Override public void enterExpectedDurationStmt(VispParser.ExpectedDurationStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("expectedDuration statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setExpectedDuration(Double.parseDouble(ctx.NUMBER().getText())); } catch (Exception e) { LOG.error("Could not set optional attribute expected duration"); } } @Override public void enterScalingCPUThresholdStmt(VispParser.ScalingCPUThresholdStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("scalingCPUThreshold statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setScalingCPUThreshold(Double.parseDouble(ctx.NUMBER().getText())); } catch (Exception e) { LOG.error("Could not set optional attribute scalingCPUThreshold"); } } @Override public void enterScalingMemoryThresholdStmt(VispParser.ScalingMemoryThresholdStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("scalingMemoryThreshold statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setScalingMemoryThreshold(Double.parseDouble(ctx.NUMBER().getText())); } catch (Exception e) { LOG.error("Could not set optional attribute scalingMemoryThreshold"); } } @Override public void enterQueueThreshold(VispParser.QueueThresholdContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("queueThreshold statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setQueueThreshold(Double.parseDouble(ctx.NUMBER().getText())); } catch (Exception e) { LOG.error("Could not set optional attribute queueThreshold"); } } @Override public void enterPinnedStmt(VispParser.PinnedStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("pinned statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setPinned(ctx.BOOLEAN().getText().toLowerCase().equals("true")); } catch (Exception e) { LOG.error("Could not set optional attribute pinned"); } } @Override public void enterReplicationAllowedStmt(VispParser.ReplicationAllowedStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("replicationAllowed statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setReplicationAllowed(ctx.BOOLEAN().getText().toLowerCase().equals("true")); } catch (Exception e) { LOG.error("Could not set optional attribute replicationAllowed"); } } @Override public void enterCompensationStmt(VispParser.CompensationStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("compensation statement has no effect for operator type Source/Sink"); return; } String compensationValue = stringRemoveQuotes(ctx.STRING().getText()); String[] allowedValues = {"redeploysingle", "redeploytopology", "mailto", "deploy"}; boolean usesValidValue = false; for (String s : allowedValues) { if (compensationValue.toLowerCase().contains(s)) { usesValidValue = true; } } if (!usesValidValue) { throw new RuntimeException("Unsupported value for compensation: '" + compensationValue + "'; Use one of: {redeploySingle, redeployTopology, mailto:<email>, deploy:<url>}"); } ((ProcessingOperator) newOperator).setCompensation(compensationValue); } @Override public void exitConfigfile(VispParser.ConfigfileContext ctx) { for (String name : topology.keySet()) { for (String source : topology.get(name).getSourcesText()) { try { topology.get(name).getSources().add(topology.get(source)); } catch (Exception e) { LOG.warn("Could not set source '" + source + "' for node '" + currentNodeName + "'"); } } } checkIsEachNonSinkIsUsedAsSource(); checkIfPathOrderContainsAllPaths(); } private void checkIsEachNonSinkIsUsedAsSource() { for (Operator o : topology.values()) { if (o instanceof Sink) { continue; } boolean foundAsSource = false; for (Operator potentialSourceDonor : topology.values()) { if (potentialSourceDonor.getSources().contains(o)) { foundAsSource = true; } } if (!foundAsSource) { LOG.warn("Non-sink node " + o.getName() + " is used nowhere as a source"); } } } private void checkIfPathOrderContainsAllPaths() { for (String operatorId : topology.keySet()) { Operator op = topology.get(operatorId); if (!(op instanceof Split)) { continue; } List<String> pathOrder = ((Split) op).getPathOrder(); List<String> allOutgoingPaths = getAllOutgoingPaths(operatorId); for (String path : allOutgoingPaths) { if (!pathOrder.contains(path)) { throw new RuntimeException("Operator " + operatorId + "'s pathOrder does not contain path " + path); } } } } private List<String> getAllOutgoingPaths(String splitOperatorId) { List<String> outgoingPaths = new ArrayList<>(); for (String operatorId : topology.keySet()) { Operator op = topology.get(operatorId); for (Operator out : op.getSources()) { if (out.getName().equals(splitOperatorId)) { outgoingPaths.add(op.getName()); } } } return outgoingPaths; } private void initOperator() { newOperator.setSourcesText(new ArrayList<>()); newOperator.setAllowedLocationsList(new ArrayList<>()); if (newOperator instanceof ProcessingOperator) { newOperator.setSize(Operator.Size.UNKNOWN); // default ((ProcessingOperator) newOperator).setPinned(false); ((ProcessingOperator) newOperator).setReplicationAllowed(true); ((ProcessingOperator) newOperator).setQueueThreshold(0.0); ((ProcessingOperator) newOperator).setScalingCPUThreshold(0.0); ((ProcessingOperator) newOperator).setScalingMemoryThreshold(0.0); ((ProcessingOperator) newOperator).setExpectedDuration(0.0); ((ProcessingOperator) newOperator).setCompensation("redeploySingle"); } } }
src/main/java/ac/at/tuwien/infosys/visp/topologyParser/antlr/listener/TopologyListener.java
package ac.at.tuwien.infosys.visp.topologyParser.antlr.listener; import ac.at.tuwien.infosys.visp.common.operators.Operator; import ac.at.tuwien.infosys.visp.common.operators.ProcessingOperator; import ac.at.tuwien.infosys.visp.common.operators.Sink; import ac.at.tuwien.infosys.visp.common.operators.Split; import ac.at.tuwien.infosys.visp.common.operators.Join; import ac.at.tuwien.infosys.visp.common.operators.Source; import ac.at.tuwien.infosys.visp.topologyParser.antlr.VispBaseListener; import ac.at.tuwien.infosys.visp.topologyParser.antlr.VispParser; import org.antlr.v4.runtime.tree.TerminalNode; import org.apache.log4j.Logger; import java.io.*; import java.util.*; public class TopologyListener extends VispBaseListener { public VispParser parser; public List<String> linesToWriteToGraphViz; public List<String> linesToWriteToFlux; private static final Logger LOG = Logger.getLogger(TopologyListener.class); public String currentNodeName = ""; public Operator newOperator; private Map<String, Operator> topology = new LinkedHashMap<>(); // the following fields MUST be set, otherwise the input is not accepted: public boolean typeIsSet, allowedLocationsIsSet, statefulIsSet, concreteLocationIsSet, pathOrderIsSet; public TopologyListener(VispParser parser) { this.parser = parser; linesToWriteToGraphViz = new ArrayList<String>(); linesToWriteToGraphViz.add("\ndigraph {\n"); linesToWriteToFlux = new ArrayList<String>(); } public Map<String, Operator> getTopology() { return topology; } public void writeGraphvizFile(String filename) throws IOException { LOG.info("in writeGraphvizFile for filename " + filename); linesToWriteToGraphViz.add("\n}"); try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(filename), "utf-8"))) { for (String s : linesToWriteToGraphViz) { writer.write("\t" + s); } } } public void writeFluxFile(String filename) throws IOException { LOG.info("in writeFluxFile for filename " + filename); linesToWriteToFlux.add("name: \"visp-topology\"\nconfig:\n\ttopology.workers: 1\n\n"); linesToWriteToFlux.add("# spout definitions\n"); linesToWriteToFlux.add("spouts:\n"); for (String operatorId : topology.keySet()) { if (topology.get(operatorId) instanceof Source) { printOperatorFlux(operatorId, linesToWriteToFlux); } } linesToWriteToFlux.add("\n# bolt definitions\n"); linesToWriteToFlux.add("bolts:\n"); for (String operatorId : topology.keySet()) { if (topology.get(operatorId) instanceof ProcessingOperator || topology.get(operatorId) instanceof Sink) { printOperatorFlux(operatorId, linesToWriteToFlux); } } linesToWriteToFlux.add("\n# stream definitions\n"); linesToWriteToFlux.add("streams:\n"); for (String operatorId : topology.keySet()) { if (topology.get(operatorId) instanceof ProcessingOperator || topology.get(operatorId) instanceof Sink) { printStreamFlux(operatorId, linesToWriteToFlux); } } try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(filename), "utf-8"))) { for (String s : linesToWriteToFlux) { writer.write(s); } } } private void printOperatorFlux(String operatorId, List<String> linesToWriteToFlux) { linesToWriteToFlux.add(" - id: \"" + operatorId + "\"\n"); linesToWriteToFlux.add(" className: \"" + topology.get(operatorId).getType() + "\"\n"); linesToWriteToFlux.add(" parallelism: 1\n"); } private void printStreamFlux(String operatorId, List<String> linesToWriteToFlux) { Operator op = topology.get(operatorId); for(Operator source : op.getSources()) { if(source == null) { LOG.warn("Source of operator " + op.getName() + " is null..."); continue; } linesToWriteToFlux.add(" - name: \"" + source.getName() + " --> " + op.getName() + "\"\n"); linesToWriteToFlux.add(" from: \"" + source.getName() + "\"\n"); linesToWriteToFlux.add(" to: \"" + op.getName() + "\"\n"); linesToWriteToFlux.add(" grouping:\n"); linesToWriteToFlux.add(" type: SHUFFLE\n"); // TODO } } @Override public void enterConfigfile(VispParser.ConfigfileContext ctx) { // this method is called when the parser begins reading the config file } @Override public void enterNodeBlock(VispParser.NodeBlockContext ctx) { // this method is called in the beginning of each node block typeIsSet = false; allowedLocationsIsSet = false; statefulIsSet = false; concreteLocationIsSet = false; } @Override public void exitNodeBlock(VispParser.NodeBlockContext ctx) { // this method is called when the parsing of a certain node is completed // now it is time to create the corresponding object and // add it to the topology if (newOperator instanceof Join) { finishOperatorCreation(); return; } if (newOperator instanceof Split) { if (!pathOrderIsSet) { throw new RuntimeException("Path order not set for split operator " + currentNodeName); } else { finishOperatorCreation(); return; } } if (newOperator instanceof ProcessingOperator) { if (!typeIsSet) { throw new RuntimeException("Type not set for operator " + currentNodeName); } if (newOperator.getSourcesText().size() == 0) { throw new RuntimeException("No sources set for operator " + currentNodeName); } if (!allowedLocationsIsSet) { throw new RuntimeException("Allowed locations not set for operator " + currentNodeName); } if (!statefulIsSet) { throw new RuntimeException("Stateful not set for operator " + currentNodeName); } } else { if (typeIsSet) { // all required fields are there if (newOperator instanceof Sink) { if (newOperator.getSourcesText().size() == 0) { throw new RuntimeException("No sources set for sink " + currentNodeName); } } } else { throw new RuntimeException("Type missing for node " + currentNodeName); } } if (!concreteLocationIsSet) { // concrete location was not explicitly set if (newOperator instanceof Source || newOperator instanceof Sink) { throw new RuntimeException("No concreteLocation set for source/sink " + currentNodeName); } // pick one randomly from allowed ones Operator.Location locationToClone = newOperator.getAllowedLocationsList().get( new Random().nextInt(newOperator.getAllowedLocationsList().size())); Operator.Location newLocation = new Operator.Location(locationToClone.getIpAddress(), locationToClone.getResourcePool()); newOperator.setConcreteLocation(newLocation); LOG.info("concrete location was not specified - " + "picked concrete location to be " + newOperator.getConcreteLocation().getIpAddress() + "/" + newOperator.getConcreteLocation().getResourcePool()); } finishOperatorCreation(); } private void finishOperatorCreation() { newOperator.setName(currentNodeName); topology.put(currentNodeName, newOperator); String color = ""; if (newOperator instanceof Source) { color = "beige"; } else if (newOperator instanceof ProcessingOperator) { color = "skyblue"; } else { color = "springgreen"; } String toWrite = "\"" + currentNodeName + "\" [style=filled, fontname=\"helvetica\", shape=box, fillcolor=" + color + ", label=<" + currentNodeName + "<BR />\n" + "\t<FONT POINT-SIZE=\"10\">" + newOperator.getConcreteLocation() + (newOperator.getSize() != null ? "<BR />\nSize: " + newOperator.getSize().toString().toLowerCase() : "") + "</FONT>>" + "]"; this.linesToWriteToGraphViz.add("\t" + toWrite + "\n"); } @Override public void enterNewNodeId(VispParser.NewNodeIdContext ctx) { LOG.debug("define a new node with the id " + ctx.getText()); currentNodeName = ctx.getText().substring(1); // remove the dollar sign } @Override public void enterSourceNode(VispParser.SourceNodeContext ctx) { LOG.debug("add node " + ctx.getText() + " as a source for node " + currentNodeName); newOperator.getSourcesText().add(ctx.getText().substring(1)); // remove dollar sign linesToWriteToGraphViz.add("\"" + ctx.getText().substring(1) + "\" -> \"" + currentNodeName + "\"\n"); } @Override public void enterAllowedLocationsStmt(VispParser.AllowedLocationsStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("allowedLocations statement has no effect for operator type Source/Sink"); return; } List<Operator.Location> allowedLocations = new ArrayList<>(); allowedLocationsIsSet = true; for (TerminalNode location : ctx.LOCATION()) { Operator.Location operatorLocation = new Operator.Location(getIpAddress(location.getText()), getResourcePool(location.getText())); allowedLocations.add(operatorLocation); } newOperator.setAllowedLocationsList(allowedLocations); LOG.info("Setting allowed locations to : " + allowedLocations); } private String getResourcePool(String text) { String[] splitted = text.split("/"); return splitted[1]; } private String getIpAddress(String text) { String[] splitted = text.split("/"); return splitted[0]; } @Override public void enterInputFormatStmt(VispParser.InputFormatStmtContext ctx) { List<String> inputFormats = new ArrayList<>(); for (TerminalNode n : ctx.STRING()) { inputFormats.add(stringRemoveQuotes(n.getText())); } newOperator.setInputFormat(inputFormats); } @Override public void enterStatefulStmt(VispParser.StatefulStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("stateful statement has no effect for operator type Source/Sink"); return; } statefulIsSet = true; newOperator.setStateful(ctx.BOOLEAN().getText().toLowerCase().equals("true")); } @Override public void enterTypeStmt(VispParser.TypeStmtContext ctx) { typeIsSet = true; newOperator.setType(stringRemoveQuotes(ctx.STRING().getText())); } @Override public void enterPathOrderStmt(VispParser.PathOrderStmtContext ctx) { if (newOperator instanceof Split) { pathOrderIsSet = true; List<String> pathOrder = new ArrayList<>(); for (TerminalNode t : ctx.ID()) { pathOrder.add(t.toString().substring(1)); // remove dollar sign } ((Split) newOperator).setPathOrder(pathOrder); } else { LOG.warn("Ignoring pathOrder statement for operator " + currentNodeName + " (not applicable for operator type)"); } } @Override public void enterOutputFormatStmt(VispParser.OutputFormatStmtContext ctx) { if (newOperator instanceof Sink) { LOG.warn("output format statement has no effect for operator type Sink"); return; } newOperator.setOutputFormat(stringRemoveQuotes(ctx.STRING().getText())); } private String stringRemoveQuotes(String input) { if (input.charAt(0) == '"' && input.charAt(input.length() - 1) == '"') { return input.substring(1, input.length() - 1); } else { return input; } } @Override public void enterNodeType(VispParser.NodeTypeContext ctx) { LOG.debug("Node " + currentNodeName + " has nodeType " + ctx.getText()); switch (ctx.getText()) { case "Source": newOperator = new Source(); break; case "Operator": newOperator = new ProcessingOperator(); break; case "Sink": newOperator = new Sink(); break; case "Split": newOperator = new Split(); break; case "Join": newOperator = new Join(); break; default: throw new RuntimeException("Invalid node type: " + ctx.getText()); } initOperator(); } @Override public void enterConcreteLocationStmt(VispParser.ConcreteLocationStmtContext ctx) { concreteLocationIsSet = true; newOperator.setConcreteLocation(new Operator.Location(getIpAddress(ctx.LOCATION().getText()), getResourcePool(ctx.LOCATION().getText()))); // TODO: add check whether concrete concreteLocation is in allowed locations } @Override public void enterSizeStmt(VispParser.SizeStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("size statement has no effect for operator type Source/Sink"); return; } String sizeString = ctx.sizeType().getText(); switch (sizeString) { case "small": newOperator.setSize(Operator.Size.SMALL); break; case "medium": newOperator.setSize(Operator.Size.MEDIUM); break; case "large": newOperator.setSize(Operator.Size.LARGE); break; case "unknown": newOperator.setSize(Operator.Size.UNKNOWN); break; default: throw new RuntimeException("Unknown operator size: " + sizeString); } } @Override public void enterExpectedDurationStmt(VispParser.ExpectedDurationStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("expectedDuration statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setExpectedDuration(Double.parseDouble(ctx.NUMBER().getText())); } catch (Exception e) { LOG.error("Could not set optional attribute expected duration"); } } @Override public void enterScalingCPUThresholdStmt(VispParser.ScalingCPUThresholdStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("scalingCPUThreshold statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setScalingCPUThreshold(Double.parseDouble(ctx.NUMBER().getText())); } catch (Exception e) { LOG.error("Could not set optional attribute scalingCPUThreshold"); } } @Override public void enterScalingMemoryThresholdStmt(VispParser.ScalingMemoryThresholdStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("scalingMemoryThreshold statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setScalingMemoryThreshold(Double.parseDouble(ctx.NUMBER().getText())); } catch (Exception e) { LOG.error("Could not set optional attribute scalingMemoryThreshold"); } } @Override public void enterQueueThreshold(VispParser.QueueThresholdContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("queueThreshold statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setQueueThreshold(Double.parseDouble(ctx.NUMBER().getText())); } catch (Exception e) { LOG.error("Could not set optional attribute queueThreshold"); } } @Override public void enterPinnedStmt(VispParser.PinnedStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("pinned statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setPinned(ctx.BOOLEAN().getText().toLowerCase().equals("true")); } catch (Exception e) { LOG.error("Could not set optional attribute pinned"); } } @Override public void enterReplicationAllowedStmt(VispParser.ReplicationAllowedStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("replicationAllowed statement has no effect for operator type Source/Sink"); return; } try { ((ProcessingOperator) newOperator).setReplicationAllowed(ctx.BOOLEAN().getText().toLowerCase().equals("true")); } catch (Exception e) { LOG.error("Could not set optional attribute replicationAllowed"); } } @Override public void enterCompensationStmt(VispParser.CompensationStmtContext ctx) { if (newOperator instanceof Source || newOperator instanceof Sink) { LOG.warn("compensation statement has no effect for operator type Source/Sink"); return; } String compensationValue = stringRemoveQuotes(ctx.STRING().getText()); String[] allowedValues = {"redeploysingle", "redeploytopology", "mailto", "deploy"}; boolean usesValidValue = false; for (String s : allowedValues) { if (compensationValue.toLowerCase().contains(s)) { usesValidValue = true; } } if (!usesValidValue) { throw new RuntimeException("Unsupported value for compensation: '" + compensationValue + "'; Use one of: {redeploySingle, redeployTopology, mailto:<email>, deploy:<url>}"); } ((ProcessingOperator) newOperator).setCompensation(compensationValue); } @Override public void exitConfigfile(VispParser.ConfigfileContext ctx) { for (String name : topology.keySet()) { for (String source : topology.get(name).getSourcesText()) { try { topology.get(name).getSources().add(topology.get(source)); } catch (Exception e) { LOG.warn("Could not set source '" + source + "' for node '" + currentNodeName + "'"); } } } checkIsEachNonSinkIsUsedAsSource(); checkIfPathOrderContainsAllPaths(); } private void checkIsEachNonSinkIsUsedAsSource() { for (Operator o : topology.values()) { if (o instanceof Sink) { continue; } boolean foundAsSource = false; for (Operator potentialSourceDonor : topology.values()) { if (potentialSourceDonor.getSources().contains(o)) { foundAsSource = true; } } if (!foundAsSource) { LOG.warn("Non-sink node " + o.getName() + " is used nowhere as a source"); } } } private void checkIfPathOrderContainsAllPaths() { for (String operatorId : topology.keySet()) { Operator op = topology.get(operatorId); if (!(op instanceof Split)) { continue; } List<String> pathOrder = ((Split) op).getPathOrder(); List<String> allOutgoingPaths = getAllOutgoingPaths(operatorId); for (String path : allOutgoingPaths) { if (!pathOrder.contains(path)) { throw new RuntimeException("Operator " + operatorId + "'s pathOrder does not contain path " + path); } } } } private List<String> getAllOutgoingPaths(String splitOperatorId) { List<String> outgoingPaths = new ArrayList<>(); for (String operatorId : topology.keySet()) { Operator op = topology.get(operatorId); for (Operator out : op.getSources()) { if (out.getName().equals(splitOperatorId)) { outgoingPaths.add(op.getName()); } } } return outgoingPaths; } private void initOperator() { newOperator.setSourcesText(new ArrayList<>()); newOperator.setAllowedLocationsList(new ArrayList<>()); if (newOperator instanceof ProcessingOperator) { newOperator.setSize(Operator.Size.UNKNOWN); // default ((ProcessingOperator) newOperator).setPinned(false); ((ProcessingOperator) newOperator).setReplicationAllowed(true); ((ProcessingOperator) newOperator).setQueueThreshold(0.0); ((ProcessingOperator) newOperator).setScalingCPUThreshold(0.0); ((ProcessingOperator) newOperator).setScalingMemoryThreshold(0.0); ((ProcessingOperator) newOperator).setExpectedDuration(0.0); ((ProcessingOperator) newOperator).setCompensation("redeploySingle"); } } }
split and join nodes are now treated correctly Since this concept is not known in FLUX, each connection to a split or a join node is transformed into a direct connection from the upstream to the downstream node
src/main/java/ac/at/tuwien/infosys/visp/topologyParser/antlr/listener/TopologyListener.java
split and join nodes are now treated correctly
Java
apache-2.0
6e8766d54c4d8be93c8616a68d567854bc81cdd4
0
Donnerbart/hazelcast-simulator,pveentjer/hazelcast-simulator,fengshao0907/hazelcast-simulator,Danny-Hazelcast/hazelcast-stabilizer,fengshao0907/hazelcast-simulator,jerrinot/hazelcast-stabilizer,eminn/hazelcast-simulator,hazelcast/hazelcast-simulator,hazelcast/hazelcast-simulator,hasancelik/hazelcast-stabilizer,Danny-Hazelcast/hazelcast-stabilizer,gAmUssA/hazelcast-simulator,hazelcast/hazelcast-simulator,pveentjer/hazelcast-simulator,hasancelik/hazelcast-stabilizer,gAmUssA/hazelcast-simulator,Donnerbart/hazelcast-simulator,jerrinot/hazelcast-stabilizer,eminn/hazelcast-simulator
/* * Copyright (c) 2008-2015, 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.simulator.utils; public interface AssertTask { void run() throws Exception; }
utils/src/main/java/com/hazelcast/simulator/utils/AssertTask.java
/* * Copyright (c) 2008-2015, 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.simulator.utils; public abstract class AssertTask { public abstract void run() throws Exception; }
Made AssertTask an interface.
utils/src/main/java/com/hazelcast/simulator/utils/AssertTask.java
Made AssertTask an interface.
Java
apache-2.0
a29918e0e83427fd598d1518d23933dd7e1ffb8a
0
iservport/helianto,iservport/helianto
/* Copyright 2005 I Serv Consultoria Empresarial Ltda. * * 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.helianto.core.domain; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Embedded; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OrderColumn; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import org.helianto.core.def.Appellation; import org.helianto.core.def.Gender; import org.helianto.core.def.IdentityType; import org.helianto.core.def.Notification; import org.joda.time.DateTime; import org.joda.time.Years; import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * An uniquely identified actor. * * @author Mauricio Fernandes de Castro */ @javax.persistence.Entity @Table(name="core_identity", uniqueConstraints = {@UniqueConstraint(columnNames={"principal"})} ) public class Identity implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Column(length=64) private String displayName = ""; @Column(length=20) private String optionalSourceAlias = ""; @Column(length=40) private String principal = ""; @JsonIgnore @Embedded private PersonalData personalData; @Temporal(TemporalType.TIMESTAMP) private Date created = new Date(); private char identityType = IdentityType.PERSONAL_EMAIL.getValue(); private char notification = Notification.AUTOMATIC.getValue(); @JsonIgnore @ElementCollection @CollectionTable(name = "core_identityPhone", joinColumns = @JoinColumn(name = "identityId")) @OrderColumn(name="sequence") private List<Phone> phones = new ArrayList<Phone>(); @JsonIgnore @ElementCollection @CollectionTable(name = "core_identityContact", joinColumns = @JoinColumn(name = "identityId")) @OrderColumn(name="sequence") private List<ContactInfo> contactInfos = new ArrayList<ContactInfo>(); @Transient private transient MultipartFile file; @Transient private String passwordToChange; @Transient private String passwordConfirmation; /** * Default constructor. */ public Identity() { super(); this.personalData = new PersonalData(); } /** * Principal constructor. * * @param principal */ public Identity(String principal) { this(principal, ""); } /** * Principal and optional alias constructor. * * @param principal * @param displayName */ public Identity(String principal, String displayName) { this(principal, displayName, new PersonalData()); } /** * Principal and optional alias constructor. * * @param principal * @param displayName * @param personalData */ public Identity(String principal, String displayName, PersonalData personalData) { setPrincipal(principal); setDisplayName(displayName); setPersonalData(personalData); } /** * Read constructor. * * @param id * @param userGroupId * @param identityType * @param principal * @param displayName * @param appellation * @param firstName * @param lastName * @param gender * @param notification * @param birthDate * @param imageUrl */ public Identity(Integer id, char identityType, String principal, String displayName, char appellation, String firstName, String lastName, char gender, char notification, Date birthDate, String imageUrl) { this(principal, displayName, new PersonalData(firstName, lastName, gender, appellation, birthDate, imageUrl)); this.id = id; this.identityType = identityType; this.notification = notification; } /** * Primary key. */ public int getId() { return this.id; } public void setId(int id) { this.id = id; } /** * Principal getter. */ public String getPrincipal() { return this.principal; } /** * Setting the principal also forces to lower case. * * @param principal */ public void setPrincipal(String principal) { if (principal!=null) { this.principal = principal.toLowerCase(); } else { this.principal = null; } } /** * <<Transient>> Principal name, i.e., substring of principal before '@', if any, * or the principal itself. */ public String getPrincipalName() { if (getPrincipal()!=null) { int position = getPrincipal().indexOf("@"); if (position>0) { return getPrincipal().substring(0, position); } return getPrincipal(); } return ""; } /** * <<Transient>> User principal domain, i.e., substring of principal after '@', if any, * or empty string. */ public String getPrincipalDomain() { if (getPrincipal()!=null) { int position = getPrincipal().indexOf("@"); if (position>0) { return getPrincipal().substring(position); } } return ""; } /** * Optional source alias. * * <p> * May be used to create an user in the future. * </p> */ public String getOptionalSourceAlias() { return optionalSourceAlias; } public void setOptionalSourceAlias(String optionalSourceAlias) { this.optionalSourceAlias = optionalSourceAlias; } // /** // * Optional alias. // * @deprecated // * @see #getDisplayName() // */ // public String getOptionalAlias() { // return getDisplayName(); // } // public void setOptionalAlias(String displayName) { // setDisplayName(displayName); // } /** * Display name. */ public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } /** * PersonalData getter. */ public PersonalData getPersonalData() { return this.personalData; } public void setPersonalData(PersonalData personalData) { this.personalData = personalData; } /** * Safe personal data getter. */ protected final PersonalData safePersonalData() { if (getPersonalData()==null) { return new PersonalData(); } return getPersonalData(); } /** * <<Transient>> identity first name. */ public String getIdentityFirstName() { return safePersonalData().getFirstName(); } public void setIdentityFirstName(String firstName) { safePersonalData().setFirstName(firstName); } /** * <<Transient>> identity last name. */ public String getIdentityLastName() { return safePersonalData().getLastName(); } public void setIdentityLastName(String lastName) { safePersonalData().setLastName(lastName); } /** * <<Transient>> Safe identity name getter. */ public String getIdentityName() { if (getPersonalData()==null) { return getAlias(); } return new StringBuilder(getPersonalData().getFirstName()) .append(" ") .append(getPersonalData().getLastName()).toString(); } /** * <<Transient>> gender. */ @JsonIgnore public char getGender() { return safePersonalData().getGender(); } public void setGender(char gender) { safePersonalData().setGender(gender); } /** * Gender as enum. */ public Gender getGenderAsEnum() { for (Gender g: Gender.values()) { if (g.getValue()==safePersonalData().getGender()) { return g; } } return Gender.NOT_SUPPLIED; } @JsonSerialize public void setGenderAsEnum(Gender gender) { safePersonalData().setGender(gender.getValue()); } /** * Appellation. */ @JsonIgnore public char getAppellation() { return safePersonalData().getAppellation(); } public void setAppellation(char appellation) { safePersonalData().setAppellation(appellation); } /** * <<Transient>> appellation. */ public Appellation getAppellationAsEnum() { for (Appellation a: Appellation.values()) { if (a.getValue()==safePersonalData().getAppellation()) { return a; } } return Appellation.NOT_SUPPLIED; } @JsonSerialize public void setAppellationAsEnum(Appellation appellation) { safePersonalData().setAppellation(appellation.getValue()); } /** * <<Transient>> birth date. */ public Date getBirthDate() { return safePersonalData().getBirthDate(); } public void setBirthDate(Date birthDate) { safePersonalData().setBirthDate(birthDate); } /** * <<Transient>> Safe age getter. */ public int getAge() { return getAge(new Date()); } /** * <<Transient>> Safe age getter. * * @param date */ protected int getAge(Date date) { if (getPersonalData()!=null && getPersonalData().getBirthDate()!=null) { DateTime birthdate = new DateTime(getPersonalData().getBirthDate()).withTimeAtStartOfDay(); return Years.yearsBetween(birthdate, new DateTime(date)).getYears(); } return -1; } /** * <<Transient>> True if image url is available. */ public boolean isImageAvailable() { if (getPersonalData()!=null && getPersonalData().getImageUrl()!=null && getPersonalData().getImageUrl().length()>0) { return true; } return false; } /** * <<Transient>> image URL. */ public String getImageUrl() { if (isImageAvailable()) { return safePersonalData().getImageUrl(); } return ""; } public void setImageUrl(String imageUrl) { safePersonalData().setImageUrl(imageUrl); } /** * <<Transient>> Safe identity alias. */ public String getAlias() { if (getDisplayName()!=null && getDisplayName().length()>0) { return getDisplayName(); } return getPrincipal(); } /** * Date created. */ public Date getCreated() { return this.created; } public void setCreated(Date created) { this.created = created; } /** * IdentityType getter. */ @JsonIgnore public char getIdentityType() { return this.identityType; } public void setIdentityType(char identityType) { this.identityType = identityType; } /** * Identity type as enum. */ public IdentityType getIdentityTypeAsEnum() { for (IdentityType t: IdentityType.values()) { if (t.getValue()==this.identityType) { return t; } } return IdentityType.PERSONAL_EMAIL; } @JsonSerialize public void setIdentityTypeAsEnum(IdentityType identityType) { this.identityType = identityType.getValue(); } /** * True if can receive email. */ public boolean isAddressable() { return IdentityType.isAddressable(getIdentityType()); } /** * Notification getter. */ @JsonIgnore public char getNotification() { return this.notification; } public void setNotification(char notification) { this.notification = notification; } /** * Notification as enum. */ public Notification getNotificationAsEnum() { for (Notification t: Notification.values()) { if (t.getValue()==this.notification) { return t; } } return Notification.AUTOMATIC; } @JsonSerialize public void setNotificationAsEnum(Notification notification) { this.notification = notification.getValue(); } /** * <<Transient>> Required to allow for file upload. */ public MultipartFile getFile() { return file; } public void setFile(MultipartFile file) { this.file = file; } /** * <<Transient>> Password to change. */ public String getPasswordToChange() { return passwordToChange; } public void setPasswordToChange(String passwordToChange) { this.passwordToChange = passwordToChange; } /** * <<Transient>> Password confirmation. */ public String getPasswordConfirmation() { return passwordConfirmation; } public void setPasswordConfirmation(String passwordConfirmation) { this.passwordConfirmation = passwordConfirmation; } /** * True only if password to change is not empty and matches password confirmation. */ public boolean isPasswordChanging() { if (getPasswordToChange()!=null && !getPasswordToChange().isEmpty() && getPasswordToChange().equals(getPasswordConfirmation())) { return true; } return false; } /** * List of phones. */ public List<Phone> getPhones() { return phones; } public void setPhones(List<Phone> phones) { this.phones = phones; } /** * List of contact infos. */ public List<ContactInfo> getContactInfos() { return contactInfos; } public void setContactInfos(List<ContactInfo> contactInfos) { this.contactInfos = contactInfos; } /** * Merger. * * @param command */ public Identity merge(Identity command) { setId(command.getId()); setIdentityTypeAsEnum(command.getIdentityTypeAsEnum()); setPrincipal(command.getPrincipal()); setDisplayName(command.getDisplayName()); setAppellationAsEnum(command.getAppellationAsEnum()); setIdentityFirstName(command.getIdentityFirstName()); setIdentityLastName(command.getIdentityLastName()); setGenderAsEnum(command.getGenderAsEnum()); setNotificationAsEnum(command.getNotificationAsEnum()); setBirthDate(command.getBirthDate()); setImageUrl(command.getImageUrl()); return this; } /** * toString * @return String */ public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getClass().getName()).append("@").append(Integer.toHexString(hashCode())).append(" ["); buffer.append("principal").append("='").append(getPrincipal()).append("' "); buffer.append("]"); return buffer.toString(); } /** * equals */ public boolean equals(Object other) { if ( (this == other ) ) return true; if ( (other == null ) ) return false; if ( !(other instanceof Identity) ) return false; Identity castOther = (Identity) other; return ((this.getPrincipal()==castOther.getPrincipal()) || ( this.getPrincipal()!=null && castOther.getPrincipal()!=null && this.getPrincipal().equals(castOther.getPrincipal()) )); } /** * hashCode */ public int hashCode() { int result = 17; result = 37 * result + ( getPrincipal() == null ? 0 : this.getPrincipal().hashCode() ); return result; } /* * Deprecated fields */ @JsonIgnore @Column(name="PIT_1") private char personalIdentityType_1 = 'N'; /** * @deprecated */ public char getPersonalIdentityType_1() { return personalIdentityType_1; } public void setPersonalIdentityType_1(char personalIdentityType_1) { this.personalIdentityType_1 = personalIdentityType_1; } @JsonIgnore @Column(name="PIT_2") private char personalIdentityType_2 = 'N'; /** * @deprecated */ public char getPersonalIdentityType_2() { return personalIdentityType_2; } public void setPersonalIdentityType_2(char personalIdentityType_2) { this.personalIdentityType_2 = personalIdentityType_2; } }
helianto-core/src/main/java/org/helianto/core/domain/Identity.java
/* Copyright 2005 I Serv Consultoria Empresarial Ltda. * * 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.helianto.core.domain; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Embedded; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OrderColumn; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import org.helianto.core.def.Appellation; import org.helianto.core.def.Gender; import org.helianto.core.def.IdentityType; import org.helianto.core.def.Notification; import org.joda.time.DateTime; import org.joda.time.Years; import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * An uniquely identified actor. * * @author Mauricio Fernandes de Castro */ @javax.persistence.Entity @Table(name="core_identity", uniqueConstraints = {@UniqueConstraint(columnNames={"principal"})} ) public class Identity implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Column(length=64) private String displayName = ""; @Column(length=20) private String optionalSourceAlias = ""; @Column(length=40) private String principal = ""; @JsonIgnore @Embedded private PersonalData personalData; @Temporal(TemporalType.TIMESTAMP) private Date created = new Date(); private char identityType = IdentityType.PERSONAL_EMAIL.getValue(); private char notification = Notification.AUTOMATIC.getValue(); @JsonIgnore @ElementCollection @CollectionTable(name = "core_identityPhone", joinColumns = @JoinColumn(name = "identityId")) @OrderColumn(name="sequence") private List<Phone> phones = new ArrayList<Phone>(); @JsonIgnore @ElementCollection @CollectionTable(name = "core_identityContact", joinColumns = @JoinColumn(name = "identityId")) @OrderColumn(name="sequence") private List<ContactInfo> contactInfos = new ArrayList<ContactInfo>(); @Transient private transient MultipartFile file; @Transient private String passwordToChange; @Transient private String passwordConfirmation; /** * Default constructor. */ public Identity() { super(); this.personalData = new PersonalData(); } /** * Principal constructor. * * @param principal */ public Identity(String principal) { this(principal, ""); } /** * Principal and optional alias constructor. * * @param principal * @param displayName */ public Identity(String principal, String displayName) { this(principal, displayName, new PersonalData()); } /** * Principal and optional alias constructor. * * @param principal * @param displayName * @param personalData */ public Identity(String principal, String displayName, PersonalData personalData) { setPrincipal(principal); setDisplayName(displayName); setPersonalData(personalData); } /** * Read constructor. * * @param id * @param userGroupId * @param identityType * @param principal * @param displayName * @param appellation * @param firstName * @param lastName * @param gender * @param notification * @param birthDate * @param imageUrl */ public Identity(Integer id, char identityType, String principal, String displayName, char appellation, String firstName, String lastName, char gender, char notification, Date birthDate, String imageUrl) { this(principal, displayName, new PersonalData(firstName, lastName, gender, appellation, birthDate, imageUrl)); this.id = id; this.identityType = identityType; this.notification = notification; } /** * Primary key. */ public int getId() { return this.id; } public void setId(int id) { this.id = id; } /** * Principal getter. */ public String getPrincipal() { return this.principal; } /** * Setting the principal also forces to lower case. * * @param principal */ public void setPrincipal(String principal) { if (principal!=null) { this.principal = principal.toLowerCase(); } else { this.principal = null; } } /** * <<Transient>> Principal name, i.e., substring of principal before '@', if any, * or the principal itself. */ public String getPrincipalName() { if (getPrincipal()!=null) { int position = getPrincipal().indexOf("@"); if (position>0) { return getPrincipal().substring(0, position); } return getPrincipal(); } return ""; } /** * <<Transient>> User principal domain, i.e., substring of principal after '@', if any, * or empty string. */ public String getPrincipalDomain() { if (getPrincipal()!=null) { int position = getPrincipal().indexOf("@"); if (position>0) { return getPrincipal().substring(position); } } return ""; } /** * Optional source alias. * * <p> * May be used to create an user in the future. * </p> */ public String getOptionalSourceAlias() { return optionalSourceAlias; } public void setOptionalSourceAlias(String optionalSourceAlias) { this.optionalSourceAlias = optionalSourceAlias; } // /** // * Optional alias. // * @deprecated // * @see #getDisplayName() // */ // public String getOptionalAlias() { // return getDisplayName(); // } // public void setOptionalAlias(String displayName) { // setDisplayName(displayName); // } /** * Display name. */ public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } /** * PersonalData getter. */ public PersonalData getPersonalData() { return this.personalData; } public void setPersonalData(PersonalData personalData) { this.personalData = personalData; } /** * Safe personal data getter. */ protected final PersonalData safePersonalData() { if (getPersonalData()==null) { return new PersonalData(); } return getPersonalData(); } /** * <<Transient>> identity first name. */ public String getIdentityFirstName() { return safePersonalData().getFirstName(); } public void setIdentityFirstName(String firstName) { safePersonalData().setFirstName(firstName); } /** * <<Transient>> identity last name. */ public String getIdentityLastName() { return safePersonalData().getLastName(); } public void setIdentityLastName(String lastName) { safePersonalData().setLastName(lastName); } /** * <<Transient>> Safe identity name getter. */ public String getIdentityName() { if (getPersonalData()==null) { return getAlias(); } return new StringBuilder(getPersonalData().getFirstName()) .append(" ") .append(getPersonalData().getLastName()).toString(); } /** * <<Transient>> gender. */ @JsonIgnore public char getGender() { return safePersonalData().getGender(); } public void setGender(char gender) { safePersonalData().setGender(gender); } /** * Gender as enum. */ public Gender getGenderAsEnum() { for (Gender g: Gender.values()) { if (g.getValue()==safePersonalData().getGender()) { return g; } } return Gender.NOT_SUPPLIED; } @JsonSerialize public void setGenderAsEnum(Gender gender) { safePersonalData().setGender(gender.getValue()); } /** * Appellation. */ @JsonIgnore public char getAppellation() { return safePersonalData().getAppellation(); } public void setAppellation(char appellation) { safePersonalData().setAppellation(appellation); } /** * <<Transient>> appellation. */ public Appellation getAppellationAsEnum() { for (Appellation a: Appellation.values()) { if (a.getValue()==safePersonalData().getAppellation()) { return a; } } return Appellation.NOT_SUPPLIED; } @JsonSerialize public void setAppellationAsEnum(Appellation appellation) { safePersonalData().setAppellation(appellation.getValue()); } /** * <<Transient>> birth date. */ public Date getBirthDate() { return safePersonalData().getBirthDate(); } public void setBirthDate(Date birthDate) { safePersonalData().setBirthDate(birthDate); } /** * <<Transient>> Safe age getter. */ public int getAge() { return getAge(new Date()); } /** * <<Transient>> Safe age getter. * * @param date */ protected int getAge(Date date) { if (getPersonalData()!=null && getPersonalData().getBirthDate()!=null) { DateTime birthdate = new DateTime(getPersonalData().getBirthDate()).withTimeAtStartOfDay(); return Years.yearsBetween(birthdate, new DateTime(date)).getYears(); } return -1; } /** * <<Transient>> True if image url is available. */ public boolean isImageAvailable() { if (getPersonalData()!=null && getPersonalData().getImageUrl()!=null && getPersonalData().getImageUrl().length()>0) { return true; } return false; } /** * <<Transient>> image URL. */ public String getImageUrl() { if (isImageAvailable()) { return safePersonalData().getImageUrl(); } return ""; } public void setImageUrl(String imageUrl) { safePersonalData().setImageUrl(imageUrl); } /** * <<Transient>> Safe identity alias. */ public String getAlias() { if (getDisplayName()!=null && getDisplayName().length()>0) { return getDisplayName(); } return getPrincipal(); } /** * Date created. */ public Date getCreated() { return this.created; } public void setCreated(Date created) { this.created = created; } /** * IdentityType getter. */ @JsonIgnore public char getIdentityType() { return this.identityType; } public void setIdentityType(char identityType) { this.identityType = identityType; } /** * Identity type as enum. */ public IdentityType getIdentityTypeAsEnum() { for (IdentityType t: IdentityType.values()) { if (t.getValue()==this.identityType) { return t; } } return IdentityType.PERSONAL_EMAIL; } @JsonSerialize public void setIdentityTypeAsEnum(IdentityType identityType) { this.identityType = identityType.getValue(); } /** * True if can receive email. */ public boolean isAddressable() { return IdentityType.isAddressable(getIdentityType()); } /** * Notification getter. */ @JsonIgnore public char getNotification() { return this.notification; } public void setNotification(char notification) { this.notification = notification; } /** * Notification as enum. */ public Notification getNotificationAsEnum() { for (Notification t: Notification.values()) { if (t.getValue()==this.notification) { return t; } } return Notification.AUTOMATIC; } @JsonSerialize public void setNotificationAsEnum(Notification notification) { this.notification = notification.getValue(); } /** * <<Transient>> Required to allow for file upload. */ public MultipartFile getFile() { return file; } public void setFile(MultipartFile file) { this.file = file; } /** * <<Transient>> Password to change. */ public String getPasswordToChange() { return passwordToChange; } public void setPasswordToChange(String passwordToChange) { this.passwordToChange = passwordToChange; } /** * <<Transient>> Password confirmation. */ public String getPasswordConfirmation() { return passwordConfirmation; } public void setPasswordConfirmation(String passwordConfirmation) { this.passwordConfirmation = passwordConfirmation; } /** * True only if password to change is not empty and matches password confirmation. */ public boolean isPasswordChanging() { if (getPasswordToChange()!=null && !getPasswordToChange().isEmpty() && getPasswordToChange().equals(getPasswordConfirmation())) { return true; } return false; } /** * List of phones. */ public List<Phone> getPhones() { return phones; } public void setPhones(List<Phone> phones) { this.phones = phones; } /** * List of contact infos. */ public List<ContactInfo> getContactInfos() { return contactInfos; } public void setContactInfos(List<ContactInfo> contactInfos) { this.contactInfos = contactInfos; } /** * Merger. * * @param command */ public Identity merge(Identity command) { setId(command.getId()); setIdentityType(command.getIdentityType()); setPrincipal(command.getPrincipal()); setDisplayName(command.getDisplayName()); setAppellationAsEnum(command.getAppellationAsEnum()); setIdentityFirstName(command.getIdentityFirstName()); setIdentityLastName(command.getIdentityLastName()); setGenderAsEnum(command.getGenderAsEnum()); setNotificationAsEnum(command.getNotificationAsEnum()); setBirthDate(command.getBirthDate()); setImageUrl(command.getImageUrl()); return this; } /** * toString * @return String */ public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getClass().getName()).append("@").append(Integer.toHexString(hashCode())).append(" ["); buffer.append("principal").append("='").append(getPrincipal()).append("' "); buffer.append("]"); return buffer.toString(); } /** * equals */ public boolean equals(Object other) { if ( (this == other ) ) return true; if ( (other == null ) ) return false; if ( !(other instanceof Identity) ) return false; Identity castOther = (Identity) other; return ((this.getPrincipal()==castOther.getPrincipal()) || ( this.getPrincipal()!=null && castOther.getPrincipal()!=null && this.getPrincipal().equals(castOther.getPrincipal()) )); } /** * hashCode */ public int hashCode() { int result = 17; result = 37 * result + ( getPrincipal() == null ? 0 : this.getPrincipal().hashCode() ); return result; } /* * Deprecated fields */ @JsonIgnore @Column(name="PIT_1") private char personalIdentityType_1 = 'N'; /** * @deprecated */ public char getPersonalIdentityType_1() { return personalIdentityType_1; } public void setPersonalIdentityType_1(char personalIdentityType_1) { this.personalIdentityType_1 = personalIdentityType_1; } @JsonIgnore @Column(name="PIT_2") private char personalIdentityType_2 = 'N'; /** * @deprecated */ public char getPersonalIdentityType_2() { return personalIdentityType_2; } public void setPersonalIdentityType_2(char personalIdentityType_2) { this.personalIdentityType_2 = personalIdentityType_2; } }
Refactored identityType update method.
helianto-core/src/main/java/org/helianto/core/domain/Identity.java
Refactored identityType update method.
Java
apache-2.0
959b022ee24a435629acd27192ed607409d8cef7
0
k9mail/k-9,cketti/k-9,cketti/k-9,cketti/k-9,k9mail/k-9,k9mail/k-9,cketti/k-9
package com.fsck.k9.view; import android.content.Context; import android.content.pm.PackageManager; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import timber.log.Timber; import android.view.KeyEvent; import android.webkit.WebSettings; import android.webkit.WebSettings.LayoutAlgorithm; import android.webkit.WebSettings.RenderPriority; import android.webkit.WebView; import android.widget.Toast; import com.fsck.k9.K9; import com.fsck.k9.K9.Theme; import com.fsck.k9.ui.R; import com.fsck.k9.mailstore.AttachmentResolver; public class MessageWebView extends RigidWebView { public MessageWebView(Context context) { super(context); } public MessageWebView(Context context, AttributeSet attrs) { super(context, attrs); } public MessageWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * Configure a web view to load or not load network data. A <b>true</b> setting here means that * network data will be blocked. * @param shouldBlockNetworkData True if network data should be blocked, false to allow network data. */ public void blockNetworkData(final boolean shouldBlockNetworkData) { /* * Block network loads. * * Images with content: URIs will not be blocked, nor * will network images that are already in the WebView cache. * */ getSettings().setBlockNetworkLoads(shouldBlockNetworkData); } /** * Configure a {@link WebView} to display a Message. This method takes into account a user's * preferences when configuring the view. This message is used to view a message and to display a message being * replied to. */ public void configure() { this.setVerticalScrollBarEnabled(true); this.setVerticalScrollbarOverlay(true); this.setScrollBarStyle(SCROLLBARS_INSIDE_OVERLAY); this.setLongClickable(true); if (K9.getK9MessageViewTheme() == Theme.DARK) { // Black theme should get a black webview background // we'll set the background of the messages on load this.setBackgroundColor(0xff000000); } final WebSettings webSettings = this.getSettings(); /* TODO this might improve rendering smoothness when webview is animated into view if (VERSION.SDK_INT >= VERSION_CODES.M) { webSettings.setOffscreenPreRaster(true); } */ webSettings.setSupportZoom(true); webSettings.setBuiltInZoomControls(true); webSettings.setUseWideViewPort(true); if (K9.autofitWidth()) { webSettings.setLoadWithOverviewMode(true); } disableDisplayZoomControls(); webSettings.setJavaScriptEnabled(false); webSettings.setLoadsImagesAutomatically(true); webSettings.setRenderPriority(RenderPriority.HIGH); // TODO: Review alternatives. NARROW_COLUMNS is deprecated on KITKAT webSettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS); setOverScrollMode(OVER_SCROLL_NEVER); webSettings.setTextZoom(K9.getFontSizes().getMessageViewContentAsPercent()); // Disable network images by default. This is overridden by preferences. blockNetworkData(true); } /** * Disable on-screen zoom controls on devices that support zooming via pinch-to-zoom. */ private void disableDisplayZoomControls() { PackageManager pm = getContext().getPackageManager(); boolean supportsMultiTouch = pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH) || pm.hasSystemFeature(PackageManager.FEATURE_FAKETOUCH_MULTITOUCH_DISTINCT); getSettings().setDisplayZoomControls(!supportsMultiTouch); } public void displayHtmlContentWithInlineAttachments(@NonNull String htmlText, @Nullable AttachmentResolver attachmentResolver, @Nullable OnPageFinishedListener onPageFinishedListener) { setWebViewClient(attachmentResolver, onPageFinishedListener); setHtmlContent(htmlText); } private void setWebViewClient(@Nullable AttachmentResolver attachmentResolver, @Nullable OnPageFinishedListener onPageFinishedListener) { K9WebViewClient webViewClient = K9WebViewClient.newInstance(attachmentResolver); if (onPageFinishedListener != null) { webViewClient.setOnPageFinishedListener(onPageFinishedListener); } setWebViewClient(webViewClient); } private void setHtmlContent(@NonNull String htmlText) { loadDataWithBaseURL("about:blank", htmlText, "text/html", "utf-8", null); resumeTimers(); } /* * Emulate the shift key being pressed to trigger the text selection mode * of a WebView. */ public void emulateShiftHeld() { try { KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0); shiftPressEvent.dispatch(this, null, null); Toast.makeText(getContext() , R.string.select_text_now, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Timber.e(e, "Exception in emulateShiftHeld()"); } } public interface OnPageFinishedListener { void onPageFinished(); } }
app/ui/src/main/java/com/fsck/k9/view/MessageWebView.java
package com.fsck.k9.view; import android.content.Context; import android.content.pm.PackageManager; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import timber.log.Timber; import android.view.KeyEvent; import android.webkit.WebSettings; import android.webkit.WebSettings.LayoutAlgorithm; import android.webkit.WebSettings.RenderPriority; import android.webkit.WebView; import android.widget.Toast; import com.fsck.k9.K9; import com.fsck.k9.K9.Theme; import com.fsck.k9.ui.R; import com.fsck.k9.mailstore.AttachmentResolver; public class MessageWebView extends RigidWebView { public MessageWebView(Context context) { super(context); } public MessageWebView(Context context, AttributeSet attrs) { super(context, attrs); } public MessageWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * Configure a web view to load or not load network data. A <b>true</b> setting here means that * network data will be blocked. * @param shouldBlockNetworkData True if network data should be blocked, false to allow network data. */ public void blockNetworkData(final boolean shouldBlockNetworkData) { /* * Block network loads. * * Images with content: URIs will not be blocked, nor * will network images that are already in the WebView cache. * */ getSettings().setBlockNetworkLoads(shouldBlockNetworkData); } /** * Configure a {@link WebView} to display a Message. This method takes into account a user's * preferences when configuring the view. This message is used to view a message and to display a message being * replied to. */ public void configure() { this.setVerticalScrollBarEnabled(true); this.setVerticalScrollbarOverlay(true); this.setScrollBarStyle(SCROLLBARS_INSIDE_OVERLAY); this.setLongClickable(true); if (K9.getK9MessageViewTheme() == Theme.DARK) { // Black theme should get a black webview background // we'll set the background of the messages on load this.setBackgroundColor(0xff000000); } final WebSettings webSettings = this.getSettings(); webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); /* TODO this might improve rendering smoothness when webview is animated into view if (VERSION.SDK_INT >= VERSION_CODES.M) { webSettings.setOffscreenPreRaster(true); } */ webSettings.setSupportZoom(true); webSettings.setBuiltInZoomControls(true); webSettings.setUseWideViewPort(true); if (K9.autofitWidth()) { webSettings.setLoadWithOverviewMode(true); } disableDisplayZoomControls(); webSettings.setJavaScriptEnabled(false); webSettings.setLoadsImagesAutomatically(true); webSettings.setRenderPriority(RenderPriority.HIGH); // TODO: Review alternatives. NARROW_COLUMNS is deprecated on KITKAT webSettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS); setOverScrollMode(OVER_SCROLL_NEVER); webSettings.setTextZoom(K9.getFontSizes().getMessageViewContentAsPercent()); // Disable network images by default. This is overridden by preferences. blockNetworkData(true); } /** * Disable on-screen zoom controls on devices that support zooming via pinch-to-zoom. */ private void disableDisplayZoomControls() { PackageManager pm = getContext().getPackageManager(); boolean supportsMultiTouch = pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH) || pm.hasSystemFeature(PackageManager.FEATURE_FAKETOUCH_MULTITOUCH_DISTINCT); getSettings().setDisplayZoomControls(!supportsMultiTouch); } public void displayHtmlContentWithInlineAttachments(@NonNull String htmlText, @Nullable AttachmentResolver attachmentResolver, @Nullable OnPageFinishedListener onPageFinishedListener) { setWebViewClient(attachmentResolver, onPageFinishedListener); setHtmlContent(htmlText); } private void setWebViewClient(@Nullable AttachmentResolver attachmentResolver, @Nullable OnPageFinishedListener onPageFinishedListener) { K9WebViewClient webViewClient = K9WebViewClient.newInstance(attachmentResolver); if (onPageFinishedListener != null) { webViewClient.setOnPageFinishedListener(onPageFinishedListener); } setWebViewClient(webViewClient); } private void setHtmlContent(@NonNull String htmlText) { loadDataWithBaseURL("about:blank", htmlText, "text/html", "utf-8", null); resumeTimers(); } /* * Emulate the shift key being pressed to trigger the text selection mode * of a WebView. */ public void emulateShiftHeld() { try { KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0); shiftPressEvent.dispatch(this, null, null); Toast.makeText(getContext() , R.string.select_text_now, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Timber.e(e, "Exception in emulateShiftHeld()"); } } public interface OnPageFinishedListener { void onPageFinished(); } }
Enabling Web cache unconditionally
app/ui/src/main/java/com/fsck/k9/view/MessageWebView.java
Enabling Web cache unconditionally
Java
apache-2.0
044856d87b39a0ffb581ad946968da4598198f15
0
bmaupin/android-sms-plus
/* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.ui; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.provider.Telephony.Sms; import android.provider.Telephony.Sms.Inbox; import android.telephony.SmsMessage; import android.text.TextUtils; import android.util.Log; import android.util.Config; import android.view.Window; import com.android.mms.R; import com.android.mms.transaction.SmsReceiverService; import com.google.android.mms.util.SqliteWrapper; /** * Display a class-zero SMS message to the user. Wait for the user to dismiss * it. */ public class ClassZeroActivity extends Activity { private static final String BUFFER = " "; private static final int BUFFER_OFFSET = BUFFER.length() * 2; private static final String TAG = "display_00"; private static final int ON_AUTO_SAVE = 1; private static final String[] REPLACE_PROJECTION = new String[] { Sms._ID, Sms.ADDRESS, Sms.PROTOCOL }; private static final int REPLACE_COLUMN_ID = 0; /** Default timer to dismiss the dialog. */ private static final long DEFAULT_TIMER = 5 * 60 * 1000; /** To remember the exact time when the timer should fire. */ private static final String TIMER_FIRE = "timer_fire"; private SmsMessage mMessage = null; /** Is the message read. */ private boolean mRead = false; /** The timer to dismiss the dialog automatically. */ private long mTimerSet = 0; private AlertDialog mDialog = null; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // Do not handle an invalid message. if (msg.what == ON_AUTO_SAVE) { mRead = false; mDialog.dismiss(); saveMessage(); finish(); } } }; private void saveMessage() { if (mMessage.isReplace()) { replaceMessage(mMessage); } else { storeMessage(mMessage); } } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setBackgroundDrawableResource( R.drawable.class_zero_background); byte[] pdu = getIntent().getByteArrayExtra("pdu"); mMessage = SmsMessage.createFromPdu(pdu); CharSequence messageChars = mMessage.getMessageBody(); String message = messageChars.toString(); if (TextUtils.isEmpty(message)) { finish(); return; } // TODO: The following line adds an emptry string before and after a message. // This is not the correct way to layout a message. This is more of a hack // to work-around a bug in AlertDialog. This needs to be fixed later when // Android fixes the bug in AlertDialog. if (message.length() < BUFFER_OFFSET) messageChars = BUFFER + message + BUFFER; long now = SystemClock.uptimeMillis(); mDialog = new AlertDialog.Builder(this).setMessage(messageChars) .setPositiveButton(R.string.save, mSaveListener) .setNegativeButton(android.R.string.cancel, mCancelListener) .setCancelable(false).show(); mTimerSet = now + DEFAULT_TIMER; if (icicle != null) { mTimerSet = icicle.getLong(TIMER_FIRE, mTimerSet); } if (mTimerSet <= now) { // Save the message if the timer already expired. mHandler.sendEmptyMessage(ON_AUTO_SAVE); } else { mHandler.sendEmptyMessageAtTime(ON_AUTO_SAVE, mTimerSet); if (Config.DEBUG) { Log.d(TAG, "onCreate time = " + Long.toString(mTimerSet) + " " + this.toString()); } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putLong(TIMER_FIRE, mTimerSet); if (Config.DEBUG) { Log.d(TAG, "onSaveInstanceState time = " + Long.toString(mTimerSet) + " " + this.toString()); } } @Override protected void onStop() { super.onStop(); mHandler.removeMessages(ON_AUTO_SAVE); if (Config.DEBUG) { Log.d(TAG, "onStop " + this.toString()); } } private final OnClickListener mCancelListener = new OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { finish(); } }; private final OnClickListener mSaveListener = new OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mRead = true; saveMessage(); finish(); } }; private ContentValues extractContentValues(SmsMessage sms) { // Store the message in the content provider. ContentValues values = new ContentValues(); values.put(Inbox.ADDRESS, sms.getDisplayOriginatingAddress()); // Use now for the timestamp to avoid confusion with clock // drift between the handset and the SMSC. values.put(Inbox.DATE, new Long(System.currentTimeMillis())); values.put(Inbox.PROTOCOL, sms.getProtocolIdentifier()); values.put(Inbox.READ, Integer.valueOf(mRead ? 1 : 0)); if (sms.getPseudoSubject().length() > 0) { values.put(Inbox.SUBJECT, sms.getPseudoSubject()); } values.put(Inbox.REPLY_PATH_PRESENT, sms.isReplyPathPresent() ? 1 : 0); values.put(Inbox.SERVICE_CENTER, sms.getServiceCenterAddress()); return values; } private Uri replaceMessage(SmsMessage sms) { ContentValues values = extractContentValues(sms); values.put(Inbox.BODY, sms.getMessageBody()); ContentResolver resolver = getContentResolver(); String originatingAddress = sms.getOriginatingAddress(); int protocolIdentifier = sms.getProtocolIdentifier(); String selection = Sms.ADDRESS + " = ? AND " + Sms.PROTOCOL + " = ?"; String[] selectionArgs = new String[] { originatingAddress, Integer.toString(protocolIdentifier) }; Cursor cursor = SqliteWrapper.query(this, resolver, Inbox.CONTENT_URI, REPLACE_PROJECTION, selection, selectionArgs, null); try { if (cursor.moveToFirst()) { long messageId = cursor.getLong(REPLACE_COLUMN_ID); Uri messageUri = ContentUris.withAppendedId( Sms.CONTENT_URI, messageId); SqliteWrapper.update(this, resolver, messageUri, values, null, null); return messageUri; } } finally { cursor.close(); } return storeMessage(sms); } private Uri storeMessage(SmsMessage sms) { // Store the message in the content provider. ContentValues values = extractContentValues(sms); values.put(Inbox.BODY, sms.getDisplayMessageBody()); ContentResolver resolver = getContentResolver(); return SqliteWrapper.insert(this, resolver, Inbox.CONTENT_URI, values); } }
src/com/android/mms/ui/ClassZeroActivity.java
/* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.ui; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.provider.Telephony.Sms; import android.provider.Telephony.Sms.Inbox; import android.telephony.SmsMessage; import android.util.Log; import android.util.Config; import android.view.Window; import com.android.mms.R; import com.android.mms.transaction.SmsReceiverService; import com.google.android.mms.util.SqliteWrapper; /** * Display a class-zero SMS message to the user. Wait for the user to dismiss * it. */ public class ClassZeroActivity extends Activity { private static final String TAG = "display_00"; private static final int ON_AUTO_SAVE = 1; private static final String[] REPLACE_PROJECTION = new String[] { Sms._ID, Sms.ADDRESS, Sms.PROTOCOL }; private static final int REPLACE_COLUMN_ID = 0; /** Default timer to dismiss the dialog. */ private static final long DEFAULT_TIMER = 5 * 60 * 1000; /** To remember the exact time when the timer should fire. */ private static final String TIMER_FIRE = "timer_fire"; private SmsMessage mMessage = null; /** Is the message read. */ private boolean mRead = false; /** The timer to dismiss the dialog automatically. */ private long mTimerSet = 0; private AlertDialog mDialog = null; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // Do not handle an invalid message. if (msg.what == ON_AUTO_SAVE) { mRead = false; mDialog.dismiss(); saveMessage(); finish(); } } }; private void saveMessage() { if (mMessage.isReplace()) { replaceMessage(mMessage); } else { storeMessage(mMessage); } } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setBackgroundDrawableResource( R.drawable.class_zero_background); byte[] pdu = getIntent().getByteArrayExtra("pdu"); mMessage = SmsMessage.createFromPdu(pdu); CharSequence messageChars = mMessage.getMessageBody(); long now = SystemClock.uptimeMillis(); mDialog = new AlertDialog.Builder(this).setMessage(messageChars) .setPositiveButton(R.string.save, mSaveListener) .setNegativeButton(android.R.string.cancel, mCancelListener) .setCancelable(false).show(); mTimerSet = now + DEFAULT_TIMER; if (icicle != null) { mTimerSet = icicle.getLong(TIMER_FIRE, mTimerSet); } if (mTimerSet <= now) { // Save the message if the timer already expired. mHandler.sendEmptyMessage(ON_AUTO_SAVE); } else { mHandler.sendEmptyMessageAtTime(ON_AUTO_SAVE, mTimerSet); if (Config.DEBUG) { Log.d(TAG, "onCreate time = " + Long.toString(mTimerSet) + " " + this.toString()); } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putLong(TIMER_FIRE, mTimerSet); if (Config.DEBUG) { Log.d(TAG, "onSaveInstanceState time = " + Long.toString(mTimerSet) + " " + this.toString()); } } @Override protected void onStop() { super.onStop(); mHandler.removeMessages(ON_AUTO_SAVE); if (Config.DEBUG) { Log.d(TAG, "onStop " + this.toString()); } } private final OnClickListener mCancelListener = new OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { finish(); } }; private final OnClickListener mSaveListener = new OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mRead = true; saveMessage(); finish(); } }; private ContentValues extractContentValues(SmsMessage sms) { // Store the message in the content provider. ContentValues values = new ContentValues(); values.put(Inbox.ADDRESS, sms.getDisplayOriginatingAddress()); // Use now for the timestamp to avoid confusion with clock // drift between the handset and the SMSC. values.put(Inbox.DATE, new Long(System.currentTimeMillis())); values.put(Inbox.PROTOCOL, sms.getProtocolIdentifier()); values.put(Inbox.READ, Integer.valueOf(mRead ? 1 : 0)); if (sms.getPseudoSubject().length() > 0) { values.put(Inbox.SUBJECT, sms.getPseudoSubject()); } values.put(Inbox.REPLY_PATH_PRESENT, sms.isReplyPathPresent() ? 1 : 0); values.put(Inbox.SERVICE_CENTER, sms.getServiceCenterAddress()); return values; } private Uri replaceMessage(SmsMessage sms) { ContentValues values = extractContentValues(sms); values.put(Inbox.BODY, sms.getMessageBody()); ContentResolver resolver = getContentResolver(); String originatingAddress = sms.getOriginatingAddress(); int protocolIdentifier = sms.getProtocolIdentifier(); String selection = Sms.ADDRESS + " = ? AND " + Sms.PROTOCOL + " = ?"; String[] selectionArgs = new String[] { originatingAddress, Integer.toString(protocolIdentifier) }; Cursor cursor = SqliteWrapper.query(this, resolver, Inbox.CONTENT_URI, REPLACE_PROJECTION, selection, selectionArgs, null); try { if (cursor.moveToFirst()) { long messageId = cursor.getLong(REPLACE_COLUMN_ID); Uri messageUri = ContentUris.withAppendedId( Sms.CONTENT_URI, messageId); SqliteWrapper.update(this, resolver, messageUri, values, null, null); return messageUri; } } finally { cursor.close(); } return storeMessage(sms); } private Uri storeMessage(SmsMessage sms) { // Store the message in the content provider. ContentValues values = extractContentValues(sms); values.put(Inbox.BODY, sms.getDisplayMessageBody()); ContentResolver resolver = getContentResolver(); return SqliteWrapper.insert(this, resolver, Inbox.CONTENT_URI, values); } }
Cancel button on the notification dialog, when Displaymode00 message is recieved is not proper. Whenever the string in the notification is small, the Cancel button is getting cut and the second half is displayed below.
src/com/android/mms/ui/ClassZeroActivity.java
Cancel button on the notification dialog, when Displaymode00 message is recieved is not proper.
Java
apache-2.0
6f15f161462bb3559fd2dc9e5e0125ac3d71d138
0
jsendnsca/jsendnsca
/* * 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.googlecode.jsendnsca.encryption; import org.apache.commons.lang.StringUtils; /** * Encryption to be used when sending the * {@link com.googlecode.jsendnsca.MessagePayload} * * @author Raj Patel * */ public enum Encryption { /** * no encryption */ NONE(), /** * Triple DES encryption */ TRIPLE_DES(new TripleDESEncryptor()), /** * XOR encryption(?) */ XOR(new XorEncryptor()), /** * Rijndael 128 encryption */ RIJNDAEL128(new AESEncryptor(16)), /** * Rijndael 192 encryption */ RIJNDAEL192(new AESEncryptor(24)), /** * Rijndael 256 encryption */ RIJNDAEL256(new AESEncryptor(32)), /** * Blowfish 128 encryption */ BLOWFISH128(new BlowfishEncryptor(16)), /** * Blowfish 448 encryption, JCE is needed to use Blowfish with long keys */ BLOWFISH448(new BlowfishEncryptor(56)); /** * @return the {@link Encryptor} for this {@link Encryption} constant */ public Encryptor getEncryptor() { return encryptor; } public static String supportedList() { return StringUtils.join(Encryption.values(), ','); } private final Encryptor encryptor; Encryption() { this.encryptor = none(); } Encryption(Encryptor encryptor) { this.encryptor = encryptor; } private Encryptor none() { return new Encryptor() { public void encrypt(byte[] passiveCheckBytes, byte[] initVector, String password) { } }; } }
src/main/java/com/googlecode/jsendnsca/encryption/Encryption.java
/* * 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.googlecode.jsendnsca.encryption; import org.apache.commons.lang.StringUtils; /** * Encryption to be used when sending the * {@link com.googlecode.jsendnsca.MessagePayload} * * @author Raj Patel * */ public enum Encryption { /** * no encryption */ NONE(), /** * Triple DES encryption */ TRIPLE_DES(new TripleDESEncryptor()), /** * XOR encryption(?) */ XOR(new XorEncryptor()), /** * Rijndael 128 encryption */ RIJNDAEL128(new AESEncryptor(16)), /** * Rijndael 192 encryption */ RIJNDAEL192(new AESEncryptor(24)), /** * Rijndael 256 encryption */ RIJNDAEL256(new AESEncryptor(32)), /** * Blowfish 128 encryption */ BLOWFISH128(new BlowfishEncryptor(16)), /** * Blowfish 448 encryption, JCE are needed to use Blowfish with long keys */ BLOWFISH448(new BlowfishEncryptor(56)); /** * @return the {@link Encryptor} for this {@link Encryption} constant */ public Encryptor getEncryptor() { return encryptor; } public static String supportedList() { return StringUtils.join(Encryption.values(), ','); } private final Encryptor encryptor; Encryption() { this.encryptor = none(); } Encryption(Encryptor encryptor) { this.encryptor = encryptor; } private Encryptor none() { return new Encryptor() { public void encrypt(byte[] passiveCheckBytes, byte[] initVector, String password) { } }; } }
Blowfish Encryptor fixed typo
src/main/java/com/googlecode/jsendnsca/encryption/Encryption.java
Blowfish Encryptor
Java
apache-2.0
2451c2c532e70766f8f1a045a1e3573dfebb8688
0
mahak/hbase,Apache9/hbase,Apache9/hbase,francisliu/hbase,ndimiduk/hbase,ChinmaySKulkarni/hbase,ndimiduk/hbase,Apache9/hbase,ndimiduk/hbase,Apache9/hbase,francisliu/hbase,ndimiduk/hbase,francisliu/hbase,Apache9/hbase,ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,ChinmaySKulkarni/hbase,mahak/hbase,francisliu/hbase,ndimiduk/hbase,Apache9/hbase,Apache9/hbase,ChinmaySKulkarni/hbase,mahak/hbase,apurtell/hbase,mahak/hbase,apurtell/hbase,mahak/hbase,ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,francisliu/hbase,ndimiduk/hbase,Apache9/hbase,apurtell/hbase,mahak/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,francisliu/hbase,francisliu/hbase,francisliu/hbase,apurtell/hbase,mahak/hbase,ndimiduk/hbase,ndimiduk/hbase,ndimiduk/hbase,Apache9/hbase,apurtell/hbase,Apache9/hbase,francisliu/hbase,ChinmaySKulkarni/hbase,ndimiduk/hbase,mahak/hbase,ChinmaySKulkarni/hbase,mahak/hbase,apurtell/hbase,apurtell/hbase,mahak/hbase,francisliu/hbase,apurtell/hbase
/** * 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.replication.regionserver; import static org.apache.hadoop.hbase.wal.AbstractFSWALProvider.getArchivedLogPath; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.Server; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableDescriptors; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.regionserver.RSRpcServices; import org.apache.hadoop.hbase.regionserver.RegionServerCoprocessorHost; import org.apache.hadoop.hbase.replication.ChainWALEntryFilter; import org.apache.hadoop.hbase.replication.ClusterMarkingEntryFilter; import org.apache.hadoop.hbase.replication.ReplicationEndpoint; import org.apache.hadoop.hbase.replication.ReplicationException; import org.apache.hadoop.hbase.replication.ReplicationPeer; import org.apache.hadoop.hbase.replication.ReplicationQueueInfo; import org.apache.hadoop.hbase.replication.ReplicationQueueStorage; import org.apache.hadoop.hbase.replication.SystemTableWALEntryFilter; import org.apache.hadoop.hbase.replication.WALEntryFilter; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.hbase.wal.AbstractFSWALProvider; import org.apache.hadoop.hbase.wal.WAL.Entry; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting; import org.apache.hbase.thirdparty.com.google.common.collect.Lists; /** * Class that handles the source of a replication stream. * Currently does not handle more than 1 slave * For each slave cluster it selects a random number of peers * using a replication ratio. For example, if replication ration = 0.1 * and slave cluster has 100 region servers, 10 will be selected. * <p> * A stream is considered down when we cannot contact a region server on the * peer cluster for more than 55 seconds by default. * </p> */ @InterfaceAudience.Private public class ReplicationSource implements ReplicationSourceInterface { private static final Logger LOG = LoggerFactory.getLogger(ReplicationSource.class); // Queues of logs to process, entry in format of walGroupId->queue, // each presents a queue for one wal group private Map<String, PriorityBlockingQueue<Path>> queues = new HashMap<>(); // per group queue size, keep no more than this number of logs in each wal group protected int queueSizePerGroup; protected ReplicationQueueStorage queueStorage; protected ReplicationPeer replicationPeer; protected Configuration conf; protected ReplicationQueueInfo replicationQueueInfo; // The manager of all sources to which we ping back our progress protected ReplicationSourceManager manager; // Should we stop everything? protected Server server; // How long should we sleep for each retry private long sleepForRetries; protected FileSystem fs; // id of this cluster private UUID clusterId; // total number of edits we replicated private AtomicLong totalReplicatedEdits = new AtomicLong(0); // The znode we currently play with protected String queueId; // Maximum number of retries before taking bold actions private int maxRetriesMultiplier; // Indicates if this particular source is running private volatile boolean sourceRunning = false; // Metrics for this source private MetricsSource metrics; // WARN threshold for the number of queued logs, defaults to 2 private int logQueueWarnThreshold; // ReplicationEndpoint which will handle the actual replication private volatile ReplicationEndpoint replicationEndpoint; // A filter (or a chain of filters) for the WAL entries. protected volatile WALEntryFilter walEntryFilter; // throttler private ReplicationThrottler throttler; private long defaultBandwidth; private long currentBandwidth; private WALFileLengthProvider walFileLengthProvider; @VisibleForTesting protected final ConcurrentHashMap<String, ReplicationSourceShipper> workerThreads = new ConcurrentHashMap<>(); private AtomicLong totalBufferUsed; public static final String WAIT_ON_ENDPOINT_SECONDS = "hbase.replication.wait.on.endpoint.seconds"; public static final int DEFAULT_WAIT_ON_ENDPOINT_SECONDS = 30; private int waitOnEndpointSeconds = -1; private Thread initThread; /** * Instantiation method used by region servers * @param conf configuration to use * @param fs file system to use * @param manager replication manager to ping to * @param server the server for this region server * @param queueId the id of our replication queue * @param clusterId unique UUID for the cluster * @param metrics metrics for replication source */ @Override public void init(Configuration conf, FileSystem fs, ReplicationSourceManager manager, ReplicationQueueStorage queueStorage, ReplicationPeer replicationPeer, Server server, String queueId, UUID clusterId, WALFileLengthProvider walFileLengthProvider, MetricsSource metrics) throws IOException { this.server = server; this.conf = HBaseConfiguration.create(conf); this.waitOnEndpointSeconds = this.conf.getInt(WAIT_ON_ENDPOINT_SECONDS, DEFAULT_WAIT_ON_ENDPOINT_SECONDS); decorateConf(); this.sleepForRetries = this.conf.getLong("replication.source.sleepforretries", 1000); // 1 second this.maxRetriesMultiplier = this.conf.getInt("replication.source.maxretriesmultiplier", 300); // 5 minutes @ 1 sec per this.queueSizePerGroup = this.conf.getInt("hbase.regionserver.maxlogs", 32); this.queueStorage = queueStorage; this.replicationPeer = replicationPeer; this.manager = manager; this.fs = fs; this.metrics = metrics; this.clusterId = clusterId; this.queueId = queueId; this.replicationQueueInfo = new ReplicationQueueInfo(queueId); this.logQueueWarnThreshold = this.conf.getInt("replication.source.log.queue.warn", 2); defaultBandwidth = this.conf.getLong("replication.source.per.peer.node.bandwidth", 0); currentBandwidth = getCurrentBandwidth(); this.throttler = new ReplicationThrottler((double) currentBandwidth / 10.0); this.totalBufferUsed = manager.getTotalBufferUsed(); this.walFileLengthProvider = walFileLengthProvider; LOG.info("queueId={}, ReplicationSource: {}, currentBandwidth={}", queueId, replicationPeer.getId(), this.currentBandwidth); } private void decorateConf() { String replicationCodec = this.conf.get(HConstants.REPLICATION_CODEC_CONF_KEY); if (StringUtils.isNotEmpty(replicationCodec)) { this.conf.set(HConstants.RPC_CODEC_CONF_KEY, replicationCodec); } } @Override public void enqueueLog(Path log) { String logPrefix = AbstractFSWALProvider.getWALPrefixFromWALName(log.getName()); PriorityBlockingQueue<Path> queue = queues.get(logPrefix); if (queue == null) { queue = new PriorityBlockingQueue<>(queueSizePerGroup, new LogsComparator()); // make sure that we do not use an empty queue when setting up a ReplicationSource, otherwise // the shipper may quit immediately queue.put(log); queues.put(logPrefix, queue); if (this.isSourceActive() && this.walEntryFilter != null) { // new wal group observed after source startup, start a new worker thread to track it // notice: it's possible that log enqueued when this.running is set but worker thread // still not launched, so it's necessary to check workerThreads before start the worker tryStartNewShipper(logPrefix, queue); } } else { queue.put(log); } if (LOG.isTraceEnabled()) { LOG.trace("{} Added log file {} to queue of source {}.", logPeerId(), logPrefix, this.replicationQueueInfo.getQueueId()); } this.metrics.incrSizeOfLogQueue(); // This will log a warning for each new log that gets created above the warn threshold int queueSize = queue.size(); if (queueSize > this.logQueueWarnThreshold) { LOG.warn("{} WAL group {} queue size: {} exceeds value of " + "replication.source.log.queue.warn: {}", logPeerId(), logPrefix, queueSize, logQueueWarnThreshold); } } @Override public void addHFileRefs(TableName tableName, byte[] family, List<Pair<Path, Path>> pairs) throws ReplicationException { String peerId = replicationPeer.getId(); Map<TableName, List<String>> tableCFMap = replicationPeer.getTableCFs(); if (tableCFMap != null) { List<String> tableCfs = tableCFMap.get(tableName); if (tableCFMap.containsKey(tableName) && (tableCfs == null || tableCfs.contains(Bytes.toString(family)))) { this.queueStorage.addHFileRefs(peerId, pairs); metrics.incrSizeOfHFileRefsQueue(pairs.size()); } else { LOG.debug("HFiles will not be replicated belonging to the table {} family {} to peer id {}", tableName, Bytes.toString(family), peerId); } } else { // user has explicitly not defined any table cfs for replication, means replicate all the // data this.queueStorage.addHFileRefs(peerId, pairs); metrics.incrSizeOfHFileRefsQueue(pairs.size()); } } private ReplicationEndpoint createReplicationEndpoint() throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException { RegionServerCoprocessorHost rsServerHost = null; if (server instanceof HRegionServer) { rsServerHost = ((HRegionServer) server).getRegionServerCoprocessorHost(); } String replicationEndpointImpl = replicationPeer.getPeerConfig().getReplicationEndpointImpl(); ReplicationEndpoint replicationEndpoint; if (replicationEndpointImpl == null) { // Default to HBase inter-cluster replication endpoint; skip reflection replicationEndpoint = new HBaseInterClusterReplicationEndpoint(); } else { try { replicationEndpoint = Class.forName(replicationEndpointImpl) .asSubclass(ReplicationEndpoint.class) .getDeclaredConstructor() .newInstance(); } catch (NoSuchMethodException | InvocationTargetException e) { throw new IllegalArgumentException(e); } } if (rsServerHost != null) { ReplicationEndpoint newReplicationEndPoint = rsServerHost.postCreateReplicationEndPoint(replicationEndpoint); if (newReplicationEndPoint != null) { // Override the newly created endpoint from the hook with configured end point replicationEndpoint = newReplicationEndPoint; } } return replicationEndpoint; } private void initAndStartReplicationEndpoint(ReplicationEndpoint replicationEndpoint) throws IOException, TimeoutException { TableDescriptors tableDescriptors = null; if (server instanceof HRegionServer) { tableDescriptors = ((HRegionServer) server).getTableDescriptors(); } replicationEndpoint .init(new ReplicationEndpoint.Context(server, conf, replicationPeer.getConfiguration(), fs, replicationPeer.getId(), clusterId, replicationPeer, metrics, tableDescriptors, server)); replicationEndpoint.start(); replicationEndpoint.awaitRunning(waitOnEndpointSeconds, TimeUnit.SECONDS); } private void initializeWALEntryFilter(UUID peerClusterId) { // get the WALEntryFilter from ReplicationEndpoint and add it to default filters ArrayList<WALEntryFilter> filters = Lists.<WALEntryFilter> newArrayList(new SystemTableWALEntryFilter()); WALEntryFilter filterFromEndpoint = this.replicationEndpoint.getWALEntryfilter(); if (filterFromEndpoint != null) { filters.add(filterFromEndpoint); } filters.add(new ClusterMarkingEntryFilter(clusterId, peerClusterId, replicationEndpoint)); this.walEntryFilter = new ChainWALEntryFilter(filters); } private void tryStartNewShipper(String walGroupId, PriorityBlockingQueue<Path> queue) { ReplicationSourceShipper worker = createNewShipper(walGroupId, queue); ReplicationSourceShipper extant = workerThreads.putIfAbsent(walGroupId, worker); if (extant != null) { if(LOG.isDebugEnabled()) { LOG.debug("{} Someone has beat us to start a worker thread for wal group {}", logPeerId(), walGroupId); } } else { if(LOG.isDebugEnabled()) { LOG.debug("{} Starting up worker for wal group {}", logPeerId(), walGroupId); } ReplicationSourceWALReader walReader = createNewWALReader(walGroupId, queue, worker.getStartPosition()); Threads.setDaemonThreadRunning(walReader, Thread.currentThread().getName() + ".replicationSource.wal-reader." + walGroupId + "," + queueId, this::uncaughtException); worker.setWALReader(walReader); worker.startup(this::uncaughtException); } } @Override public Map<String, ReplicationStatus> getWalGroupStatus() { Map<String, ReplicationStatus> sourceReplicationStatus = new TreeMap<>(); long ageOfLastShippedOp, replicationDelay, fileSize; for (Map.Entry<String, ReplicationSourceShipper> walGroupShipper : workerThreads.entrySet()) { String walGroupId = walGroupShipper.getKey(); ReplicationSourceShipper shipper = walGroupShipper.getValue(); ageOfLastShippedOp = metrics.getAgeofLastShippedOp(walGroupId); int queueSize = queues.get(walGroupId).size(); replicationDelay = metrics.getReplicationDelay(); Path currentPath = shipper.getCurrentPath(); fileSize = -1; if (currentPath != null) { try { fileSize = getFileSize(currentPath); } catch (IOException e) { LOG.warn("Ignore the exception as the file size of HLog only affects the web ui", e); } } else { currentPath = new Path("NO_LOGS_IN_QUEUE"); LOG.warn("{} No replication ongoing, waiting for new log", logPeerId()); } ReplicationStatus.ReplicationStatusBuilder statusBuilder = ReplicationStatus.newBuilder(); statusBuilder.withPeerId(this.getPeerId()) .withQueueSize(queueSize) .withWalGroup(walGroupId) .withCurrentPath(currentPath) .withCurrentPosition(shipper.getCurrentPosition()) .withFileSize(fileSize) .withAgeOfLastShippedOp(ageOfLastShippedOp) .withReplicationDelay(replicationDelay); sourceReplicationStatus.put(this.getPeerId() + "=>" + walGroupId, statusBuilder.build()); } return sourceReplicationStatus; } private long getFileSize(Path currentPath) throws IOException { long fileSize; try { fileSize = fs.getContentSummary(currentPath).getLength(); } catch (FileNotFoundException e) { currentPath = getArchivedLogPath(currentPath, conf); fileSize = fs.getContentSummary(currentPath).getLength(); } return fileSize; } protected ReplicationSourceShipper createNewShipper(String walGroupId, PriorityBlockingQueue<Path> queue) { return new ReplicationSourceShipper(conf, walGroupId, queue, this); } private ReplicationSourceWALReader createNewWALReader(String walGroupId, PriorityBlockingQueue<Path> queue, long startPosition) { return replicationPeer.getPeerConfig().isSerial() ? new SerialReplicationSourceWALReader(fs, conf, queue, startPosition, walEntryFilter, this) : new ReplicationSourceWALReader(fs, conf, queue, startPosition, walEntryFilter, this); } protected final void uncaughtException(Thread t, Throwable e) { RSRpcServices.exitIfOOME(e); LOG.error("Unexpected exception in {} currentPath={}", t.getName(), getCurrentPath(), e); server.abort("Unexpected exception in " + t.getName(), e); } @Override public ReplicationEndpoint getReplicationEndpoint() { return this.replicationEndpoint; } @Override public ReplicationSourceManager getSourceManager() { return this.manager; } @Override public void tryThrottle(int batchSize) throws InterruptedException { checkBandwidthChangeAndResetThrottler(); if (throttler.isEnabled()) { long sleepTicks = throttler.getNextSleepInterval(batchSize); if (sleepTicks > 0) { if (LOG.isTraceEnabled()) { LOG.trace("{} To sleep {}ms for throttling control", logPeerId(), sleepTicks); } Thread.sleep(sleepTicks); // reset throttler's cycle start tick when sleep for throttling occurs throttler.resetStartTick(); } } } private void checkBandwidthChangeAndResetThrottler() { long peerBandwidth = getCurrentBandwidth(); if (peerBandwidth != currentBandwidth) { currentBandwidth = peerBandwidth; throttler.setBandwidth((double) currentBandwidth / 10.0); LOG.info("ReplicationSource : {} bandwidth throttling changed, currentBandWidth={}", replicationPeer.getId(), currentBandwidth); } } private long getCurrentBandwidth() { long peerBandwidth = replicationPeer.getPeerBandwidth(); // user can set peer bandwidth to 0 to use default bandwidth return peerBandwidth != 0 ? peerBandwidth : defaultBandwidth; } /** * Do the sleeping logic * @param msg Why we sleep * @param sleepMultiplier by how many times the default sleeping time is augmented * @return True if <code>sleepMultiplier</code> is &lt; <code>maxRetriesMultiplier</code> */ protected boolean sleepForRetries(String msg, int sleepMultiplier) { try { if (LOG.isTraceEnabled()) { LOG.trace("{} {}, sleeping {} times {}", logPeerId(), msg, sleepForRetries, sleepMultiplier); } Thread.sleep(this.sleepForRetries * sleepMultiplier); } catch (InterruptedException e) { if(LOG.isDebugEnabled()) { LOG.debug("{} Interrupted while sleeping between retries", logPeerId()); } Thread.currentThread().interrupt(); } return sleepMultiplier < maxRetriesMultiplier; } private void initialize() { int sleepMultiplier = 1; while (this.isSourceActive()) { ReplicationEndpoint replicationEndpoint; try { replicationEndpoint = createReplicationEndpoint(); } catch (Exception e) { LOG.warn("{} error creating ReplicationEndpoint, retry", logPeerId(), e); if (sleepForRetries("Error creating ReplicationEndpoint", sleepMultiplier)) { sleepMultiplier++; } continue; } try { initAndStartReplicationEndpoint(replicationEndpoint); this.replicationEndpoint = replicationEndpoint; break; } catch (Exception e) { LOG.warn("{} Error starting ReplicationEndpoint, retry", logPeerId(), e); replicationEndpoint.stop(); if (sleepForRetries("Error starting ReplicationEndpoint", sleepMultiplier)) { sleepMultiplier++; } } } if (!this.isSourceActive()) { return; } sleepMultiplier = 1; UUID peerClusterId; // delay this until we are in an asynchronous thread for (;;) { peerClusterId = replicationEndpoint.getPeerUUID(); if (this.isSourceActive() && peerClusterId == null) { if(LOG.isDebugEnabled()) { LOG.debug("{} Could not connect to Peer ZK. Sleeping for {} millis", logPeerId(), (this.sleepForRetries * sleepMultiplier)); } if (sleepForRetries("Cannot contact the peer's zk ensemble", sleepMultiplier)) { sleepMultiplier++; } } else { break; } } if(!this.isSourceActive()) { return; } // In rare case, zookeeper setting may be messed up. That leads to the incorrect // peerClusterId value, which is the same as the source clusterId if (clusterId.equals(peerClusterId) && !replicationEndpoint.canReplicateToSameCluster()) { this.terminate("ClusterId " + clusterId + " is replicating to itself: peerClusterId " + peerClusterId + " which is not allowed by ReplicationEndpoint:" + replicationEndpoint.getClass().getName(), null, false); this.manager.removeSource(this); return; } LOG.info("{} Source: {}, is now replicating from cluster: {}; to peer cluster: {};", logPeerId(), this.replicationQueueInfo.getQueueId(), clusterId, peerClusterId); initializeWALEntryFilter(peerClusterId); // start workers for (Map.Entry<String, PriorityBlockingQueue<Path>> entry : queues.entrySet()) { String walGroupId = entry.getKey(); PriorityBlockingQueue<Path> queue = entry.getValue(); tryStartNewShipper(walGroupId, queue); } } @Override public void startup() { // mark we are running now this.sourceRunning = true; initThread = new Thread(this::initialize); Threads.setDaemonThreadRunning(initThread, Thread.currentThread().getName() + ".replicationSource," + this.queueId, this::uncaughtException); } @Override public void terminate(String reason) { terminate(reason, null); } @Override public void terminate(String reason, Exception cause) { terminate(reason, cause, true); } @Override public void terminate(String reason, Exception cause, boolean clearMetrics) { terminate(reason, cause, clearMetrics, true); } public void terminate(String reason, Exception cause, boolean clearMetrics, boolean join) { if (cause == null) { LOG.info("{} Closing source {} because: {}", logPeerId(), this.queueId, reason); } else { LOG.error("{} Closing source {} because an error occurred: {}", logPeerId(), this.queueId, reason, cause); } this.sourceRunning = false; if (initThread != null && Thread.currentThread() != initThread) { // This usually won't happen but anyway, let's wait until the initialization thread exits. // And notice that we may call terminate directly from the initThread so here we need to // avoid join on ourselves. initThread.interrupt(); Threads.shutdown(initThread, this.sleepForRetries); } Collection<ReplicationSourceShipper> workers = workerThreads.values(); for (ReplicationSourceShipper worker : workers) { worker.stopWorker(); if(worker.entryReader != null) { worker.entryReader.setReaderRunning(false); } } for (ReplicationSourceShipper worker : workers) { if (worker.isAlive() || worker.entryReader.isAlive()) { try { // Wait worker to stop Thread.sleep(this.sleepForRetries); } catch (InterruptedException e) { LOG.info("{} Interrupted while waiting {} to stop", logPeerId(), worker.getName()); Thread.currentThread().interrupt(); } // If worker still is alive after waiting, interrupt it if (worker.isAlive()) { worker.interrupt(); } // If entry reader is alive after waiting, interrupt it if (worker.entryReader.isAlive()) { worker.entryReader.interrupt(); } } } if (this.replicationEndpoint != null) { this.replicationEndpoint.stop(); } if (join) { for (ReplicationSourceShipper worker : workers) { Threads.shutdown(worker, this.sleepForRetries); LOG.info("{} ReplicationSourceWorker {} terminated", logPeerId(), worker.getName()); } if (this.replicationEndpoint != null) { try { this.replicationEndpoint.awaitTerminated(sleepForRetries * maxRetriesMultiplier, TimeUnit.MILLISECONDS); } catch (TimeoutException te) { LOG.warn("{} Got exception while waiting for endpoint to shutdown " + "for replication source : {}", logPeerId(), this.queueId, te); } } } if (clearMetrics) { this.metrics.clear(); } } @Override public String getQueueId() { return this.queueId; } @Override public Path getCurrentPath() { // only for testing for (ReplicationSourceShipper worker : workerThreads.values()) { if (worker.getCurrentPath() != null) { return worker.getCurrentPath(); } } return null; } @Override public boolean isSourceActive() { return !this.server.isStopped() && this.sourceRunning; } public UUID getPeerClusterUUID(){ return this.clusterId; } /** * Comparator used to compare logs together based on their start time */ public static class LogsComparator implements Comparator<Path> { @Override public int compare(Path o1, Path o2) { return Long.compare(getTS(o1), getTS(o2)); } /** * <p> * Split a path to get the start time * </p> * <p> * For example: 10.20.20.171%3A60020.1277499063250 * </p> * @param p path to split * @return start time */ private static long getTS(Path p) { return AbstractFSWALProvider.getWALStartTimeFromWALName(p.getName()); } } public ReplicationQueueInfo getReplicationQueueInfo() { return replicationQueueInfo; } public boolean isWorkerRunning(){ for(ReplicationSourceShipper worker : this.workerThreads.values()){ if(worker.isActive()){ return worker.isActive(); } } return false; } @Override public String getStats() { StringBuilder sb = new StringBuilder(); sb.append("Total replicated edits: ").append(totalReplicatedEdits) .append(", current progress: \n"); for (Map.Entry<String, ReplicationSourceShipper> entry : workerThreads.entrySet()) { String walGroupId = entry.getKey(); ReplicationSourceShipper worker = entry.getValue(); long position = worker.getCurrentPosition(); Path currentPath = worker.getCurrentPath(); sb.append("walGroup [").append(walGroupId).append("]: "); if (currentPath != null) { sb.append("currently replicating from: ").append(currentPath).append(" at position: ") .append(position).append("\n"); } else { sb.append("no replication ongoing, waiting for new log"); } } return sb.toString(); } @Override public MetricsSource getSourceMetrics() { return this.metrics; } @Override //offsets totalBufferUsed by deducting shipped batchSize. public void postShipEdits(List<Entry> entries, int batchSize) { if (throttler.isEnabled()) { throttler.addPushSize(batchSize); } totalReplicatedEdits.addAndGet(entries.size()); totalBufferUsed.addAndGet(-batchSize); } @Override public WALFileLengthProvider getWALFileLengthProvider() { return walFileLengthProvider; } @Override public ServerName getServerWALsBelongTo() { return server.getServerName(); } @Override public ReplicationPeer getPeer() { return replicationPeer; } Server getServer() { return server; } ReplicationQueueStorage getQueueStorage() { return queueStorage; } void removeWorker(ReplicationSourceShipper worker) { workerThreads.remove(worker.walGroupId, worker); } private String logPeerId(){ return "[Source for peer " + this.getPeer().getId() + "]:"; } }
hbase-server/src/main/java/org/apache/hadoop/hbase/replication/regionserver/ReplicationSource.java
/** * 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.replication.regionserver; import static org.apache.hadoop.hbase.wal.AbstractFSWALProvider.getArchivedLogPath; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.Server; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableDescriptors; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.regionserver.RSRpcServices; import org.apache.hadoop.hbase.regionserver.RegionServerCoprocessorHost; import org.apache.hadoop.hbase.replication.ChainWALEntryFilter; import org.apache.hadoop.hbase.replication.ClusterMarkingEntryFilter; import org.apache.hadoop.hbase.replication.ReplicationEndpoint; import org.apache.hadoop.hbase.replication.ReplicationException; import org.apache.hadoop.hbase.replication.ReplicationPeer; import org.apache.hadoop.hbase.replication.ReplicationQueueInfo; import org.apache.hadoop.hbase.replication.ReplicationQueueStorage; import org.apache.hadoop.hbase.replication.SystemTableWALEntryFilter; import org.apache.hadoop.hbase.replication.WALEntryFilter; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.hbase.wal.AbstractFSWALProvider; import org.apache.hadoop.hbase.wal.WAL.Entry; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting; import org.apache.hbase.thirdparty.com.google.common.collect.Lists; /** * Class that handles the source of a replication stream. * Currently does not handle more than 1 slave * For each slave cluster it selects a random number of peers * using a replication ratio. For example, if replication ration = 0.1 * and slave cluster has 100 region servers, 10 will be selected. * <p> * A stream is considered down when we cannot contact a region server on the * peer cluster for more than 55 seconds by default. * </p> */ @InterfaceAudience.Private public class ReplicationSource implements ReplicationSourceInterface { private static final Logger LOG = LoggerFactory.getLogger(ReplicationSource.class); // Queues of logs to process, entry in format of walGroupId->queue, // each presents a queue for one wal group private Map<String, PriorityBlockingQueue<Path>> queues = new HashMap<>(); // per group queue size, keep no more than this number of logs in each wal group protected int queueSizePerGroup; protected ReplicationQueueStorage queueStorage; protected ReplicationPeer replicationPeer; protected Configuration conf; protected ReplicationQueueInfo replicationQueueInfo; // The manager of all sources to which we ping back our progress protected ReplicationSourceManager manager; // Should we stop everything? protected Server server; // How long should we sleep for each retry private long sleepForRetries; protected FileSystem fs; // id of this cluster private UUID clusterId; // total number of edits we replicated private AtomicLong totalReplicatedEdits = new AtomicLong(0); // The znode we currently play with protected String queueId; // Maximum number of retries before taking bold actions private int maxRetriesMultiplier; // Indicates if this particular source is running private volatile boolean sourceRunning = false; // Metrics for this source private MetricsSource metrics; // WARN threshold for the number of queued logs, defaults to 2 private int logQueueWarnThreshold; // ReplicationEndpoint which will handle the actual replication private volatile ReplicationEndpoint replicationEndpoint; // A filter (or a chain of filters) for the WAL entries. protected volatile WALEntryFilter walEntryFilter; // throttler private ReplicationThrottler throttler; private long defaultBandwidth; private long currentBandwidth; private WALFileLengthProvider walFileLengthProvider; @VisibleForTesting protected final ConcurrentHashMap<String, ReplicationSourceShipper> workerThreads = new ConcurrentHashMap<>(); private AtomicLong totalBufferUsed; public static final String WAIT_ON_ENDPOINT_SECONDS = "hbase.replication.wait.on.endpoint.seconds"; public static final int DEFAULT_WAIT_ON_ENDPOINT_SECONDS = 30; private int waitOnEndpointSeconds = -1; private Thread initThread; /** * Instantiation method used by region servers * @param conf configuration to use * @param fs file system to use * @param manager replication manager to ping to * @param server the server for this region server * @param queueId the id of our replication queue * @param clusterId unique UUID for the cluster * @param metrics metrics for replication source */ @Override public void init(Configuration conf, FileSystem fs, ReplicationSourceManager manager, ReplicationQueueStorage queueStorage, ReplicationPeer replicationPeer, Server server, String queueId, UUID clusterId, WALFileLengthProvider walFileLengthProvider, MetricsSource metrics) throws IOException { this.server = server; this.conf = HBaseConfiguration.create(conf); this.waitOnEndpointSeconds = this.conf.getInt(WAIT_ON_ENDPOINT_SECONDS, DEFAULT_WAIT_ON_ENDPOINT_SECONDS); decorateConf(); this.sleepForRetries = this.conf.getLong("replication.source.sleepforretries", 1000); // 1 second this.maxRetriesMultiplier = this.conf.getInt("replication.source.maxretriesmultiplier", 300); // 5 minutes @ 1 sec per this.queueSizePerGroup = this.conf.getInt("hbase.regionserver.maxlogs", 32); this.queueStorage = queueStorage; this.replicationPeer = replicationPeer; this.manager = manager; this.fs = fs; this.metrics = metrics; this.clusterId = clusterId; this.queueId = queueId; this.replicationQueueInfo = new ReplicationQueueInfo(queueId); this.logQueueWarnThreshold = this.conf.getInt("replication.source.log.queue.warn", 2); defaultBandwidth = this.conf.getLong("replication.source.per.peer.node.bandwidth", 0); currentBandwidth = getCurrentBandwidth(); this.throttler = new ReplicationThrottler((double) currentBandwidth / 10.0); this.totalBufferUsed = manager.getTotalBufferUsed(); this.walFileLengthProvider = walFileLengthProvider; LOG.info("queueId={}, ReplicationSource: {}, currentBandwidth={}", queueId, replicationPeer.getId(), this.currentBandwidth); } private void decorateConf() { String replicationCodec = this.conf.get(HConstants.REPLICATION_CODEC_CONF_KEY); if (StringUtils.isNotEmpty(replicationCodec)) { this.conf.set(HConstants.RPC_CODEC_CONF_KEY, replicationCodec); } } @Override public void enqueueLog(Path log) { String logPrefix = AbstractFSWALProvider.getWALPrefixFromWALName(log.getName()); PriorityBlockingQueue<Path> queue = queues.get(logPrefix); if (queue == null) { queue = new PriorityBlockingQueue<>(queueSizePerGroup, new LogsComparator()); // make sure that we do not use an empty queue when setting up a ReplicationSource, otherwise // the shipper may quit immediately queue.put(log); queues.put(logPrefix, queue); if (this.isSourceActive() && this.walEntryFilter != null) { // new wal group observed after source startup, start a new worker thread to track it // notice: it's possible that log enqueued when this.running is set but worker thread // still not launched, so it's necessary to check workerThreads before start the worker tryStartNewShipper(logPrefix, queue); } } else { queue.put(log); } if (LOG.isTraceEnabled()) { LOG.trace("{} Added log file {} to queue of source {}.", logPeerId(), logPrefix, this.replicationQueueInfo.getQueueId()); } this.metrics.incrSizeOfLogQueue(); // This will log a warning for each new log that gets created above the warn threshold int queueSize = queue.size(); if (queueSize > this.logQueueWarnThreshold) { LOG.warn("{} WAL group {} queue size: {} exceeds value of " + "replication.source.log.queue.warn: {}", logPeerId(), logPrefix, queueSize, logQueueWarnThreshold); } } @Override public void addHFileRefs(TableName tableName, byte[] family, List<Pair<Path, Path>> pairs) throws ReplicationException { String peerId = replicationPeer.getId(); Map<TableName, List<String>> tableCFMap = replicationPeer.getTableCFs(); if (tableCFMap != null) { List<String> tableCfs = tableCFMap.get(tableName); if (tableCFMap.containsKey(tableName) && (tableCfs == null || tableCfs.contains(Bytes.toString(family)))) { this.queueStorage.addHFileRefs(peerId, pairs); metrics.incrSizeOfHFileRefsQueue(pairs.size()); } else { LOG.debug("HFiles will not be replicated belonging to the table {} family {} to peer id {}", tableName, Bytes.toString(family), peerId); } } else { // user has explicitly not defined any table cfs for replication, means replicate all the // data this.queueStorage.addHFileRefs(peerId, pairs); metrics.incrSizeOfHFileRefsQueue(pairs.size()); } } private ReplicationEndpoint createReplicationEndpoint() throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException { RegionServerCoprocessorHost rsServerHost = null; if (server instanceof HRegionServer) { rsServerHost = ((HRegionServer) server).getRegionServerCoprocessorHost(); } String replicationEndpointImpl = replicationPeer.getPeerConfig().getReplicationEndpointImpl(); ReplicationEndpoint replicationEndpoint; if (replicationEndpointImpl == null) { // Default to HBase inter-cluster replication endpoint; skip reflection replicationEndpoint = new HBaseInterClusterReplicationEndpoint(); } else { try { replicationEndpoint = Class.forName(replicationEndpointImpl) .asSubclass(ReplicationEndpoint.class) .getDeclaredConstructor() .newInstance(); } catch (NoSuchMethodException | InvocationTargetException e) { throw new IllegalArgumentException(e); } } if (rsServerHost != null) { ReplicationEndpoint newReplicationEndPoint = rsServerHost.postCreateReplicationEndPoint(replicationEndpoint); if (newReplicationEndPoint != null) { // Override the newly created endpoint from the hook with configured end point replicationEndpoint = newReplicationEndPoint; } } return replicationEndpoint; } private void initAndStartReplicationEndpoint(ReplicationEndpoint replicationEndpoint) throws IOException, TimeoutException { TableDescriptors tableDescriptors = null; if (server instanceof HRegionServer) { tableDescriptors = ((HRegionServer) server).getTableDescriptors(); } replicationEndpoint .init(new ReplicationEndpoint.Context(server, conf, replicationPeer.getConfiguration(), fs, replicationPeer.getId(), clusterId, replicationPeer, metrics, tableDescriptors, server)); replicationEndpoint.start(); replicationEndpoint.awaitRunning(waitOnEndpointSeconds, TimeUnit.SECONDS); } private void initializeWALEntryFilter(UUID peerClusterId) { // get the WALEntryFilter from ReplicationEndpoint and add it to default filters ArrayList<WALEntryFilter> filters = Lists.<WALEntryFilter> newArrayList(new SystemTableWALEntryFilter()); WALEntryFilter filterFromEndpoint = this.replicationEndpoint.getWALEntryfilter(); if (filterFromEndpoint != null) { filters.add(filterFromEndpoint); } filters.add(new ClusterMarkingEntryFilter(clusterId, peerClusterId, replicationEndpoint)); this.walEntryFilter = new ChainWALEntryFilter(filters); } private void tryStartNewShipper(String walGroupId, PriorityBlockingQueue<Path> queue) { ReplicationSourceShipper worker = createNewShipper(walGroupId, queue); ReplicationSourceShipper extant = workerThreads.putIfAbsent(walGroupId, worker); if (extant != null) { if(LOG.isDebugEnabled()) { LOG.debug("{} Someone has beat us to start a worker thread for wal group {}", logPeerId(), walGroupId); } } else { if(LOG.isDebugEnabled()) { LOG.debug("{} Starting up worker for wal group {}", logPeerId(), walGroupId); } ReplicationSourceWALReader walReader = createNewWALReader(walGroupId, queue, worker.getStartPosition()); Threads.setDaemonThreadRunning(walReader, Thread.currentThread().getName() + ".replicationSource.wal-reader." + walGroupId + "," + queueId, this::uncaughtException); worker.setWALReader(walReader); worker.startup(this::uncaughtException); } } @Override public Map<String, ReplicationStatus> getWalGroupStatus() { Map<String, ReplicationStatus> sourceReplicationStatus = new TreeMap<>(); long ageOfLastShippedOp, replicationDelay, fileSize; for (Map.Entry<String, ReplicationSourceShipper> walGroupShipper : workerThreads.entrySet()) { String walGroupId = walGroupShipper.getKey(); ReplicationSourceShipper shipper = walGroupShipper.getValue(); ageOfLastShippedOp = metrics.getAgeofLastShippedOp(walGroupId); int queueSize = queues.get(walGroupId).size(); replicationDelay = metrics.getReplicationDelay(); Path currentPath = shipper.getCurrentPath(); fileSize = -1; if (currentPath != null) { try { fileSize = getFileSize(currentPath); } catch (IOException e) { LOG.warn("Ignore the exception as the file size of HLog only affects the web ui", e); } } else { currentPath = new Path("NO_LOGS_IN_QUEUE"); LOG.warn("{} No replication ongoing, waiting for new log", logPeerId()); } ReplicationStatus.ReplicationStatusBuilder statusBuilder = ReplicationStatus.newBuilder(); statusBuilder.withPeerId(this.getPeerId()) .withQueueSize(queueSize) .withWalGroup(walGroupId) .withCurrentPath(currentPath) .withCurrentPosition(shipper.getCurrentPosition()) .withFileSize(fileSize) .withAgeOfLastShippedOp(ageOfLastShippedOp) .withReplicationDelay(replicationDelay); sourceReplicationStatus.put(this.getPeerId() + "=>" + walGroupId, statusBuilder.build()); } return sourceReplicationStatus; } private long getFileSize(Path currentPath) throws IOException { long fileSize; try { fileSize = fs.getContentSummary(currentPath).getLength(); } catch (FileNotFoundException e) { currentPath = getArchivedLogPath(currentPath, conf); fileSize = fs.getContentSummary(currentPath).getLength(); } return fileSize; } protected ReplicationSourceShipper createNewShipper(String walGroupId, PriorityBlockingQueue<Path> queue) { return new ReplicationSourceShipper(conf, walGroupId, queue, this); } private ReplicationSourceWALReader createNewWALReader(String walGroupId, PriorityBlockingQueue<Path> queue, long startPosition) { return replicationPeer.getPeerConfig().isSerial() ? new SerialReplicationSourceWALReader(fs, conf, queue, startPosition, walEntryFilter, this) : new ReplicationSourceWALReader(fs, conf, queue, startPosition, walEntryFilter, this); } protected final void uncaughtException(Thread t, Throwable e) { RSRpcServices.exitIfOOME(e); LOG.error("Unexpected exception in {} currentPath={}", t.getName(), getCurrentPath(), e); server.abort("Unexpected exception in " + t.getName(), e); } @Override public ReplicationEndpoint getReplicationEndpoint() { return this.replicationEndpoint; } @Override public ReplicationSourceManager getSourceManager() { return this.manager; } @Override public void tryThrottle(int batchSize) throws InterruptedException { checkBandwidthChangeAndResetThrottler(); if (throttler.isEnabled()) { long sleepTicks = throttler.getNextSleepInterval(batchSize); if (sleepTicks > 0) { if (LOG.isTraceEnabled()) { LOG.trace("{} To sleep {}ms for throttling control", logPeerId(), sleepTicks); } Thread.sleep(sleepTicks); // reset throttler's cycle start tick when sleep for throttling occurs throttler.resetStartTick(); } } } private void checkBandwidthChangeAndResetThrottler() { long peerBandwidth = getCurrentBandwidth(); if (peerBandwidth != currentBandwidth) { currentBandwidth = peerBandwidth; throttler.setBandwidth((double) currentBandwidth / 10.0); LOG.info("ReplicationSource : {} bandwidth throttling changed, currentBandWidth={}", replicationPeer.getId(), currentBandwidth); } } private long getCurrentBandwidth() { long peerBandwidth = replicationPeer.getPeerBandwidth(); // user can set peer bandwidth to 0 to use default bandwidth return peerBandwidth != 0 ? peerBandwidth : defaultBandwidth; } /** * Do the sleeping logic * @param msg Why we sleep * @param sleepMultiplier by how many times the default sleeping time is augmented * @return True if <code>sleepMultiplier</code> is &lt; <code>maxRetriesMultiplier</code> */ protected boolean sleepForRetries(String msg, int sleepMultiplier) { try { if (LOG.isTraceEnabled()) { LOG.trace("{} {}, sleeping {} times {}", logPeerId(), msg, sleepForRetries, sleepMultiplier); } Thread.sleep(this.sleepForRetries * sleepMultiplier); } catch (InterruptedException e) { if(LOG.isDebugEnabled()) { LOG.debug("{} Interrupted while sleeping between retries", logPeerId()); } Thread.currentThread().interrupt(); } return sleepMultiplier < maxRetriesMultiplier; } private void initialize() { int sleepMultiplier = 1; while (this.isSourceActive()) { ReplicationEndpoint replicationEndpoint; try { replicationEndpoint = createReplicationEndpoint(); } catch (Exception e) { LOG.warn("{} error creating ReplicationEndpoint, retry", logPeerId(), e); if (sleepForRetries("Error creating ReplicationEndpoint", sleepMultiplier)) { sleepMultiplier++; } continue; } try { initAndStartReplicationEndpoint(replicationEndpoint); this.replicationEndpoint = replicationEndpoint; break; } catch (Exception e) { LOG.warn("{} Error starting ReplicationEndpoint, retry", logPeerId(), e); replicationEndpoint.stop(); if (sleepForRetries("Error starting ReplicationEndpoint", sleepMultiplier)) { sleepMultiplier++; } } } if (!this.isSourceActive()) { return; } sleepMultiplier = 1; UUID peerClusterId; // delay this until we are in an asynchronous thread for (;;) { peerClusterId = replicationEndpoint.getPeerUUID(); if (this.isSourceActive() && peerClusterId == null) { if(LOG.isDebugEnabled()) { LOG.debug("{} Could not connect to Peer ZK. Sleeping for {} millis", logPeerId(), (this.sleepForRetries * sleepMultiplier)); } if (sleepForRetries("Cannot contact the peer's zk ensemble", sleepMultiplier)) { sleepMultiplier++; } } else { break; } } if(!this.isSourceActive()) { return; } // In rare case, zookeeper setting may be messed up. That leads to the incorrect // peerClusterId value, which is the same as the source clusterId if (clusterId.equals(peerClusterId) && !replicationEndpoint.canReplicateToSameCluster()) { this.terminate("ClusterId " + clusterId + " is replicating to itself: peerClusterId " + peerClusterId + " which is not allowed by ReplicationEndpoint:" + replicationEndpoint.getClass().getName(), null, false); this.manager.removeSource(this); return; } LOG.info("{} Source: {}, is now replicating from cluster: {}; to peer cluster: {};", logPeerId(), this.replicationQueueInfo.getQueueId(), clusterId, peerClusterId); initializeWALEntryFilter(peerClusterId); // start workers for (Map.Entry<String, PriorityBlockingQueue<Path>> entry : queues.entrySet()) { String walGroupId = entry.getKey(); PriorityBlockingQueue<Path> queue = entry.getValue(); tryStartNewShipper(walGroupId, queue); } } @Override public void startup() { // mark we are running now this.sourceRunning = true; initThread = new Thread(this::initialize); Threads.setDaemonThreadRunning(initThread, Thread.currentThread().getName() + ".replicationSource," + this.queueId, this::uncaughtException); } @Override public void terminate(String reason) { terminate(reason, null); } @Override public void terminate(String reason, Exception cause) { terminate(reason, cause, true); } @Override public void terminate(String reason, Exception cause, boolean clearMetrics) { terminate(reason, cause, clearMetrics, true); } public void terminate(String reason, Exception cause, boolean clearMetrics, boolean join) { if (cause == null) { LOG.info("{} Closing source {} because: {}", logPeerId(), this.queueId, reason); } else { LOG.error("{} Closing source {} because an error occurred: {}", logPeerId(), this.queueId, reason, cause); } this.sourceRunning = false; if (initThread != null && Thread.currentThread() != initThread) { // This usually won't happen but anyway, let's wait until the initialization thread exits. // And notice that we may call terminate directly from the initThread so here we need to // avoid join on ourselves. initThread.interrupt(); Threads.shutdown(initThread, this.sleepForRetries); } Collection<ReplicationSourceShipper> workers = workerThreads.values(); for (ReplicationSourceShipper worker : workers) { worker.stopWorker(); if(worker.entryReader != null) { worker.entryReader.setReaderRunning(false); } } for (ReplicationSourceShipper worker : workers) { if (worker.isAlive() || worker.entryReader.isAlive()) { try { // Wait worker to stop Thread.sleep(this.sleepForRetries); } catch (InterruptedException e) { LOG.info("{} Interrupted while waiting {} to stop", logPeerId(), worker.getName()); Thread.currentThread().interrupt(); } // If worker still is alive after waiting, interrupt it if (worker.isAlive()) { worker.interrupt(); } // If entry reader is alive after waiting, interrupt it if (worker.entryReader.isAlive()) { worker.entryReader.interrupt(); } } } if (this.replicationEndpoint != null) { this.replicationEndpoint.stop(); } if (clearMetrics) { metrics.clear(); } if (join) { for (ReplicationSourceShipper worker : workers) { Threads.shutdown(worker, this.sleepForRetries); LOG.info("{} ReplicationSourceWorker {} terminated", logPeerId(), worker.getName()); } if (this.replicationEndpoint != null) { try { this.replicationEndpoint.awaitTerminated(sleepForRetries * maxRetriesMultiplier, TimeUnit.MILLISECONDS); } catch (TimeoutException te) { LOG.warn("{} Got exception while waiting for endpoint to shutdown " + "for replication source : {}", logPeerId(), this.queueId, te); } } } if (clearMetrics) { this.metrics.clear(); } } @Override public String getQueueId() { return this.queueId; } @Override public Path getCurrentPath() { // only for testing for (ReplicationSourceShipper worker : workerThreads.values()) { if (worker.getCurrentPath() != null) { return worker.getCurrentPath(); } } return null; } @Override public boolean isSourceActive() { return !this.server.isStopped() && this.sourceRunning; } public UUID getPeerClusterUUID(){ return this.clusterId; } /** * Comparator used to compare logs together based on their start time */ public static class LogsComparator implements Comparator<Path> { @Override public int compare(Path o1, Path o2) { return Long.compare(getTS(o1), getTS(o2)); } /** * <p> * Split a path to get the start time * </p> * <p> * For example: 10.20.20.171%3A60020.1277499063250 * </p> * @param p path to split * @return start time */ private static long getTS(Path p) { return AbstractFSWALProvider.getWALStartTimeFromWALName(p.getName()); } } public ReplicationQueueInfo getReplicationQueueInfo() { return replicationQueueInfo; } public boolean isWorkerRunning(){ for(ReplicationSourceShipper worker : this.workerThreads.values()){ if(worker.isActive()){ return worker.isActive(); } } return false; } @Override public String getStats() { StringBuilder sb = new StringBuilder(); sb.append("Total replicated edits: ").append(totalReplicatedEdits) .append(", current progress: \n"); for (Map.Entry<String, ReplicationSourceShipper> entry : workerThreads.entrySet()) { String walGroupId = entry.getKey(); ReplicationSourceShipper worker = entry.getValue(); long position = worker.getCurrentPosition(); Path currentPath = worker.getCurrentPath(); sb.append("walGroup [").append(walGroupId).append("]: "); if (currentPath != null) { sb.append("currently replicating from: ").append(currentPath).append(" at position: ") .append(position).append("\n"); } else { sb.append("no replication ongoing, waiting for new log"); } } return sb.toString(); } @Override public MetricsSource getSourceMetrics() { return this.metrics; } @Override //offsets totalBufferUsed by deducting shipped batchSize. public void postShipEdits(List<Entry> entries, int batchSize) { if (throttler.isEnabled()) { throttler.addPushSize(batchSize); } totalReplicatedEdits.addAndGet(entries.size()); totalBufferUsed.addAndGet(-batchSize); } @Override public WALFileLengthProvider getWALFileLengthProvider() { return walFileLengthProvider; } @Override public ServerName getServerWALsBelongTo() { return server.getServerName(); } @Override public ReplicationPeer getPeer() { return replicationPeer; } Server getServer() { return server; } ReplicationQueueStorage getQueueStorage() { return queueStorage; } void removeWorker(ReplicationSourceShipper worker) { workerThreads.remove(worker.walGroupId, worker); } private String logPeerId(){ return "[Source for peer " + this.getPeer().getId() + "]:"; } }
HBASE-23231 Addendum remove redundant metrics.clear in ReplicationSource This is only a problem on master which was introduced when we merge sync replication feature branch back
hbase-server/src/main/java/org/apache/hadoop/hbase/replication/regionserver/ReplicationSource.java
HBASE-23231 Addendum remove redundant metrics.clear in ReplicationSource
Java
apache-2.0
deb384f82664eeb64fbf0bfc0c96cf9decf4af1f
0
svn2github/openid4java,LeifWarner/openid4java,janrain/openid4java,LeifWarner/openid4java,janrain/openid4java
/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.html.dom.HTMLDocumentImpl; import org.openid4java.OpenIDException; import org.openid4java.discovery.yadis.YadisException; import org.openid4java.discovery.yadis.YadisHtmlParser; import org.openid4java.discovery.yadis.YadisResolver; import org.w3c.dom.NodeList; import org.w3c.dom.html.HTMLHeadElement; import org.w3c.dom.html.HTMLMetaElement; /** * A {@link org.openid4java.discovery.yadis.YadisHtmlParser} implementation using the DOMParser of CyberNeko HTML. * * @author Sutra Zhou * @since 0.9.4 * @see OpenID4JavaDOMParser */ public class CyberNekoDOMYadisHtmlParser implements YadisHtmlParser { private static final Log _log = LogFactory.getLog(CyberNekoDOMYadisHtmlParser.class); private static final boolean DEBUG = _log.isDebugEnabled(); /* * (non-Javadoc) * * @see org.openid4java.discovery.yadis.YadisParser#getHtmlMeta(java.lang.String) */ public String getHtmlMeta(String input) throws YadisException { String xrdsLocation = null; HTMLDocumentImpl doc = this.parseDocument(input); if (DEBUG) { _log.debug("document:\n" + OpenID4JavaDOMParser.toXmlString(doc)); } NodeList heads = doc.getElementsByTagName("head"); if (heads.getLength() != 1) throw new YadisException( "HTML response must have exactly one HEAD element, " + "found " + heads.getLength() + " : " + heads.toString(), OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); HTMLHeadElement head = (HTMLHeadElement) doc.getHead(); NodeList metaElements = head.getElementsByTagName("META"); if (metaElements == null || metaElements.getLength() == 0) { if (DEBUG) _log.debug("No <meta> element found under <html><head>. " + "See Yadis specification, section 6.2.5/1."); } else { for (int i = 0, len = metaElements.getLength(); i < len; i++) { HTMLMetaElement metaElement = (HTMLMetaElement) metaElements.item(i); String httpEquiv = metaElement.getHttpEquiv(); if (YadisResolver.YADIS_XRDS_LOCATION.equalsIgnoreCase(httpEquiv)) { if (xrdsLocation != null) throw new YadisException( "More than one " + YadisResolver.YADIS_XRDS_LOCATION + "META tags found in HEAD: " + head.toString(), OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); xrdsLocation = metaElement.getContent(); if (DEBUG) _log.debug("Found " + YadisResolver.YADIS_XRDS_LOCATION + " META tags."); } } } return xrdsLocation; } private HTMLDocumentImpl parseDocument(String htmlData) throws YadisException { OpenID4JavaDOMParser parser = new OpenID4JavaDOMParser(); try { parser.parse(OpenID4JavaDOMParser.createInputSource(htmlData)); } catch (Exception e) { throw new YadisException("Error parsing HTML message", OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE, e); } if (parser.isIgnoredHeadStartElement()) { throw new YadisException("HTML response must have exactly one HEAD element.", OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); } return (HTMLDocumentImpl) parser.getDocument(); } }
src/org/openid4java/util/CyberNekoDOMYadisHtmlParser.java
/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.html.dom.HTMLDocumentImpl; import org.openid4java.OpenIDException; import org.openid4java.discovery.yadis.YadisException; import org.openid4java.discovery.yadis.YadisHtmlParser; import org.openid4java.discovery.yadis.YadisResolver; import org.w3c.dom.NodeList; import org.w3c.dom.html.HTMLHeadElement; import org.w3c.dom.html.HTMLMetaElement; /** * A {@link org.openid4java.discovery.yadis.YadisHtmlParser} implementation using the DOMParser of CyberNeko HTML. * * @author Sutra Zhou * @since 0.9.4 * @see OpenID4JavaDOMParser */ public class CyberNekoDOMYadisHtmlParser implements YadisHtmlParser { private static final Log _log = LogFactory.getLog(CyberNekoDOMYadisHtmlParser.class); private static final boolean DEBUG = _log.isDebugEnabled(); /* * (non-Javadoc) * * @see org.openid4java.discovery.yadis.YadisParser#getHtmlMeta(java.lang.String) */ public String getHtmlMeta(String input) throws YadisException { String xrdsLocation = null; HTMLDocumentImpl doc = this.parseDocument(input); if (DEBUG) { _log.debug("document:\n" + OpenID4JavaDOMParser.toXmlString(doc)); } NodeList heads = doc.getElementsByTagName("head"); if (heads.getLength() != 1) throw new YadisException( "HTML response must have exactly one HEAD element, " + "found " + heads.getLength() + " : " + heads.toString(), OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); HTMLHeadElement head = (HTMLHeadElement) doc.getHead(); NodeList metaElements = head.getElementsByTagName("META"); if (metaElements == null || metaElements.getLength() == 0) { throw new YadisException( "No <meta> element found under <html><head>. " + "See Yadis specification, section 6.2.5/1.", OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); } for (int i = 0, len = metaElements.getLength(); i < len; i++) { HTMLMetaElement metaElement = (HTMLMetaElement) metaElements.item(i); String httpEquiv = metaElement.getHttpEquiv(); if (YadisResolver.YADIS_XRDS_LOCATION.equalsIgnoreCase(httpEquiv)) { if (xrdsLocation != null) throw new YadisException( "More than one " + YadisResolver.YADIS_XRDS_LOCATION + "META tags found in HEAD: " + head.toString(), OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); xrdsLocation = metaElement.getContent(); if (DEBUG) _log.debug("Found " + YadisResolver.YADIS_XRDS_LOCATION + "META tags."); } } return xrdsLocation; } private HTMLDocumentImpl parseDocument(String htmlData) throws YadisException { OpenID4JavaDOMParser parser = new OpenID4JavaDOMParser(); try { parser.parse(OpenID4JavaDOMParser.createInputSource(htmlData)); } catch (Exception e) { throw new YadisException("Error parsing HTML message", OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE, e); } if (parser.isIgnoredHeadStartElement()) { throw new YadisException("HTML response must have exactly one HEAD element.", OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); } return (HTMLDocumentImpl) parser.getDocument(); } }
Updated YadisHtmlParser - missed in a previous commit. git-svn-id: 04d5f425e1afaf15ebdf27760bf69bd4e651a03a@549 0ddc078c-3e21-0410-a0b4-493e83258d60
src/org/openid4java/util/CyberNekoDOMYadisHtmlParser.java
Updated YadisHtmlParser - missed in a previous commit.
Java
apache-2.0
e774b22d7e6aa3774e1a76389fa56cdbf15e9a7c
0
apache/commons-jexl,apache/commons-jexl,apache/commons-jexl
/* * 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.commons.jexl; import java.util.Map; import java.math.BigDecimal; import java.math.BigInteger; import org.apache.commons.jexl.junit.Asserter; public class ArithmeticTest extends JexlTestCase { private Asserter asserter; @Override public void setUp() { asserter = new Asserter(JEXL); } public void testBigDecimal() throws Exception { asserter.setVariable("left", new BigDecimal(2)); asserter.setVariable("right", new BigDecimal(6)); asserter.assertExpression("left + right", new BigDecimal(8)); asserter.assertExpression("right - left", new BigDecimal(4)); asserter.assertExpression("right * left", new BigDecimal(12)); asserter.assertExpression("right / left", new BigDecimal(3)); asserter.assertExpression("right % left", new BigDecimal(0)); } public void testBigInteger() throws Exception { asserter.setVariable("left", new BigInteger("2")); asserter.setVariable("right", new BigInteger("6")); asserter.assertExpression("left + right", new BigInteger("8")); asserter.assertExpression("right - left", new BigInteger("4")); asserter.assertExpression("right * left", new BigInteger("12")); asserter.assertExpression("right / left", new BigInteger("3")); asserter.assertExpression("right % left", new BigInteger("0")); } /** * test some simple mathematical calculations */ public void testUnaryMinus() throws Exception { asserter.setVariable("aByte", new Byte((byte) 1)); asserter.setVariable("aShort", new Short((short) 2)); asserter.setVariable("anInteger", new Integer(3)); asserter.setVariable("aLong", new Long(4)); asserter.setVariable("aFloat", new Float(5.5)); asserter.setVariable("aDouble", new Double(6.6)); asserter.setVariable("aBigInteger", new BigInteger("7")); asserter.setVariable("aBigDecimal", new BigDecimal("8.8")); asserter.assertExpression("-3", new Integer("-3")); asserter.assertExpression("-3.0", new Float("-3.0")); asserter.assertExpression("-aByte", new Byte((byte) -1)); asserter.assertExpression("-aShort", new Short((short) -2)); asserter.assertExpression("-anInteger", new Integer(-3)); asserter.assertExpression("-aLong", new Long(-4)); asserter.assertExpression("-aFloat", new Float(-5.5)); asserter.assertExpression("-aDouble", new Double(-6.6)); asserter.assertExpression("-aBigInteger", new BigInteger("-7")); asserter.assertExpression("-aBigDecimal", new BigDecimal("-8.8")); } /** * test some simple mathematical calculations */ public void testCalculations() throws Exception { asserter.setVariable("foo", new Integer(2)); asserter.assertExpression("foo + 2", new Integer(4)); asserter.assertExpression("3 + 3", new Integer(6)); asserter.assertExpression("3 + 3 + foo", new Integer(8)); asserter.assertExpression("3 * 3", new Integer(9)); asserter.assertExpression("3 * 3 + foo", new Integer(11)); asserter.assertExpression("3 * 3 - foo", new Integer(7)); /* * test parenthesized exprs */ asserter.assertExpression("(4 + 3) * 6", new Integer(42)); asserter.assertExpression("(8 - 2) * 7", new Integer(42)); /* * test some floaty stuff */ asserter.assertExpression("3 * \"3.0\"", new Double(9)); asserter.assertExpression("3 * 3.0", new Double(9)); /* * test / and % */ asserter.assertExpression("6 / 3", new Integer(6 / 3)); asserter.assertExpression("6.4 / 3", new Double(6.4 / 3)); asserter.assertExpression("0 / 3", new Integer(0 / 3)); asserter.assertExpression("3 / 0", new Double(0)); asserter.assertExpression("4 % 3", new Integer(1)); asserter.assertExpression("4.8 % 3", new Double(4.8 % 3)); /* * test new null coersion */ asserter.setVariable("imanull", null); asserter.assertExpression("imanull + 2", new Integer(2)); asserter.assertExpression("imanull + imanull", new Integer(0)); } public void testCoercions() throws Exception { asserter.assertExpression("1", new Integer(1)); // numerics default to Integer // asserter.assertExpression("5L", new Long(5)); // TODO when implemented asserter.setVariable("I2", new Integer(2)); asserter.setVariable("L2", new Long(2)); asserter.setVariable("L3", new Long(3)); asserter.setVariable("B10", BigInteger.TEN); // Integer & Integer => Integer asserter.assertExpression("I2 + 2", new Integer(4)); asserter.assertExpression("I2 * 2", new Integer(4)); asserter.assertExpression("I2 - 2", new Integer(0)); asserter.assertExpression("I2 / 2", new Integer(1)); // Integer & Long => Long asserter.assertExpression("I2 * L2", new Long(4)); asserter.assertExpression("I2 / L2", new Long(1)); // Long & Long => Long asserter.assertExpression("L2 + 3", new Long(5)); asserter.assertExpression("L2 + L3", new Long(5)); asserter.assertExpression("L2 / L2", new Long(1)); asserter.assertExpression("L2 / 2", new Long(1)); // BigInteger asserter.assertExpression("B10 / 10", BigInteger.ONE); asserter.assertExpression("B10 / I2", new BigInteger("5")); asserter.assertExpression("B10 / L2", new BigInteger("5")); } /** * * if silent, all arith exception return 0.0 * if not silent, all arith exception throw * @throws Exception */ public void testDivideByZero() throws Exception { JexlContext context = JexlHelper.createContext(); Map<String, Object> vars = context.getVars(); vars.put("aByte", new Byte((byte) 1)); vars.put("aShort", new Short((short) 2)); vars.put("aInteger", new Integer(3)); vars.put("aLong", new Long(4)); vars.put("aFloat", new Float(5.5)); vars.put("aDouble", new Double(6.6)); vars.put("aBigInteger", new BigInteger("7")); vars.put("aBigDecimal", new BigDecimal("8.8")); vars.put("zByte", new Byte((byte) 0)); vars.put("zShort", new Short((short) 0)); vars.put("zInteger", new Integer(0)); vars.put("zLong", new Long(0)); vars.put("zFloat", new Float(0)); vars.put("zDouble", new Double(0)); vars.put("zBigInteger", new BigInteger("0")); vars.put("zBigDecimal", new BigDecimal("0")); String[] tnames = { "Byte", "Short", "Integer", "Long", "Float", "Double", "BigInteger", "BigDecimal" }; // number of permutations this will generate final int PERMS = tnames.length * tnames.length; JexlEngine jexl = new JexlEngine(); jexl.setCache(128); jexl.setSilent(false); // for non-silent, silent... for (int s = 0; s < 2; ++s) { jexl.setLenient(s == 0); int zthrow = 0; int zeval = 0; // for vars of all types... for (String vname : tnames) { // for zeros of all types... for (String zname : tnames) { // divide var by zero String expr = "a" + vname + " / " + "z" + zname; try { Expression zexpr = jexl.createExpression(expr); Object nan = zexpr.evaluate(context); // check we have a zero & incremement zero count if (nan instanceof Number) { double zero = ((Number) nan).doubleValue(); if (zero == 0.0) zeval += 1; } } catch (Exception any) { // increment the exception count zthrow += 1; } } } if (!jexl.isLenient()) assertTrue("All expressions should have thrown " + zthrow + "/" + PERMS, zthrow == PERMS); else assertTrue("All expressions should have zeroed " + zeval + "/" + PERMS, zeval == PERMS); } debuggerCheck(jexl); } }
src/test/java/org/apache/commons/jexl/ArithmeticTest.java
/* * 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.commons.jexl; import java.util.Map; import java.math.BigDecimal; import java.math.BigInteger; import org.apache.commons.jexl.junit.Asserter; public class ArithmeticTest extends JexlTestCase { private Asserter asserter; @Override public void setUp() { asserter = new Asserter(JEXL); } public void testBigDecimal() throws Exception { asserter.setVariable("left", new BigDecimal(2)); asserter.setVariable("right", new BigDecimal(6)); asserter.assertExpression("left + right", new BigDecimal(8)); asserter.assertExpression("right - left", new BigDecimal(4)); asserter.assertExpression("right * left", new BigDecimal(12)); asserter.assertExpression("right / left", new BigDecimal(3)); asserter.assertExpression("right % left", new BigDecimal(0)); } public void testBigInteger() throws Exception { asserter.setVariable("left", new BigInteger("2")); asserter.setVariable("right", new BigInteger("6")); asserter.assertExpression("left + right", new BigInteger("8")); asserter.assertExpression("right - left", new BigInteger("4")); asserter.assertExpression("right * left", new BigInteger("12")); asserter.assertExpression("right / left", new BigInteger("3")); asserter.assertExpression("right % left", new BigInteger("0")); } /** * test some simple mathematical calculations */ public void testUnaryMinus() throws Exception { asserter.setVariable("aByte", new Byte((byte) 1)); asserter.setVariable("aShort", new Short((short) 2)); asserter.setVariable("anInteger", new Integer(3)); asserter.setVariable("aLong", new Long(4)); asserter.setVariable("aFloat", new Float(5.5)); asserter.setVariable("aDouble", new Double(6.6)); asserter.setVariable("aBigInteger", new BigInteger("7")); asserter.setVariable("aBigDecimal", new BigDecimal("8.8")); asserter.assertExpression("-3", new Integer("-3")); asserter.assertExpression("-3.0", new Float("-3.0")); asserter.assertExpression("-aByte", new Byte((byte) -1)); asserter.assertExpression("-aShort", new Short((short) -2)); asserter.assertExpression("-anInteger", new Integer(-3)); asserter.assertExpression("-aLong", new Long(-4)); asserter.assertExpression("-aFloat", new Float(-5.5)); asserter.assertExpression("-aDouble", new Double(-6.6)); asserter.assertExpression("-aBigInteger", new BigInteger("-7")); asserter.assertExpression("-aBigDecimal", new BigDecimal("-8.8")); } /** * test some simple mathematical calculations */ public void testCalculations() throws Exception { asserter.setVariable("foo", new Integer(2)); asserter.assertExpression("foo + 2", new Integer(4)); asserter.assertExpression("3 + 3", new Integer(6)); asserter.assertExpression("3 + 3 + foo", new Integer(8)); asserter.assertExpression("3 * 3", new Integer(9)); asserter.assertExpression("3 * 3 + foo", new Integer(11)); asserter.assertExpression("3 * 3 - foo", new Integer(7)); /* * test parenthesized exprs */ asserter.assertExpression("(4 + 3) * 6", new Integer(42)); asserter.assertExpression("(8 - 2) * 7", new Integer(42)); /* * test some floaty stuff */ asserter.assertExpression("3 * \"3.0\"", new Double(9)); asserter.assertExpression("3 * 3.0", new Double(9)); /* * test / and % */ asserter.assertExpression("6 / 3", new Integer(6 / 3)); asserter.assertExpression("6.4 / 3", new Double(6.4 / 3)); asserter.assertExpression("0 / 3", new Integer(0 / 3)); asserter.assertExpression("3 / 0", new Double(0)); asserter.assertExpression("4 % 3", new Integer(1)); asserter.assertExpression("4.8 % 3", new Double(4.8 % 3)); /* * test new null coersion */ asserter.setVariable("imanull", null); asserter.assertExpression("imanull + 2", new Integer(2)); asserter.assertExpression("imanull + imanull", new Integer(0)); } /** * * if silent, all arith exception return 0.0 * if not silent, all arith exception throw * @throws Exception */ public void testDivideByZero() throws Exception { JexlContext context = JexlHelper.createContext(); Map<String, Object> vars = context.getVars(); vars.put("aByte", new Byte((byte) 1)); vars.put("aShort", new Short((short) 2)); vars.put("aInteger", new Integer(3)); vars.put("aLong", new Long(4)); vars.put("aFloat", new Float(5.5)); vars.put("aDouble", new Double(6.6)); vars.put("aBigInteger", new BigInteger("7")); vars.put("aBigDecimal", new BigDecimal("8.8")); vars.put("zByte", new Byte((byte) 0)); vars.put("zShort", new Short((short) 0)); vars.put("zInteger", new Integer(0)); vars.put("zLong", new Long(0)); vars.put("zFloat", new Float(0)); vars.put("zDouble", new Double(0)); vars.put("zBigInteger", new BigInteger("0")); vars.put("zBigDecimal", new BigDecimal("0")); String[] tnames = { "Byte", "Short", "Integer", "Long", "Float", "Double", "BigInteger", "BigDecimal" }; // number of permutations this will generate final int PERMS = tnames.length * tnames.length; JexlEngine jexl = new JexlEngine(); jexl.setCache(128); jexl.setSilent(false); // for non-silent, silent... for (int s = 0; s < 2; ++s) { jexl.setLenient(s == 0); int zthrow = 0; int zeval = 0; // for vars of all types... for (String vname : tnames) { // for zeros of all types... for (String zname : tnames) { // divide var by zero String expr = "a" + vname + " / " + "z" + zname; try { Expression zexpr = jexl.createExpression(expr); Object nan = zexpr.evaluate(context); // check we have a zero & incremement zero count if (nan instanceof Number) { double zero = ((Number) nan).doubleValue(); if (zero == 0.0) zeval += 1; } } catch (Exception any) { // increment the exception count zthrow += 1; } } } if (!jexl.isLenient()) assertTrue("All expressions should have thrown " + zthrow + "/" + PERMS, zthrow == PERMS); else assertTrue("All expressions should have zeroed " + zeval + "/" + PERMS, zeval == PERMS); } debuggerCheck(jexl); } }
Add some coercion tests git-svn-id: 4652571f3dffef9654f8145d6bccf468f90ae391@814694 13f79535-47bb-0310-9956-ffa450edef68
src/test/java/org/apache/commons/jexl/ArithmeticTest.java
Add some coercion tests
Java
apache-2.0
a2a26f8c7a92ffabd6e2183a440fefe70491c590
0
henrichg/PhoneProfilesPlus
package sk.henrichg.phoneprofilesplus; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.PowerManager; /** * Handles broadcasts related to SIM card state changes. * <p> * Possible states that are received here are: * <p> * Documented: * ABSENT * NETWORK_LOCKED * PIN_REQUIRED * PUK_REQUIRED * READY * UNKNOWN * <p> * Undocumented: * NOT_READY (ICC interface is not ready, e.g. radio is off or powering on) * CARD_IO_ERROR (three consecutive times there was a SIM IO error) * IMSI (ICC IMSI is ready in property) * LOADED (all ICC records, including IMSI, are loaded) * <p> * Note: some of these are not documented in * https://developer.android.com/reference/android/telephony/TelephonyManager.html * but they can be found deeper in the source code, namely in com.android.internal.telephony.IccCardConstants. */ public class SimStateChangedBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // PPApplication.logE("[IN_BROADCAST] SimStateChangedBroadcastReceiver.onReceive", "xxx"); if (intent == null) return; final Context appContext = context.getApplicationContext(); //final Intent _intent = intent; if (!PPApplication.getApplicationStarted(true)) // application is not started return; PPApplication.startHandlerThreadBroadcast(); final Handler handler = new Handler(PPApplication.handlerThreadBroadcast.getLooper()); handler.post(() -> { // PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", "START run - from=SimStateChangedBroadcastReceiver.onReceive"); PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = null; try { if (powerManager != null) { wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":SimStateChangedBroadcastReceiver_onReceive"); wakeLock.acquire(10 * 60 * 1000); } // Bundle extras = _intent.getExtras(); // if (extras != null) { // for (String key : extras.keySet()) { // Log.e("SimStateChangedBroadcastReceiver.onReceive", key + " : " + (extras.get(key) != null ? extras.get(key) : "NULL")); // } // } PPApplication.initSIMCards(); PPApplication.simCardsMutext.sim0Exists = PPApplication.hasSIMCard(appContext, 0); PPApplication.simCardsMutext.sim1Exists = PPApplication.hasSIMCard(appContext, 1); PPApplication.simCardsMutext.sim2Exists = PPApplication.hasSIMCard(appContext, 2); PPApplication.simCardsMutext.simCardsDetected = true; // Log.e("SimStateChangedBroadcastReceiver.onReceive", "PPApplication.simCardsMutext.sim0Exists="+PPApplication.simCardsMutext.sim0Exists); // Log.e("SimStateChangedBroadcastReceiver.onReceive", "PPApplication.simCardsMutext.sim1Exists="+PPApplication.simCardsMutext.sim1Exists); // Log.e("SimStateChangedBroadcastReceiver.onReceive", "PPApplication.simCardsMutext.sim2Exists="+PPApplication.simCardsMutext.sim2Exists); // Log.e("SimStateChangedBroadcastReceiver.onReceive", "PPApplication.simCardsMutext.simCardsDetected="+PPApplication.simCardsMutext.simCardsDetected); PhoneProfilesService.registerPhoneCallsListener(false, appContext); PPApplication.sleep(1000); PhoneProfilesService.registerPhoneCallsListener(true, appContext); PPApplication.restartMobileCellsScanner(appContext); } catch (Exception e) { // PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e)); PPApplication.recordException(e); } finally { if ((wakeLock != null) && wakeLock.isHeld()) { try { wakeLock.release(); } catch (Exception ignored) {} } } }); } }
phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/SimStateChangedBroadcastReceiver.java
package sk.henrichg.phoneprofilesplus; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.PowerManager; /** * Handles broadcasts related to SIM card state changes. * <p> * Possible states that are received here are: * <p> * Documented: * ABSENT * NETWORK_LOCKED * PIN_REQUIRED * PUK_REQUIRED * READY * UNKNOWN * <p> * Undocumented: * NOT_READY (ICC interface is not ready, e.g. radio is off or powering on) * CARD_IO_ERROR (three consecutive times there was a SIM IO error) * IMSI (ICC IMSI is ready in property) * LOADED (all ICC records, including IMSI, are loaded) * <p> * Note: some of these are not documented in * https://developer.android.com/reference/android/telephony/TelephonyManager.html * but they can be found deeper in the source code, namely in com.android.internal.telephony.IccCardConstants. */ public class SimStateChangedBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // PPApplication.logE("[IN_BROADCAST] SimStateChangedBroadcastReceiver.onReceive", "xxx"); if (intent == null) return; final Context appContext = context.getApplicationContext(); //final Intent _intent = intent; if (!PPApplication.getApplicationStarted(true)) // application is not started return; PPApplication.startHandlerThreadBroadcast(); final Handler handler = new Handler(PPApplication.handlerThreadBroadcast.getLooper()); handler.post(() -> { // PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", "START run - from=SimStateChangedBroadcastReceiver.onReceive"); PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = null; try { if (powerManager != null) { wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":SimStateChangedBroadcastReceiver_onReceive"); wakeLock.acquire(10 * 60 * 1000); } // Bundle extras = _intent.getExtras(); // if (extras != null) { // for (String key : extras.keySet()) { // Log.e("SimStateChangedBroadcastReceiver.onReceive", key + " : " + (extras.get(key) != null ? extras.get(key) : "NULL")); // } // } PPApplication.initSIMCards(); PPApplication.simCardsMutext.sim0Exists = PPApplication.hasSIMCard(appContext, 0); PPApplication.simCardsMutext.sim1Exists = PPApplication.hasSIMCard(appContext, 1); PPApplication.simCardsMutext.sim2Exists = PPApplication.hasSIMCard(appContext, 2); PPApplication.simCardsMutext.simCardsDetected = true; // Log.e("SimStateChangedBroadcastReceiver.onReceive", "PPApplication.simCardsMutext.sim0Exists="+PPApplication.simCardsMutext.sim0Exists); // Log.e("SimStateChangedBroadcastReceiver.onReceive", "PPApplication.simCardsMutext.sim1Exists="+PPApplication.simCardsMutext.sim1Exists); // Log.e("SimStateChangedBroadcastReceiver.onReceive", "PPApplication.simCardsMutext.sim2Exists="+PPApplication.simCardsMutext.sim2Exists); // Log.e("SimStateChangedBroadcastReceiver.onReceive", "PPApplication.simCardsMutext.simCardsDetected="+PPApplication.simCardsMutext.simCardsDetected); PhoneProfilesService.registerPhoneCallsListener(false, appContext); PPApplication.sleep(1000); PhoneProfilesService.registerPhoneCallsListener(true, appContext); } catch (Exception e) { // PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e)); PPApplication.recordException(e); } finally { if ((wakeLock != null) && wakeLock.isHeld()) { try { wakeLock.release(); } catch (Exception ignored) {} } } }); } }
Reregister mobile cells scanner on sim state change.
phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/SimStateChangedBroadcastReceiver.java
Reregister mobile cells scanner on sim state change.
Java
apache-2.0
9d04efe84a6f3ae8f0227ba99c66d9a389ce5e50
0
Pardus-Engerek/engerek,rpudil/midpoint,rpudil/midpoint,Pardus-Engerek/engerek,gureronder/midpoint,rpudil/midpoint,PetrGasparik/midpoint,gureronder/midpoint,gureronder/midpoint,arnost-starosta/midpoint,Pardus-Engerek/engerek,gureronder/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,Pardus-Engerek/engerek,PetrGasparik/midpoint,sabriarabacioglu/engerek,sabriarabacioglu/engerek,PetrGasparik/midpoint,rpudil/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,PetrGasparik/midpoint,sabriarabacioglu/engerek
/* * Copyright (c) 2010-2013 Evolveum * * 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.evolveum.midpoint.provisioning.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.evolveum.midpoint.common.monitor.InternalMonitor; import com.evolveum.midpoint.common.refinery.RefinedAssociationDefinition; import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition; import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; import com.evolveum.midpoint.common.refinery.ResourceShadowDiscriminator; import com.evolveum.midpoint.common.refinery.ShadowDiscriminatorObjectDelta; import com.evolveum.midpoint.prism.Containerable; import com.evolveum.midpoint.prism.ItemDefinition; import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismContainerDefinition; import com.evolveum.midpoint.prism.PrismContainerValue; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.PrismPropertyValue; import com.evolveum.midpoint.prism.Visitable; import com.evolveum.midpoint.prism.Visitor; import com.evolveum.midpoint.prism.delta.ChangeType; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.delta.PropertyDelta; import com.evolveum.midpoint.prism.path.IdItemPathSegment; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.path.NameItemPathSegment; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.query.AndFilter; import com.evolveum.midpoint.prism.query.EqualFilter; import com.evolveum.midpoint.prism.query.NaryLogicalFilter; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.query.SubstringFilter; import com.evolveum.midpoint.prism.query.ValueFilter; import com.evolveum.midpoint.provisioning.api.ChangeNotificationDispatcher; import com.evolveum.midpoint.provisioning.api.GenericConnectorException; import com.evolveum.midpoint.provisioning.api.ProvisioningOperationOptions; import com.evolveum.midpoint.provisioning.api.ResourceObjectShadowChangeDescription; import com.evolveum.midpoint.provisioning.api.ResourceOperationDescription; import com.evolveum.midpoint.provisioning.consistency.api.ErrorHandler; import com.evolveum.midpoint.provisioning.consistency.api.ErrorHandler.FailedOperation; import com.evolveum.midpoint.provisioning.consistency.impl.ErrorHandlerFactory; import com.evolveum.midpoint.provisioning.ucf.api.Change; import com.evolveum.midpoint.provisioning.ucf.api.ConnectorInstance; import com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException; import com.evolveum.midpoint.provisioning.ucf.api.PropertyModificationOperation; import com.evolveum.midpoint.provisioning.ucf.api.ResultHandler; import com.evolveum.midpoint.provisioning.ucf.impl.ConnectorFactoryIcfImpl; import com.evolveum.midpoint.provisioning.util.ProvisioningUtil; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.schema.DeltaConvertor; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttribute; import com.evolveum.midpoint.schema.processor.ResourceAttributeContainer; import com.evolveum.midpoint.schema.processor.ResourceAttributeContainerDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.schema.util.SchemaDebugUtil; import com.evolveum.midpoint.schema.util.ShadowUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.util.exception.TunnelException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AvailabilityStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.FailedOperationTypeType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationProvisioningScriptsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectAssociationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAssociationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAttributesType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** * Shadow cache is a facade that covers all the operations with shadows. * It takes care of splitting the operations between repository and resource, merging the data back, * handling the errors and generally controlling the process. * * The two principal classes that do the operations are: * ResourceObjectConvertor: executes operations on resource * ShadowManager: executes operations in the repository * * Note: These three classes were refactored recently. There may still be some some * leftovers that needs to be cleaned up. * * @author Radovan Semancik * @author Katarina Valalikova * */ public abstract class ShadowCache { @Autowired(required = true) @Qualifier("cacheRepositoryService") private RepositoryService repositoryService; @Autowired(required = true) private ErrorHandlerFactory errorHandlerFactory; @Autowired(required = true) private ResourceManager resourceTypeManager; @Autowired(required = true) private PrismContext prismContext; @Autowired(required = true) private ResourceObjectConverter resouceObjectConverter; @Autowired(required = true) protected ShadowManager shadowManager; @Autowired(required = true) private ConnectorManager connectorManager; @Autowired(required = true) private ChangeNotificationDispatcher operationListener; @Autowired(required = true) private AccessChecker accessChecker; @Autowired(required = true) private TaskManager taskManager; @Autowired(required = true) private ChangeNotificationDispatcher changeNotificationDispatcher; private static final Trace LOGGER = TraceManager.getTrace(ShadowCache.class); public ShadowCache() { repositoryService = null; } /** * Get the value of repositoryService. * * @return the value of repositoryService */ public RepositoryService getRepositoryService() { return repositoryService; } public PrismContext getPrismContext() { return prismContext; } public PrismObject<ShadowType> getShadow(String oid, PrismObject<ShadowType> repositoryShadow, Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException { Validate.notNull(oid, "Object id must not be null."); LOGGER.trace("Start getting object with oid {}", oid); GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); // We are using parent result directly, not creating subresult. // We want to hide the existence of shadow cache from the user. // Get the shadow from repository. There are identifiers that we need // for accessing the object by UCF. // Later, the repository object may have a fully cached object from the resource. if (repositoryShadow == null) { repositoryShadow = repositoryService.getObject(ShadowType.class, oid, null, parentResult); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Got repository shadow object:\n{}", repositoryShadow.debugDump()); } } // Sanity check if (!oid.equals(repositoryShadow.getOid())) { parentResult.recordFatalError("Provided OID is not equal to OID of repository shadow"); throw new IllegalArgumentException("Provided OID is not equal to OID of repository shadow"); } ResourceType resource = null; try{ resource = getResource(repositoryShadow, parentResult); } catch(ObjectNotFoundException ex){ parentResult.recordFatalError("Resource defined in shadow was not found: " + ex.getMessage(), ex); return repositoryShadow; } RefinedObjectClassDefinition objectClassDefinition = applyAttributesDefinition(repositoryShadow, resource); ConnectorInstance connector = null; OperationResult connectorResult = parentResult.createMinorSubresult(ShadowCache.class.getName() + ".getConnectorInstance"); try { connector = getConnectorInstance(resource, parentResult); connectorResult.recordSuccess(); } catch (ObjectNotFoundException ex){ connectorResult.recordPartialError("Could not get connector instance. " + ex.getMessage(), ex); return repositoryShadow; } catch (SchemaException ex){ connectorResult.recordPartialError("Could not get connector instance. " + ex.getMessage(), ex); return repositoryShadow; } catch (CommunicationException ex){ connectorResult.recordPartialError("Could not get connector instance. " + ex.getMessage(), ex); return repositoryShadow; } catch (ConfigurationException ex){ connectorResult.recordPartialError("Could not get connector instance. " + ex.getMessage(), ex); return repositoryShadow; } PrismObject<ShadowType> resourceShadow = null; try { // Let's get all the identifiers from the Shadow <attributes> part Collection<? extends ResourceAttribute<?>> identifiers = ShadowUtil.getIdentifiers(repositoryShadow); if (identifiers == null || identifiers.isEmpty()) { //check if the account is not only partially created (exist only in repo so far) if (repositoryShadow.asObjectable().getFailedOperationType() != null) { throw new GenericConnectorException( "Unable to get account from the resource. Probably it has not been created yet because of previous unavailability of the resource."); } // No identifiers found SchemaException ex = new SchemaException("No identifiers found in the repository shadow " + repositoryShadow + " with respect to " + resource); parentResult.recordFatalError("No identifiers found in the repository shadow "+ repositoryShadow, ex); throw ex; } // We need to record the fetch down here. Now it is certain that we are going to fetch from resource // (we do not have raw/noFetch option) InternalMonitor.recordShadowFetchOperation(); resourceShadow = resouceObjectConverter.getResourceObject(connector, resource, identifiers, objectClassDefinition, parentResult); resourceTypeManager.modifyResourceAvailabilityStatus(resource.asPrismObject(), AvailabilityStatusType.UP, parentResult); //try to apply changes to the account only if the resource if UP if (repositoryShadow.asObjectable().getObjectChange() != null && repositoryShadow.asObjectable().getFailedOperationType() != null && resource.getOperationalState() != null && resource.getOperationalState().getLastAvailabilityStatus() == AvailabilityStatusType.UP) { throw new GenericConnectorException( "Found changes that have been not applied to the account yet. Trying to apply them now."); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Shadow from repository:\n{}", repositoryShadow.debugDump()); LOGGER.trace("Resource object fetched from resource:\n{}", resourceShadow.debugDump()); } // Complete the shadow by adding attributes from the resource object PrismObject<ShadowType> resultShadow = completeShadow(connector, resourceShadow, repositoryShadow, resource, objectClassDefinition, parentResult); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Shadow when assembled:\n{}", resultShadow.debugDump()); } parentResult.recordSuccess(); return resultShadow; } catch (Exception ex) { try { boolean compensate = GetOperationOptions.isDoNotDiscovery(rootOptions)? false : true; resourceShadow = handleError(ex, repositoryShadow, FailedOperation.GET, resource, null, compensate, task, parentResult); return resourceShadow; } catch (GenericFrameworkException e) { throw new SystemException(e); } catch (ObjectAlreadyExistsException e) { throw new SystemException(e); } } } public abstract String afterAddOnResource(PrismObject<ShadowType> shadow, ResourceType resource, RefinedObjectClassDefinition objectClassDefinition, OperationResult parentResult) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException; public String addShadow(PrismObject<ShadowType> shadow, OperationProvisioningScriptsType scripts, ResourceType resource, ProvisioningOperationOptions options, Task task, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, ObjectAlreadyExistsException, SchemaException, ObjectNotFoundException, ConfigurationException, SecurityViolationException { Validate.notNull(shadow, "Object to add must not be null."); InternalMonitor.recordShadowChangeOperation(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Start adding shadow object:\n{}", shadow.debugDump()); } if (resource == null) { resource = getResource(shadow, parentResult); } PrismContainer<?> attributesContainer = shadow.findContainer( ShadowType.F_ATTRIBUTES); if (attributesContainer == null || attributesContainer.isEmpty()) { // throw new SchemaException("Attempt to add shadow without any attributes: " + shadowType); handleError(new SchemaException("Attempt to add shadow without any attributes: " + shadow), shadow, FailedOperation.ADD, resource, null, true, task, parentResult); } preprocessEntitlements(shadow, resource, parentResult); RefinedObjectClassDefinition objectClassDefinition; try { objectClassDefinition = determineObjectClassDefinition(shadow, resource); applyAttributesDefinition(shadow, resource); shadowManager.setKindIfNecessary(shadow.asObjectable(), objectClassDefinition); accessChecker.checkAdd(resource, shadow, objectClassDefinition, parentResult); ConnectorInstance connector = getConnectorInstance(resource, parentResult); shadow = resouceObjectConverter.addResourceObject(connector, resource, shadow, objectClassDefinition, scripts, parentResult); } catch (Exception ex) { shadow = handleError(ex, shadow, FailedOperation.ADD, resource, null, ProvisioningOperationOptions.isCompletePostponed(options), task, parentResult); return shadow.getOid(); } // This is where the repo shadow is created (if needed) String oid = afterAddOnResource(shadow, resource, objectClassDefinition, parentResult); shadow.setOid(oid); ObjectDelta<ShadowType> delta = ObjectDelta.createAddDelta(shadow); ResourceOperationDescription operationDescription = createSuccessOperationDescription(shadow, resource, delta, task, parentResult); operationListener.notifySuccess(operationDescription, task, parentResult); return oid; } private ResourceOperationDescription createSuccessOperationDescription(PrismObject<ShadowType> shadowType, ResourceType resource, ObjectDelta delta, Task task, OperationResult parentResult) { ResourceOperationDescription operationDescription = new ResourceOperationDescription(); operationDescription.setCurrentShadow(shadowType); operationDescription.setResource(resource.asPrismObject()); if (task != null){ operationDescription.setSourceChannel(task.getChannel()); } operationDescription.setObjectDelta(delta); operationDescription.setResult(parentResult); return operationDescription; } public abstract void afterModifyOnResource(PrismObject<ShadowType> shadow, Collection<? extends ItemDelta> modifications, OperationResult parentResult) throws SchemaException, ObjectNotFoundException; public abstract Collection<? extends ItemDelta> beforeModifyOnResource(PrismObject<ShadowType> shadow, ProvisioningOperationOptions options, Collection<? extends ItemDelta> modifications) throws SchemaException; public String modifyShadow(PrismObject<ShadowType> shadow, ResourceType resource, String oid, Collection<? extends ItemDelta> modifications, OperationProvisioningScriptsType scripts, ProvisioningOperationOptions options, Task task, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, ObjectNotFoundException, SchemaException, ConfigurationException, SecurityViolationException { Validate.notNull(shadow, "Object to modify must not be null."); Validate.notNull(oid, "OID must not be null."); Validate.notNull(modifications, "Object modification must not be null."); InternalMonitor.recordShadowChangeOperation(); if (resource == null) { resource = getResource(shadow, parentResult); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Modifying resource with oid {}, object:\n{}", resource.getOid(), shadow.debugDump()); } RefinedObjectClassDefinition objectClassDefinition = applyAttributesDefinition(shadow, resource); accessChecker.checkModify(resource, shadow, modifications, objectClassDefinition, parentResult); preprocessEntitlements(modifications, resource, parentResult); modifications = beforeModifyOnResource(shadow, options, modifications); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Applying change: {}", DebugUtil.debugDump(modifications)); } Collection<PropertyModificationOperation> sideEffectChanges = null; ConnectorInstance connector = getConnectorInstance(resource, parentResult); try { sideEffectChanges = resouceObjectConverter.modifyResourceObject(connector, resource, objectClassDefinition, shadow, scripts, modifications, parentResult); } catch (Exception ex) { LOGGER.debug("Provisioning exception: {}:{}, attempting to handle it", new Object[] { ex.getClass(), ex.getMessage(), ex }); try { shadow = handleError(ex, shadow, FailedOperation.MODIFY, resource, modifications, ProvisioningOperationOptions.isCompletePostponed(options), task, parentResult); parentResult.computeStatus(); } catch (ObjectAlreadyExistsException e) { parentResult.recordFatalError( "While compensating communication problem for modify operation got: " + ex.getMessage(), ex); throw new SystemException(e); } return shadow.getOid(); } afterModifyOnResource(shadow, modifications, parentResult); Collection<PropertyDelta<?>> renameDeltas = distillRenameDeltas(modifications, shadow, objectClassDefinition); Collection<? extends ItemDelta> sideEffectDelta = convertToPropertyDelta(sideEffectChanges); if (renameDeltas != null) { ((Collection) sideEffectDelta).addAll(renameDeltas); } if (!sideEffectDelta.isEmpty()) { try { repositoryService.modifyObject(shadow.getCompileTimeClass(), oid, sideEffectDelta, parentResult); } catch (ObjectAlreadyExistsException ex) { parentResult.recordFatalError("Side effect changes could not be applied", ex); LOGGER.error("Side effect changes could not be applied. " + ex.getMessage(), ex); throw new SystemException("Side effect changes could not be applied. " + ex.getMessage(), ex); } } ObjectDelta<ShadowType> delta = ObjectDelta.createModifyDelta(shadow.getOid(), modifications, shadow.getCompileTimeClass(), prismContext); ResourceOperationDescription operationDescription = createSuccessOperationDescription(shadow, resource, delta, task, parentResult); operationListener.notifySuccess(operationDescription, task, parentResult); parentResult.recordSuccess(); return oid; } private Collection<PropertyDelta<?>> distillRenameDeltas(Collection<? extends ItemDelta> modifications, PrismObject<ShadowType> shadow, RefinedObjectClassDefinition objectClassDefinition) throws SchemaException { PropertyDelta<String> nameDelta = (PropertyDelta<String>) ItemDelta.findItemDelta(modifications, new ItemPath(ShadowType.F_ATTRIBUTES, ConnectorFactoryIcfImpl.ICFS_NAME), ItemDelta.class); if (nameDelta == null){ return null; } PrismProperty<String> name = nameDelta.getPropertyNew(); String newName = name.getRealValue(); Collection<PropertyDelta<?>> deltas = new ArrayList<PropertyDelta<?>>(); // $shadow/attributes/icfs:name String normalizedNewName = shadowManager.getNormalizedAttributeValue(name.getValue(), objectClassDefinition.findAttributeDefinition(name.getElementName())); PropertyDelta<String> cloneNameDelta = nameDelta.clone(); cloneNameDelta.clearValuesToReplace(); cloneNameDelta.setValueToReplace(new PrismPropertyValue<String>(normalizedNewName)); deltas.add(cloneNameDelta); // $shadow/name if (!newName.equals(shadow.asObjectable().getName().getOrig())){ PropertyDelta<?> shadowNameDelta = PropertyDelta.createModificationReplaceProperty(ShadowType.F_NAME, shadow.getDefinition(), new PolyString(newName)); deltas.add(shadowNameDelta); } return deltas; } private Collection<? extends ItemDelta> convertToPropertyDelta( Collection<PropertyModificationOperation> sideEffectChanges) { Collection<PropertyDelta> sideEffectDelta = new ArrayList<PropertyDelta>(); if (sideEffectChanges != null) { for (PropertyModificationOperation mod : sideEffectChanges){ sideEffectDelta.add(mod.getPropertyDelta()); } } return sideEffectDelta; } public void deleteShadow(PrismObject<ShadowType> shadow, ProvisioningOperationOptions options, OperationProvisioningScriptsType scripts, ResourceType resource, Task task, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, ObjectNotFoundException, SchemaException, ConfigurationException, SecurityViolationException { Validate.notNull(shadow, "Object to delete must not be null."); Validate.notNull(parentResult, "Operation result must not be null."); InternalMonitor.recordShadowChangeOperation(); if (resource == null) { try { resource = getResource(shadow, parentResult); } catch (ObjectNotFoundException ex) { // if the force option is set, delete shadow from the repo // although the resource does not exists.. if (ProvisioningOperationOptions.isForce(options)) { parentResult.muteLastSubresultError(); getRepositoryService().deleteObject(ShadowType.class, shadow.getOid(), parentResult); parentResult.recordHandledError("Resource defined in shadow does not exists. Shadow was deleted from the repository."); return; } } RefinedObjectClassDefinition objectClassDefinition = applyAttributesDefinition(shadow, resource); ConnectorInstance connector = getConnectorInstance(resource, parentResult); LOGGER.trace("Deleting obeject {} from the resource {}.", shadow, resource); if (shadow.asObjectable().getFailedOperationType() == null || (shadow.asObjectable().getFailedOperationType() != null && FailedOperationTypeType.ADD != shadow.asObjectable().getFailedOperationType())) { try { resouceObjectConverter.deleteResourceObject(connector, resource, shadow, objectClassDefinition, scripts, parentResult); } catch (Exception ex) { try { handleError(ex, shadow, FailedOperation.DELETE, resource, null, ProvisioningOperationOptions.isCompletePostponed(options), task, parentResult); } catch (ObjectAlreadyExistsException e) { e.printStackTrace(); } return; } } LOGGER.trace("Detele object with oid {} form repository.", shadow.getOid()); try { getRepositoryService().deleteObject(ShadowType.class, shadow.getOid(), parentResult); ObjectDelta<ShadowType> delta = ObjectDelta.createDeleteDelta(shadow.getCompileTimeClass(), shadow.getOid(), prismContext); ResourceOperationDescription operationDescription = createSuccessOperationDescription(shadow, resource, delta, task, parentResult); operationListener.notifySuccess(operationDescription, task, parentResult); } catch (ObjectNotFoundException ex) { parentResult.recordFatalError("Can't delete object " + shadow + ". Reason: " + ex.getMessage(), ex); throw new ObjectNotFoundException("An error occured while deleting resource object " + shadow + "whith identifiers " + shadow + ": " + ex.getMessage(), ex); } LOGGER.trace("Object deleted from repository successfully."); parentResult.recordSuccess(); resourceTypeManager.modifyResourceAvailabilityStatus(resource.asPrismObject(), AvailabilityStatusType.UP, parentResult); } } public void applyDefinition(ObjectDelta<ShadowType> delta, ShadowType shadowTypeWhenNoOid, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { PrismObject<ShadowType> shadow = null; ResourceShadowDiscriminator discriminator = null; if (delta.isAdd()) { shadow = delta.getObjectToAdd(); } else if (delta.isModify()) { if (delta instanceof ShadowDiscriminatorObjectDelta) { // This one does not have OID, it has to be specially processed discriminator = ((ShadowDiscriminatorObjectDelta) delta).getDiscriminator(); } else { String shadowOid = delta.getOid(); if (shadowOid == null) { if (shadowTypeWhenNoOid == null) { throw new IllegalArgumentException("No OID in object delta " + delta + " and no externally-supplied shadow is present as well."); } shadow = shadowTypeWhenNoOid.asPrismObject(); } else { shadow = repositoryService.getObject(delta.getObjectTypeClass(), shadowOid, null, parentResult); } } } else { // Delete delta, nothing to do at all return; } if (shadow == null) { ResourceType resource = resourceTypeManager.getResource(discriminator.getResourceOid(), parentResult).asObjectable(); applyAttributesDefinition(delta, discriminator, resource); } else { ResourceType resource = getResource(shadow, parentResult); applyAttributesDefinition(delta, shadow, resource); } } public void applyDefinition(PrismObject<ShadowType> shadow, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { ResourceType resource = getResource(shadow, parentResult); applyAttributesDefinition(shadow, resource); } public void applyDefinition(final ObjectQuery query, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { ObjectFilter filter = query.getFilter(); String resourceOid = null; QName objectClassName = null; if (filter instanceof AndFilter){ List<? extends ObjectFilter> conditions = ((AndFilter) filter).getConditions(); resourceOid = ProvisioningUtil.getResourceOidFromFilter(conditions); objectClassName = ProvisioningUtil.getValueFromFilter(conditions, ShadowType.F_OBJECT_CLASS); } PrismObject<ResourceType> resource = resourceTypeManager.getResource(resourceOid, result); final RefinedObjectClassDefinition objectClassDef = determineObjectClassDefinition(objectClassName, resource.asObjectable(), query); applyDefinition(query, objectClassDef); } public void applyDefinition(final ObjectQuery query, final RefinedObjectClassDefinition objectClassDef) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { if (query == null) { return; } ObjectFilter filter = query.getFilter(); if (filter == null) { return; } final ItemPath attributesPath = new ItemPath(ShadowType.F_ATTRIBUTES); com.evolveum.midpoint.prism.query.Visitor visitor = new com.evolveum.midpoint.prism.query.Visitor() { @Override public void visit(ObjectFilter filter) { if (filter instanceof ValueFilter) { ValueFilter<?> valueFilter = (ValueFilter<?>)filter; ItemDefinition definition = valueFilter.getDefinition(); if (definition == null) { ItemPath itemPath = valueFilter.getFullPath(); if (attributesPath.equals(valueFilter.getParentPath())) { QName attributeName = valueFilter.getElementName(); ResourceAttributeDefinition attributeDefinition = objectClassDef.findAttributeDefinition(attributeName); if (attributeDefinition == null) { throw new TunnelException( new SchemaException("No definition for attribute "+attributeName+" in query "+query)); } valueFilter.setDefinition(attributeDefinition); } } } } }; try { filter.accept(visitor); } catch (TunnelException te) { SchemaException e = (SchemaException)te.getCause(); throw e; } } protected ResourceType getResource(PrismObject<ShadowType> shadow, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { String resourceOid = ShadowUtil.getResourceOid(shadow.asObjectable()); if (resourceOid == null) { throw new SchemaException("Shadow " + shadow + " does not have an resource OID"); } return resourceTypeManager.getResource(resourceOid, parentResult).asObjectable(); } @SuppressWarnings("rawtypes") protected PrismObject<ShadowType> handleError(Exception ex, PrismObject<ShadowType> shadow, FailedOperation op, ResourceType resource, Collection<? extends ItemDelta> modifications, boolean compensate, Task task, OperationResult parentResult) throws SchemaException, GenericFrameworkException, CommunicationException, ObjectNotFoundException, ObjectAlreadyExistsException, ConfigurationException, SecurityViolationException { // do not set result in the shadow in case of get operation, it will // resilted to misleading information // by get operation we do not modify the result in the shadow, so only // fetch result in this case needs to be set if (FailedOperation.GET != op) { shadow = extendShadow(shadow, parentResult, resource, modifications); } else { shadow.asObjectable().setResource(resource); } ErrorHandler handler = errorHandlerFactory.createErrorHandler(ex); if (handler == null) { parentResult.recordFatalError("Error without a handler. Reason: " + ex.getMessage(), ex); throw new SystemException(ex.getMessage(), ex); } LOGGER.debug("Handling provisioning exception {}:{}", new Object[] { ex.getClass(), ex.getMessage() }); LOGGER.trace("Handling provisioning exception {}:{}", new Object[] { ex.getClass(), ex.getMessage(), ex }); return handler.handleError(shadow.asObjectable(), op, ex, compensate, task, parentResult).asPrismObject(); } private PrismObject<ShadowType> extendShadow(PrismObject<ShadowType> shadow, OperationResult shadowResult, ResourceType resource, Collection<? extends ItemDelta> modifications) throws SchemaException { ShadowType shadowType = shadow.asObjectable(); shadowType.setResult(shadowResult.createOperationResultType()); shadowType.setResource(resource); if (modifications != null) { ObjectDelta<? extends ObjectType> objectDelta = ObjectDelta.createModifyDelta(shadow.getOid(), modifications, shadowType.getClass(), prismContext); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Storing delta to shadow:\n{}", objectDelta.debugDump()); } ObjectDeltaType objectDeltaType = DeltaConvertor.toObjectDeltaType(objectDelta); shadowType.setObjectChange(objectDeltaType); } return shadow; } //////////////////////////////////////////////////////////////////////////// // SEARCH //////////////////////////////////////////////////////////////////////////// public void listShadows(final ResourceType resource, final QName objectClass, final ShadowHandler<ShadowType> handler, final boolean readFromRepository, final OperationResult parentResult) throws CommunicationException, ObjectNotFoundException, SchemaException, ConfigurationException { InternalMonitor.recordShadowFetchOperation(); Validate.notNull(objectClass); if (resource == null) { parentResult.recordFatalError("Resource must not be null"); throw new IllegalArgumentException("Resource must not be null."); } searchObjectsIterativeInternal(objectClass, resource, null, null, handler, readFromRepository, parentResult); } public void searchObjectsIterative(final QName objectClassName, final ResourceType resourceType, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, final ShadowHandler<ShadowType> handler, final OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException { Validate.notNull(resourceType, "Resource must not be null."); Validate.notNull(objectClassName, "Object class must not be null."); Validate.notNull(parentResult, "Operation result must not be null."); LOGGER.trace("Searching objects iterative with obejct class {}, resource: {}.", objectClassName, resourceType); searchObjectsIterativeInternal(objectClassName, resourceType, query, options, handler, true, parentResult); } private void searchObjectsIterativeInternal(QName objectClassName, final ResourceType resourceType, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, final ShadowHandler<ShadowType> handler, final boolean readFromRepository, final OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { final ResourceSchema resourceSchema = resourceTypeManager.getResourceSchema(resourceType, parentResult); if (resourceSchema == null) { parentResult.recordFatalError("No schema for "+resourceType); throw new ConfigurationException("No schema for "+resourceType); } final RefinedObjectClassDefinition objectClassDef = determineObjectClassDefinition(objectClassName, resourceType, query); applyDefinition(query, objectClassDef); if (objectClassDef == null) { String message = "Object class " + objectClassName + " is not defined in schema of " + ObjectTypeUtil.toShortString(resourceType); LOGGER.error(message); parentResult.recordFatalError(message); throw new SchemaException(message); } GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); if (GetOperationOptions.isNoFetch(rootOptions)) { searchObjectsIterativeRepository(objectClassDef, resourceType, query, options, handler, parentResult); return; } // We need to record the fetch down here. Now it is certain that we are going to fetch from resource // (we do not have raw/noFetch option) InternalMonitor.recordShadowFetchOperation(); ObjectFilter filter = null; if (query != null) { filter = query.getFilter(); } ObjectQuery attributeQuery = null; List<ObjectFilter> attributeFilter = new ArrayList<ObjectFilter>(); if (filter instanceof AndFilter){ List<? extends ObjectFilter> conditions = ((AndFilter) filter).getConditions(); attributeFilter = getAttributeQuery(conditions, attributeFilter); if (attributeFilter.size() > 1){ attributeQuery = ObjectQuery.createObjectQuery(AndFilter.createAnd(attributeFilter)); } if (attributeFilter.size() < 1){ LOGGER.trace("No attribute filter defined in the query."); } if (attributeFilter.size() == 1){ attributeQuery = ObjectQuery.createObjectQuery(attributeFilter.get(0)); } } if (query != null && query.getPaging() != null){ if (attributeQuery == null){ attributeQuery = new ObjectQuery(); } attributeQuery.setPaging(query.getPaging()); } final ConnectorInstance connector = getConnectorInstance(resourceType, parentResult); ResultHandler<ShadowType> resultHandler = new ResultHandler<ShadowType>() { @Override public boolean handle(PrismObject<ShadowType> resourceShadow) { LOGGER.trace("Found resource object {}", SchemaDebugUtil.prettyPrint(resourceShadow)); PrismObject<ShadowType> resultShadow; try { // Try to find shadow that corresponds to the resource object if (readFromRepository) { PrismObject<ShadowType> repoShadow = lookupOrCreateShadowInRepository(connector, resourceShadow, objectClassDef, resourceType, parentResult); applyAttributesDefinition(repoShadow, resourceType); forceRenameIfNeeded(resourceShadow.asObjectable(), repoShadow.asObjectable(), objectClassDef, parentResult); resultShadow = completeShadow(connector, resourceShadow, repoShadow, resourceType, objectClassDef, parentResult); } else { resultShadow = resourceShadow; } } catch (SchemaException e) { // TODO: better error handling parentResult.recordFatalError("Schema error: " + e.getMessage(), e); LOGGER.error("Schema error: {}", e.getMessage(), e); return false; } catch (ConfigurationException e) { // TODO: better error handling parentResult.recordFatalError("Configuration error: " + e.getMessage(), e); LOGGER.error("Configuration error: {}", e.getMessage(), e); return false; } catch (ObjectNotFoundException e) { // TODO: better error handling parentResult.recordFatalError(e.getMessage(), e); LOGGER.error("{}", e.getMessage(), e); return false; } catch (ObjectAlreadyExistsException e) { // TODO: better error handling parentResult.recordFatalError(e.getMessage(), e); LOGGER.error("{}", e.getMessage(), e); return false; } catch (CommunicationException e) { // TODO: better error handling parentResult.recordFatalError(e.getMessage(), e); LOGGER.error("{}", e.getMessage(), e); return false; } catch (SecurityViolationException e) { // TODO: better error handling parentResult.recordFatalError(e.getMessage(), e); LOGGER.error("{}", e.getMessage(), e); return false; } catch (GenericConnectorException e) { // TODO: better error handling parentResult.recordFatalError(e.getMessage(), e); LOGGER.error("{}", e.getMessage(), e); return false; } return handler.handle(resultShadow.asObjectable()); } }; resouceObjectConverter.searchResourceObjects(connector, resourceType, objectClassDef, resultHandler, attributeQuery, parentResult); } private void searchObjectsIterativeRepository( RefinedObjectClassDefinition objectClassDef, final ResourceType resourceType, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, final ShadowHandler<ShadowType> shadowHandler, OperationResult parentResult) throws SchemaException { com.evolveum.midpoint.schema.ResultHandler<ShadowType> repoHandler = new com.evolveum.midpoint.schema.ResultHandler<ShadowType>() { @Override public boolean handle(PrismObject<ShadowType> object, OperationResult parentResult) { try { applyAttributesDefinition(object, resourceType); boolean cont = shadowHandler.handle(object.asObjectable()); parentResult.recordSuccess(); return cont; } catch (RuntimeException e) { parentResult.recordFatalError(e); throw e; } catch (SchemaException e) { parentResult.recordFatalError(e); throw new SystemException(e); } catch (ConfigurationException e) { parentResult.recordFatalError(e); throw new SystemException(e); } } }; shadowManager.searchObjectsIterativeRepository(objectClassDef, resourceType, query, options, repoHandler, parentResult); } private PrismObject<ShadowType> lookupOrCreateShadowInRepository(ConnectorInstance connector, PrismObject<ShadowType> resourceShadow, RefinedObjectClassDefinition objectClassDef, ResourceType resourceType, OperationResult parentResult) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, SecurityViolationException, GenericConnectorException { PrismObject<ShadowType> repoShadow = shadowManager.lookupShadowInRepository(resourceShadow, objectClassDef, resourceType, parentResult); if (repoShadow == null) { LOGGER.trace( "Shadow object (in repo) corresponding to the resource object (on the resource) was not found. The repo shadow will be created. The resource object:\n{}", SchemaDebugUtil.prettyPrint(resourceShadow)); PrismObject<ShadowType> conflictingShadow = shadowManager.lookupShadowByName(resourceShadow, objectClassDef, resourceType, parentResult); if (conflictingShadow != null){ applyAttributesDefinition(conflictingShadow, resourceType); conflictingShadow = completeShadow(connector, resourceShadow, conflictingShadow, resourceType, objectClassDef, parentResult); Task task = taskManager.createTaskInstance(); ResourceOperationDescription failureDescription = shadowManager.createResourceFailureDescription(conflictingShadow, resourceType, parentResult); changeNotificationDispatcher.notifyFailure(failureDescription, task, parentResult); shadowManager.deleteConflictedShadowFromRepo(conflictingShadow, parentResult); } // TODO: make sure that the resource object has appropriate definition (use objectClass and schema) // The resource object obviously exists on the resource, but appropriate shadow does not exist in the // repository we need to create the shadow to align repo state to the reality (resource) try { repoShadow = shadowManager.createRepositoryShadow( resourceShadow, resourceType, objectClassDef); String oid = repositoryService.addObject(repoShadow, null, parentResult); repoShadow.setOid(oid); } catch (ObjectAlreadyExistsException e) { // This should not happen. We haven't supplied an OID so is should not conflict LOGGER.error("Unexpected repository behavior: Object already exists: {}", e.getMessage(), e); throw new SystemException("Unexpected repository behavior: Object already exists: "+e.getMessage(),e); } } else { LOGGER.trace("Found shadow object in the repository {}", SchemaDebugUtil.prettyPrint(repoShadow)); } return repoShadow; } private List<ObjectFilter> getAttributeQuery(List<? extends ObjectFilter> conditions, List<ObjectFilter> attributeFilter) throws SchemaException{ ItemPath objectClassPath = new ItemPath(ShadowType.F_OBJECT_CLASS); ItemPath resourceRefPath = new ItemPath(ShadowType.F_RESOURCE_REF); for (ObjectFilter f : conditions){ if (f instanceof EqualFilter){ if (objectClassPath.equals(((EqualFilter) f).getFullPath())){ continue; } if (resourceRefPath.equals(((EqualFilter) f).getFullPath())){ continue; } attributeFilter.add(f); } else if (f instanceof NaryLogicalFilter){ attributeFilter = getAttributeQuery(((NaryLogicalFilter) f).getConditions(), attributeFilter); } else if (f instanceof SubstringFilter){ attributeFilter.add(f); } } return attributeFilter; } //////////////// ConnectorInstance getConnectorInstance(ResourceType resource, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { return connectorManager.getConfiguredConnectorInstance(resource.asPrismObject(), false, parentResult); } /////////////////////////////////////////////////////////////////////////// // TODO: maybe split this to a separate class /////////////////////////////////////////////////////////////////////////// public List<Change<ShadowType>> fetchChanges(ResourceType resourceType, QName objectClass, PrismProperty<?> lastToken, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, GenericFrameworkException, SchemaException, ConfigurationException, SecurityViolationException, ObjectAlreadyExistsException { InternalMonitor.recordShadowOtherOperation(); RefinedObjectClassDefinition refinedObjectClassDefinition = determineObjectClassDefinition(objectClass, resourceType); ConnectorInstance connector = getConnectorInstance(resourceType, parentResult); List<Change<ShadowType>> changes = null; try { changes = resouceObjectConverter.fetchChanges(connector, resourceType, refinedObjectClassDefinition, lastToken, parentResult); LOGGER.trace("Found {} change(s). Start processing it (them).", changes.size()); for (Iterator<Change<ShadowType>> i = changes.iterator(); i.hasNext();) { // search objects in repository Change<ShadowType> change = i.next(); processChange(resourceType, refinedObjectClassDefinition, objectClass, parentResult, change, connector); } } catch (SchemaException ex) { parentResult.recordFatalError("Schema error: " + ex.getMessage(), ex); throw ex; } catch (CommunicationException ex) { parentResult.recordFatalError("Communication error: " + ex.getMessage(), ex); throw ex; } catch (GenericFrameworkException ex) { parentResult.recordFatalError("Generic error: " + ex.getMessage(), ex); throw ex; } catch (ConfigurationException ex) { parentResult.recordFatalError("Configuration error: " + ex.getMessage(), ex); throw ex; } catch (ObjectNotFoundException ex){ parentResult.recordFatalError("Object not found error: " + ex.getMessage(), ex); throw ex; } catch (ObjectAlreadyExistsException ex){ parentResult.recordFatalError("Already exists error: " + ex.getMessage(), ex); throw ex; } parentResult.recordSuccess(); return changes; } @SuppressWarnings("rawtypes") boolean processSynchronization(Change<ShadowType> change, Task task, ResourceType resourceType, String channel, OperationResult result) throws SchemaException, ObjectNotFoundException, ObjectAlreadyExistsException { // int processedChanges = 0; // // for each change from the connector create change description // for (Change change : changes) { // // // this is the case,when we want to skip processing of change, // // because the shadow was not created or found to the resource // // object // // it may be caused with the fact, that the object which was // // created in the resource was deleted before the sync run // // such a change should be skipped to process consistent changes // if (change.getOldShadow() == null) { // PrismProperty<?> newToken = change.getToken(); // task.setExtensionProperty(newToken); // processedChanges++; // LOGGER.debug("Skipping processing change. Can't find appropriate shadow (e.g. the object was deleted on the resource meantime)."); // continue; // } ResourceObjectShadowChangeDescription shadowChangeDescription = createResourceShadowChangeDescription( change, resourceType, channel); if (LOGGER.isTraceEnabled()) { LOGGER.trace("**PROVISIONING: Created resource object shadow change description {}", SchemaDebugUtil.prettyPrint(shadowChangeDescription)); } OperationResult notifyChangeResult = new OperationResult(ShadowCache.class.getName() + "notifyChange"); notifyChangeResult.addParam("resourceObjectShadowChangeDescription", shadowChangeDescription); try { notifyResourceObjectChangeListeners(shadowChangeDescription, task, notifyChangeResult); notifyChangeResult.recordSuccess(); } catch (RuntimeException ex) { // recordFatalError(LOGGER, notifyChangeResult, "Synchronization error: " + ex.getMessage(), ex); saveAccountResult(shadowChangeDescription, change, notifyChangeResult, result); throw new SystemException("Synchronization error: " + ex.getMessage(), ex); } notifyChangeResult.computeStatus("Error by notify change operation."); boolean successfull = false; if (notifyChangeResult.isSuccess()) { deleteShadowFromRepo(change, result); successfull = true; // // get updated token from change, // // create property modification from new token // // and replace old token with the new one // PrismProperty<?> newToken = change.getToken(); // task.setExtensionProperty(newToken); // processedChanges++; } else { successfull =false; saveAccountResult(shadowChangeDescription, change, notifyChangeResult, result); } return successfull; // } // // also if no changes was detected, update token // if (changes.isEmpty() && tokenProperty != null) { // LOGGER.trace("No changes to synchronize on " + ObjectTypeUtil.toShortString(resourceType)); // task.setExtensionProperty(tokenProperty); // } // task.savePendingModifications(result); // return processedChanges; } private void notifyResourceObjectChangeListeners(ResourceObjectShadowChangeDescription change, Task task, OperationResult parentResult) { changeNotificationDispatcher.notifyChange(change, task, parentResult); } @SuppressWarnings("unchecked") private ResourceObjectShadowChangeDescription createResourceShadowChangeDescription(Change<ShadowType> change, ResourceType resourceType, String channel) { ResourceObjectShadowChangeDescription shadowChangeDescription = new ResourceObjectShadowChangeDescription(); shadowChangeDescription.setObjectDelta(change.getObjectDelta()); shadowChangeDescription.setResource(resourceType.asPrismObject()); shadowChangeDescription.setOldShadow(change.getOldShadow()); shadowChangeDescription.setCurrentShadow(change.getCurrentShadow()); if (null == channel){ shadowChangeDescription.setSourceChannel(QNameUtil.qNameToUri(SchemaConstants.CHANGE_CHANNEL_LIVE_SYNC)); } else{ shadowChangeDescription.setSourceChannel(channel); } return shadowChangeDescription; } @SuppressWarnings("rawtypes") private void saveAccountResult(ResourceObjectShadowChangeDescription shadowChangeDescription, Change change, OperationResult notifyChangeResult, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { Collection<? extends ItemDelta> shadowModification = createShadowResultModification(change, notifyChangeResult); String oid = getOidFromChange(change); // maybe better error handling is needed try{ repositoryService.modifyObject(ShadowType.class, oid, shadowModification, parentResult); } catch (SchemaException ex){ parentResult.recordPartialError("Couldn't modify object: schema violation: " + ex.getMessage(), ex); // throw ex; } catch (ObjectNotFoundException ex){ parentResult.recordWarning("Couldn't modify object: object not found: " + ex.getMessage(), ex); // throw ex; } catch (ObjectAlreadyExistsException ex){ parentResult.recordPartialError("Couldn't modify object: object already exists: " + ex.getMessage(), ex); // throw ex; } } private PrismObjectDefinition<ShadowType> getResourceObjectShadowDefinition() { // if (resourceObjectShadowDefinition == null) { return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass( ShadowType.class); // } // return resourceObjectShadowDefinition; } @SuppressWarnings("rawtypes") private Collection<? extends ItemDelta> createShadowResultModification(Change change, OperationResult shadowResult) { PrismObjectDefinition<ShadowType> shadowDefinition = getResourceObjectShadowDefinition(); Collection<ItemDelta> modifications = new ArrayList<ItemDelta>(); PropertyDelta resultDelta = PropertyDelta.createModificationReplaceProperty( ShadowType.F_RESULT, shadowDefinition, shadowResult.createOperationResultType()); modifications.add(resultDelta); if (change.getObjectDelta() != null && change.getObjectDelta().getChangeType() == ChangeType.DELETE) { PropertyDelta failedOperationTypeDelta = PropertyDelta.createModificationReplaceProperty(ShadowType.F_FAILED_OPERATION_TYPE, shadowDefinition, FailedOperationTypeType.DELETE); modifications.add(failedOperationTypeDelta); } return modifications; } private String getOidFromChange(Change change){ String shadowOid = null; if (change.getObjectDelta() != null && change.getObjectDelta().getOid() != null) { shadowOid = change.getObjectDelta().getOid(); } else { if (change.getCurrentShadow().getOid() != null) { shadowOid = change.getCurrentShadow().getOid(); } else { if (change.getOldShadow().getOid() != null) { shadowOid = change.getOldShadow().getOid(); } else { throw new IllegalArgumentException("No oid value defined for the object to synchronize."); } } } return shadowOid; } private void deleteShadowFromRepo(Change change, OperationResult parentResult) throws ObjectNotFoundException { if (change.getObjectDelta() != null && change.getObjectDelta().getChangeType() == ChangeType.DELETE && change.getOldShadow() != null) { LOGGER.debug("Deleting detected shadow object form repository."); try { repositoryService.deleteObject(ShadowType.class, change.getOldShadow().getOid(), parentResult); } catch (ObjectNotFoundException ex) { parentResult.recordFatalError("Can't find object " + change.getOldShadow() + " in repository."); throw new ObjectNotFoundException("Can't find object " + change.getOldShadow() + " in repository."); } LOGGER.debug("Shadow object deleted successfully form repository."); } } void processChange(ResourceType resourceType, RefinedObjectClassDefinition refinedObjectClassDefinition, QName objectClass, OperationResult parentResult, Change<ShadowType> change, ConnectorInstance connector) throws SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ObjectNotFoundException, GenericConnectorException, ObjectAlreadyExistsException{ if (refinedObjectClassDefinition == null){ refinedObjectClassDefinition = determineObjectClassDefinition(objectClass, resourceType); } PrismObject<ShadowType> oldShadow = change.getOldShadow(); if (oldShadow == null){ oldShadow = shadowManager.findOrCreateShadowFromChange(resourceType, change, refinedObjectClassDefinition, parentResult); } if (oldShadow != null) { applyAttributesDefinition(oldShadow, resourceType); ShadowType oldShadowType = oldShadow.asObjectable(); LOGGER.trace("Old shadow: {}", oldShadow); // skip setting other attribute when shadow is null if (oldShadow == null) { change.setOldShadow(null); return; } resouceObjectConverter.setProtectedFlag(resourceType, refinedObjectClassDefinition, oldShadow); change.setOldShadow(oldShadow); if (change.getCurrentShadow() != null) { PrismObject<ShadowType> currentShadow = completeShadow(connector, change.getCurrentShadow(), oldShadow, resourceType, refinedObjectClassDefinition, parentResult); change.setCurrentShadow(currentShadow); ShadowType currentShadowType = currentShadow.asObjectable(); forceRenameIfNeeded(currentShadowType, oldShadowType, refinedObjectClassDefinition, parentResult); } // FIXME: hack. the object delta must have oid specified. if (change.getObjectDelta() != null && change.getObjectDelta().getOid() == null) { ObjectDelta<ShadowType> objDelta = new ObjectDelta<ShadowType>(ShadowType.class, ChangeType.DELETE, prismContext); change.setObjectDelta(objDelta); change.getObjectDelta().setOid(oldShadow.getOid()); } } else { LOGGER.debug("No old shadow for synchronization event {}, the shadow must be gone in the meantime (this is probably harmless)", change); } } private void forceRenameIfNeeded(ShadowType currentShadowType, ShadowType oldShadowType, RefinedObjectClassDefinition refinedObjectClassDefinition, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, ObjectAlreadyExistsException { Collection<ResourceAttribute<?>> oldSecondaryIdentifiers = ShadowUtil.getSecondaryIdentifiers(oldShadowType); if (oldSecondaryIdentifiers.isEmpty()){ return; } if (oldSecondaryIdentifiers.size() > 1){ return; } ResourceAttribute<?> oldSecondaryIdentifier = oldSecondaryIdentifiers.iterator().next(); Object oldValue = oldSecondaryIdentifier.getRealValue(); Collection<ResourceAttribute<?>> newSecondaryIdentifiers = ShadowUtil.getSecondaryIdentifiers(currentShadowType); if (newSecondaryIdentifiers.isEmpty()){ return; } if (newSecondaryIdentifiers.size() > 1){ return; } ResourceAttribute newSecondaryIdentifier = newSecondaryIdentifiers.iterator().next(); Object newValue = newSecondaryIdentifier.getRealValue(); if (!shadowManager.compareAttribute(refinedObjectClassDefinition, newSecondaryIdentifier, oldValue)){ Collection<PropertyDelta> renameDeltas = new ArrayList<PropertyDelta>(); PropertyDelta<?> shadowNameDelta = PropertyDelta.createModificationReplaceProperty(ShadowType.F_NAME, oldShadowType.asPrismObject().getDefinition(), ProvisioningUtil.determineShadowName(currentShadowType.asPrismObject())); renameDeltas.add(shadowNameDelta); shadowNameDelta = PropertyDelta.createModificationReplaceProperty(new ItemPath(ShadowType.F_ATTRIBUTES, ConnectorFactoryIcfImpl.ICFS_NAME), oldShadowType.asPrismObject().getDefinition(), newValue); renameDeltas.add(shadowNameDelta); repositoryService.modifyObject(ShadowType.class, oldShadowType.getOid(), renameDeltas, parentResult); } } public PrismProperty<?> fetchCurrentToken(ResourceType resourceType, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException { InternalMonitor.recordShadowOtherOperation(); Validate.notNull(resourceType, "Resource must not be null."); Validate.notNull(parentResult, "Operation result must not be null."); ObjectClassComplexTypeDefinition objecClassDefinition = determineDefaultAccountObjectClassDefinition(resourceType); ConnectorInstance connector = getConnectorInstance(resourceType, parentResult); LOGGER.trace("Getting last token"); PrismProperty<?> lastToken = null; try { ResourceSchema resourceSchema = resourceTypeManager.getResourceSchema(resourceType, parentResult); if (resourceSchema == null) { throw new ConfigurationException("No schema for "+resourceType); } lastToken = resouceObjectConverter.fetchCurrentToken(connector, resourceType, objecClassDefinition, parentResult); } catch (CommunicationException e) { parentResult.recordFatalError(e.getMessage(), e); throw e; } catch (ConfigurationException e) { parentResult.recordFatalError(e.getMessage(), e); throw e; } LOGGER.trace("Got last token: {}", SchemaDebugUtil.prettyPrint(lastToken)); parentResult.recordSuccess(); return lastToken; } ////////////////////////////////////////////////////////////////////////////////////// public ObjectClassComplexTypeDefinition applyAttributesDefinition(ObjectDelta<ShadowType> delta, ResourceShadowDiscriminator discriminator, ResourceType resource) throws SchemaException, ConfigurationException { ObjectClassComplexTypeDefinition objectClassDefinition = determineObjectClassDefinition(discriminator, resource); return applyAttributesDefinition(delta, objectClassDefinition, resource); } public ObjectClassComplexTypeDefinition applyAttributesDefinition(ObjectDelta<ShadowType> delta, PrismObject<ShadowType> shadow, ResourceType resource) throws SchemaException, ConfigurationException { ObjectClassComplexTypeDefinition objectClassDefinition = determineObjectClassDefinition(shadow, resource); return applyAttributesDefinition(delta, objectClassDefinition, resource); } private ObjectClassComplexTypeDefinition applyAttributesDefinition(ObjectDelta<ShadowType> delta, ObjectClassComplexTypeDefinition objectClassDefinition, ResourceType resource) throws SchemaException, ConfigurationException { if (delta.isAdd()) { applyAttributesDefinition(delta.getObjectToAdd(), resource); } else if (delta.isModify()) { ItemPath attributesPath = new ItemPath(ShadowType.F_ATTRIBUTES); for(ItemDelta<?> modification: delta.getModifications()) { if (modification.getDefinition() == null && attributesPath.equals(modification.getParentPath())) { QName attributeName = modification.getElementName(); ResourceAttributeDefinition attributeDefinition = objectClassDefinition.findAttributeDefinition(attributeName); if (attributeDefinition == null) { throw new SchemaException("No definition for attribute "+attributeName+" in object delta "+delta); } modification.applyDefinition(attributeDefinition); } } } return objectClassDefinition; } public RefinedObjectClassDefinition applyAttributesDefinition( PrismObject<ShadowType> shadow, ResourceType resource) throws SchemaException, ConfigurationException { RefinedObjectClassDefinition objectClassDefinition = determineObjectClassDefinition(shadow, resource); PrismContainer<?> attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); if (attributesContainer != null) { if (attributesContainer instanceof ResourceAttributeContainer) { if (attributesContainer.getDefinition() == null) { attributesContainer.applyDefinition(objectClassDefinition.toResourceAttributeContainerDefinition()); } } else { // We need to convert <attributes> to ResourceAttributeContainer ResourceAttributeContainer convertedContainer = ResourceAttributeContainer.convertFromContainer( attributesContainer, objectClassDefinition); shadow.getValue().replace(attributesContainer, convertedContainer); } } // We also need to replace the entire object definition to inject correct object class definition here // If we don't do this then the patch (delta.applyTo) will not work correctly because it will not be able to // create the attribute container if needed. PrismObjectDefinition<ShadowType> objectDefinition = shadow.getDefinition(); PrismContainerDefinition<ShadowAttributesType> origAttrContainerDef = objectDefinition.findContainerDefinition(ShadowType.F_ATTRIBUTES); if (origAttrContainerDef == null || !(origAttrContainerDef instanceof ResourceAttributeContainerDefinition)) { PrismObjectDefinition<ShadowType> clonedDefinition = objectDefinition.cloneWithReplacedDefinition(ShadowType.F_ATTRIBUTES, objectClassDefinition.toResourceAttributeContainerDefinition()); shadow.setDefinition(clonedDefinition); } return objectClassDefinition; } private RefinedObjectClassDefinition determineObjectClassDefinition(PrismObject<ShadowType> shadow, ResourceType resource) throws SchemaException, ConfigurationException { ShadowType shadowType = shadow.asObjectable(); RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource, prismContext); if (refinedSchema == null) { throw new ConfigurationException("No schema definied for "+resource); } RefinedObjectClassDefinition objectClassDefinition = null; ShadowKindType kind = shadowType.getKind(); String intent = shadowType.getIntent(); QName objectClass = shadow.asObjectable().getObjectClass(); if (kind != null) { objectClassDefinition = refinedSchema.getRefinedDefinition(kind, intent); } if (objectClassDefinition == null) { // Fallback to objectclass only if (objectClass == null) { throw new SchemaException("No kind nor objectclass definied in "+shadow); } objectClassDefinition = refinedSchema.findRefinedDefinitionByObjectClassQName(null, objectClass); } if (objectClassDefinition == null) { throw new SchemaException("Definition for "+shadow+" not found (objectClass=" + PrettyPrinter.prettyPrint(objectClass) + ", kind="+kind+", intent='"+intent+"') in schema of " + resource); } return objectClassDefinition; } private ObjectClassComplexTypeDefinition determineObjectClassDefinition( ResourceShadowDiscriminator discriminator, ResourceType resource) throws SchemaException { ResourceSchema schema = RefinedResourceSchema.getResourceSchema(resource, prismContext); // HACK FIXME ObjectClassComplexTypeDefinition objectClassDefinition = schema.findObjectClassDefinition(ShadowKindType.ACCOUNT, discriminator.getIntent()); if (objectClassDefinition == null) { // Unknown objectclass throw new SchemaException("Account type " + discriminator.getIntent() + " is not known in schema of " + resource); } return objectClassDefinition; } private RefinedObjectClassDefinition determineObjectClassDefinition( QName objectClassName, ResourceType resourceType, ObjectQuery query) throws SchemaException, ConfigurationException { ShadowKindType kind = null; String intent = null; if (query != null && query.getFilter() != null) { List<? extends ObjectFilter> conditions = ((AndFilter) query.getFilter()).getConditions(); kind = ProvisioningUtil.getValueFromFilter(conditions, ShadowType.F_KIND); intent = ProvisioningUtil.getValueFromFilter(conditions, ShadowType.F_INTENT); } RefinedObjectClassDefinition objectClassDefinition; if (kind == null) { objectClassDefinition = getRefinedScema(resourceType).getRefinedDefinition(objectClassName); } else { objectClassDefinition = getRefinedScema(resourceType).getRefinedDefinition(kind, intent); } return objectClassDefinition; } private RefinedObjectClassDefinition determineObjectClassDefinition(QName objectClassName, ResourceType resourceType) throws SchemaException, ConfigurationException { return getRefinedScema(resourceType).getRefinedDefinition(objectClassName); } private ObjectClassComplexTypeDefinition determineDefaultAccountObjectClassDefinition(ResourceType resourceType) throws SchemaException, ConfigurationException { // HACK, FIXME return getRefinedScema(resourceType).getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); } private RefinedResourceSchema getRefinedScema(ResourceType resourceType) throws SchemaException, ConfigurationException { RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resourceType); if (refinedSchema == null) { throw new ConfigurationException("No schema for "+resourceType); } return refinedSchema; } /** * Make sure that the shadow is complete, e.g. that all the mandatory fields * are filled (e.g name, resourceRef, ...) Also transforms the shadow with * respect to simulated capabilities. */ private PrismObject<ShadowType> completeShadow(ConnectorInstance connector, PrismObject<ShadowType> resourceShadow, PrismObject<ShadowType> repoShadow, ResourceType resource, RefinedObjectClassDefinition objectClassDefinition, OperationResult parentResult) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, SecurityViolationException, GenericConnectorException { PrismObject<ShadowType> resultShadow = repoShadow.clone(); boolean resultIsResourceShadowClone = false; if (resultShadow == null) { resultShadow = resourceShadow.clone(); resultIsResourceShadowClone = true; } assert resultShadow.getPrismContext() != null : "No prism context in resultShadow"; ResourceAttributeContainer resourceAttributesContainer = ShadowUtil .getAttributesContainer(resourceShadow); ShadowType resultShadowType = resultShadow.asObjectable(); ShadowType repoShadowType = repoShadow.asObjectable(); ShadowType resourceShadowType = resourceShadow.asObjectable(); if (resultShadowType.getObjectClass() == null) { resultShadowType.setObjectClass(resourceAttributesContainer.getDefinition().getTypeName()); } if (resultShadowType.getName() == null) { resultShadowType.setName(new PolyStringType(ProvisioningUtil.determineShadowName(resourceShadow))); } if (resultShadowType.getResource() == null) { resultShadowType.setResourceRef(ObjectTypeUtil.createObjectRef(resource)); } // If the shadows are the same then no copy is needed. This was already copied by clone. if (!resultIsResourceShadowClone) { // Attributes resultShadow.removeContainer(ShadowType.F_ATTRIBUTES); ResourceAttributeContainer resultAttibutes = resourceAttributesContainer.clone(); accessChecker.filterGetAttributes(resultAttibutes, objectClassDefinition, parentResult); resultShadow.add(resultAttibutes); resultShadowType.setProtectedObject(resourceShadowType.isProtectedObject()); resultShadowType.setIgnored(resourceShadowType.isIgnored()); resultShadowType.setActivation(resourceShadowType.getActivation()); // Credentials ShadowType resultAccountShadow = resultShadow.asObjectable(); ShadowType resourceAccountShadow = resourceShadow.asObjectable(); resultAccountShadow.setCredentials(resourceAccountShadow.getCredentials()); } // Activation ActivationType resultActivationType = resultShadowType.getActivation(); ActivationType repoActivation = repoShadowType.getActivation(); if (repoActivation != null) { if (resultActivationType == null) { resultActivationType = new ActivationType(); resultShadowType.setActivation(resultActivationType); } resultActivationType.setId(repoActivation.getId()); // .. but we want metadata from repo resultActivationType.setDisableReason(repoActivation.getDisableReason()); resultActivationType.setEnableTimestamp(repoActivation.getEnableTimestamp()); resultActivationType.setDisableTimestamp(repoActivation.getDisableTimestamp()); resultActivationType.setArchiveTimestamp(repoActivation.getArchiveTimestamp()); resultActivationType.setValidityChangeTimestamp(repoActivation.getValidityChangeTimestamp()); } // Associations PrismContainer<ShadowAssociationType> resourceAssociationContainer = resourceShadow.findContainer(ShadowType.F_ASSOCIATION); if (resourceAssociationContainer != null) { RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); PrismContainer<ShadowAssociationType> associationContainer = resourceAssociationContainer.clone(); resultShadow.addReplaceExisting(associationContainer); if (associationContainer != null) { for (PrismContainerValue<ShadowAssociationType> associationCVal: associationContainer.getValues()) { ResourceAttributeContainer identifierContainer = ShadowUtil.getAttributesContainer(associationCVal, ShadowAssociationType.F_IDENTIFIERS); Collection<ResourceAttribute<?>> entitlementIdentifiers = identifierContainer.getAttributes(); if (entitlementIdentifiers == null || entitlementIdentifiers.isEmpty()) { throw new IllegalStateException("No entitlement identifiers present for association "+associationCVal); } ShadowAssociationType shadowAssociationType = associationCVal.asContainerable(); QName associationName = shadowAssociationType.getName(); RefinedAssociationDefinition rEntitlementAssociation = objectClassDefinition.findEntitlementAssociation(associationName); String entitlementIntent = rEntitlementAssociation.getIntent(); RefinedObjectClassDefinition entitlementObjectClassDef = refinedSchema.getRefinedDefinition(ShadowKindType.ENTITLEMENT, entitlementIntent); PrismObject<ShadowType> entitlementShadow = (PrismObject<ShadowType>) identifierContainer.getUserData(ResourceObjectConverter.FULL_SHADOW_KEY); if (entitlementShadow == null) { entitlementShadow = resouceObjectConverter.locateResourceObject(connector, resource, entitlementIdentifiers, entitlementObjectClassDef, parentResult); } PrismObject<ShadowType> entitlementRepoShadow = lookupOrCreateShadowInRepository(connector, entitlementShadow, entitlementObjectClassDef, resource, parentResult); ObjectReferenceType shadowRefType = new ObjectReferenceType(); shadowRefType.setOid(entitlementRepoShadow.getOid()); shadowRefType.setType(ShadowType.COMPLEX_TYPE); shadowAssociationType.setShadowRef(shadowRefType); } } } // Sanity asserts to catch some exotic bugs PolyStringType resultName = resultShadow.asObjectable().getName(); assert resultName != null : "No name generated in "+resultShadow; assert !StringUtils.isEmpty(resultName.getOrig()) : "No name (orig) in "+resultShadow; assert !StringUtils.isEmpty(resultName.getNorm()) : "No name (norm) in "+resultShadow; return resultShadow; } // ENTITLEMENTS /** * Makes sure that all the entitlements have identifiers in them so this is usable by the * ResourceObjectConverter. */ private void preprocessEntitlements(PrismObject<ShadowType> shadow, final ResourceType resource, final OperationResult result) throws SchemaException, ObjectNotFoundException, ConfigurationException { Visitor visitor = new Visitor() { @Override public void visit(Visitable visitable) { try { preprocessEntitlement((PrismContainerValue<ShadowAssociationType>)visitable, resource, result); } catch (SchemaException e) { throw new TunnelException(e); } catch (ObjectNotFoundException e) { throw new TunnelException(e); } catch (ConfigurationException e) { throw new TunnelException(e); } } }; try { shadow.accept(visitor , new ItemPath( new NameItemPathSegment(ShadowType.F_ASSOCIATION), IdItemPathSegment.WILDCARD), false); } catch (TunnelException e) { Throwable cause = e.getCause(); if (cause instanceof SchemaException) { throw (SchemaException)cause; } else if (cause instanceof ObjectNotFoundException) { throw (ObjectNotFoundException)cause; } else if (cause instanceof ConfigurationException) { throw (ConfigurationException)cause; } else { throw new SystemException("Unexpected exception "+cause, cause); } } } /** * Makes sure that all the entitlements have identifiers in them so this is usable by the * ResourceObjectConverter. */ private void preprocessEntitlements(Collection<? extends ItemDelta> modifications, final ResourceType resource, final OperationResult result) throws SchemaException, ObjectNotFoundException, ConfigurationException { Visitor visitor = new Visitor() { @Override public void visit(Visitable visitable) { try { preprocessEntitlement((PrismContainerValue<ShadowAssociationType>)visitable, resource, result); } catch (SchemaException e) { throw new TunnelException(e); } catch (ObjectNotFoundException e) { throw new TunnelException(e); } catch (ConfigurationException e) { throw new TunnelException(e); } } }; try { ItemDelta.accept(modifications, visitor , new ItemPath( new NameItemPathSegment(ShadowType.F_ASSOCIATION), IdItemPathSegment.WILDCARD), false); } catch (TunnelException e) { Throwable cause = e.getCause(); if (cause instanceof SchemaException) { throw (SchemaException)cause; } else if (cause instanceof ObjectNotFoundException) { throw (ObjectNotFoundException)cause; } else if (cause instanceof ConfigurationException) { throw (ConfigurationException)cause; } else { throw new SystemException("Unexpected exception "+cause, cause); } } } private void preprocessEntitlement(PrismContainerValue<ShadowAssociationType> association, ResourceType resource, OperationResult result) throws SchemaException, ObjectNotFoundException, ConfigurationException { PrismContainer<Containerable> identifiersContainer = association.findContainer(ShadowAssociationType.F_IDENTIFIERS); if (identifiersContainer != null && !identifiersContainer.isEmpty()) { // We already have identifiers here return; } ShadowAssociationType associationType = association.asContainerable(); if (associationType.getShadowRef() == null || StringUtils.isEmpty(associationType.getShadowRef().getOid())) { throw new SchemaException("No identifiers and no OID specified in entitlements association "+association); } PrismObject<ShadowType> repoShadow; try { repoShadow = repositoryService.getObject(ShadowType.class, associationType.getShadowRef().getOid(), null, result); } catch (ObjectNotFoundException e) { throw new ObjectNotFoundException(e.getMessage()+" while resolving entitlement association OID in "+association, e); } applyAttributesDefinition(repoShadow, resource); transplantIdentifiers(association, repoShadow); } private void transplantIdentifiers(PrismContainerValue<ShadowAssociationType> association, PrismObject<ShadowType> repoShadow) throws SchemaException { PrismContainer<Containerable> identifiersContainer = association.findContainer(ShadowAssociationType.F_IDENTIFIERS); if (identifiersContainer == null) { ResourceAttributeContainer origContainer = ShadowUtil.getAttributesContainer(repoShadow); identifiersContainer = new ResourceAttributeContainer(ShadowAssociationType.F_IDENTIFIERS, origContainer.getDefinition(), prismContext); association.add(identifiersContainer); } Collection<ResourceAttribute<?>> identifiers = ShadowUtil.getIdentifiers(repoShadow); for (ResourceAttribute<?> identifier: identifiers) { identifiersContainer.add(identifier.clone()); } Collection<ResourceAttribute<?>> secondaryIdentifiers = ShadowUtil.getSecondaryIdentifiers(repoShadow); for (ResourceAttribute<?> identifier: secondaryIdentifiers) { identifiersContainer.add(identifier.clone()); } } }
provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ShadowCache.java
/* * Copyright (c) 2010-2013 Evolveum * * 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.evolveum.midpoint.provisioning.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.evolveum.midpoint.common.monitor.InternalMonitor; import com.evolveum.midpoint.common.refinery.RefinedAssociationDefinition; import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition; import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; import com.evolveum.midpoint.common.refinery.ResourceShadowDiscriminator; import com.evolveum.midpoint.common.refinery.ShadowDiscriminatorObjectDelta; import com.evolveum.midpoint.prism.Containerable; import com.evolveum.midpoint.prism.ItemDefinition; import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismContainerDefinition; import com.evolveum.midpoint.prism.PrismContainerValue; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.PrismPropertyValue; import com.evolveum.midpoint.prism.Visitable; import com.evolveum.midpoint.prism.Visitor; import com.evolveum.midpoint.prism.delta.ChangeType; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.delta.PropertyDelta; import com.evolveum.midpoint.prism.path.IdItemPathSegment; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.path.NameItemPathSegment; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.query.AndFilter; import com.evolveum.midpoint.prism.query.EqualFilter; import com.evolveum.midpoint.prism.query.NaryLogicalFilter; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.query.SubstringFilter; import com.evolveum.midpoint.prism.query.ValueFilter; import com.evolveum.midpoint.provisioning.api.ChangeNotificationDispatcher; import com.evolveum.midpoint.provisioning.api.GenericConnectorException; import com.evolveum.midpoint.provisioning.api.ProvisioningOperationOptions; import com.evolveum.midpoint.provisioning.api.ResourceObjectShadowChangeDescription; import com.evolveum.midpoint.provisioning.api.ResourceOperationDescription; import com.evolveum.midpoint.provisioning.consistency.api.ErrorHandler; import com.evolveum.midpoint.provisioning.consistency.api.ErrorHandler.FailedOperation; import com.evolveum.midpoint.provisioning.consistency.impl.ErrorHandlerFactory; import com.evolveum.midpoint.provisioning.ucf.api.Change; import com.evolveum.midpoint.provisioning.ucf.api.ConnectorInstance; import com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException; import com.evolveum.midpoint.provisioning.ucf.api.PropertyModificationOperation; import com.evolveum.midpoint.provisioning.ucf.api.ResultHandler; import com.evolveum.midpoint.provisioning.ucf.impl.ConnectorFactoryIcfImpl; import com.evolveum.midpoint.provisioning.util.ProvisioningUtil; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.schema.DeltaConvertor; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttribute; import com.evolveum.midpoint.schema.processor.ResourceAttributeContainer; import com.evolveum.midpoint.schema.processor.ResourceAttributeContainerDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.schema.util.SchemaDebugUtil; import com.evolveum.midpoint.schema.util.ShadowUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.util.exception.TunnelException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AvailabilityStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.FailedOperationTypeType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationProvisioningScriptsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectAssociationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAssociationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAttributesType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** * Shadow cache is a facade that covers all the operations with shadows. * It takes care of splitting the operations between repository and resource, merging the data back, * handling the errors and generally controlling the process. * * The two principal classes that do the operations are: * ResourceObjectConvertor: executes operations on resource * ShadowManager: executes operations in the repository * * Note: These three classes were refactored recently. There may still be some some * leftovers that needs to be cleaned up. * * @author Radovan Semancik * @author Katarina Valalikova * */ public abstract class ShadowCache { @Autowired(required = true) @Qualifier("cacheRepositoryService") private RepositoryService repositoryService; @Autowired(required = true) private ErrorHandlerFactory errorHandlerFactory; @Autowired(required = true) private ResourceManager resourceTypeManager; @Autowired(required = true) private PrismContext prismContext; @Autowired(required = true) private ResourceObjectConverter resouceObjectConverter; @Autowired(required = true) protected ShadowManager shadowManager; @Autowired(required = true) private ConnectorManager connectorManager; @Autowired(required = true) private ChangeNotificationDispatcher operationListener; @Autowired(required = true) private AccessChecker accessChecker; @Autowired(required = true) private TaskManager taskManager; @Autowired(required = true) private ChangeNotificationDispatcher changeNotificationDispatcher; private static final Trace LOGGER = TraceManager.getTrace(ShadowCache.class); public ShadowCache() { repositoryService = null; } /** * Get the value of repositoryService. * * @return the value of repositoryService */ public RepositoryService getRepositoryService() { return repositoryService; } public PrismContext getPrismContext() { return prismContext; } public PrismObject<ShadowType> getShadow(String oid, PrismObject<ShadowType> repositoryShadow, Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException { Validate.notNull(oid, "Object id must not be null."); LOGGER.trace("Start getting object with oid {}", oid); GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); // We are using parent result directly, not creating subresult. // We want to hide the existence of shadow cache from the user. // Get the shadow from repository. There are identifiers that we need // for accessing the object by UCF. // Later, the repository object may have a fully cached object from the resource. if (repositoryShadow == null) { repositoryShadow = repositoryService.getObject(ShadowType.class, oid, null, parentResult); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Got repository shadow object:\n{}", repositoryShadow.debugDump()); } } // Sanity check if (!oid.equals(repositoryShadow.getOid())) { parentResult.recordFatalError("Provided OID is not equal to OID of repository shadow"); throw new IllegalArgumentException("Provided OID is not equal to OID of repository shadow"); } ResourceType resource = null; try{ resource = getResource(repositoryShadow, parentResult); } catch(ObjectNotFoundException ex){ parentResult.recordFatalError("Resource defined in shadow was not found: " + ex.getMessage(), ex); return repositoryShadow; } RefinedObjectClassDefinition objectClassDefinition = applyAttributesDefinition(repositoryShadow, resource); ConnectorInstance connector = null; OperationResult connectorResult = parentResult.createMinorSubresult(ShadowCache.class.getName() + ".getConnectorInstance"); try { connector = getConnectorInstance(resource, parentResult); connectorResult.recordSuccess(); } catch (ObjectNotFoundException ex){ connectorResult.recordPartialError("Could not get connector instance. " + ex.getMessage(), ex); return repositoryShadow; } catch (SchemaException ex){ connectorResult.recordPartialError("Could not get connector instance. " + ex.getMessage(), ex); return repositoryShadow; } catch (CommunicationException ex){ connectorResult.recordPartialError("Could not get connector instance. " + ex.getMessage(), ex); return repositoryShadow; } catch (ConfigurationException ex){ connectorResult.recordPartialError("Could not get connector instance. " + ex.getMessage(), ex); return repositoryShadow; } PrismObject<ShadowType> resourceShadow = null; try { // Let's get all the identifiers from the Shadow <attributes> part Collection<? extends ResourceAttribute<?>> identifiers = ShadowUtil.getIdentifiers(repositoryShadow); if (identifiers == null || identifiers.isEmpty()) { //check if the account is not only partially created (exist only in repo so far) if (repositoryShadow.asObjectable().getFailedOperationType() != null) { throw new GenericConnectorException( "Unable to get account from the resource. Probably it has not been created yet because of previous unavailability of the resource."); } // No identifiers found SchemaException ex = new SchemaException("No identifiers found in the repository shadow " + repositoryShadow + " with respect to " + resource); parentResult.recordFatalError("No identifiers found in the repository shadow "+ repositoryShadow, ex); throw ex; } // We need to record the fetch down here. Now it is certain that we are going to fetch from resource // (we do not have raw/noFetch option) InternalMonitor.recordShadowFetchOperation(); resourceShadow = resouceObjectConverter.getResourceObject(connector, resource, identifiers, objectClassDefinition, parentResult); resourceTypeManager.modifyResourceAvailabilityStatus(resource.asPrismObject(), AvailabilityStatusType.UP, parentResult); //try to apply changes to the account only if the resource if UP if (repositoryShadow.asObjectable().getObjectChange() != null && repositoryShadow.asObjectable().getFailedOperationType() != null && resource.getOperationalState() != null && resource.getOperationalState().getLastAvailabilityStatus() == AvailabilityStatusType.UP) { throw new GenericConnectorException( "Found changes that have been not applied to the account yet. Trying to apply them now."); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Shadow from repository:\n{}", repositoryShadow.debugDump()); LOGGER.trace("Resource object fetched from resource:\n{}", resourceShadow.debugDump()); } // Complete the shadow by adding attributes from the resource object PrismObject<ShadowType> resultShadow = completeShadow(connector, resourceShadow, repositoryShadow, resource, objectClassDefinition, parentResult); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Shadow when assembled:\n{}", resultShadow.debugDump()); } parentResult.recordSuccess(); return resultShadow; } catch (Exception ex) { try { boolean compensate = GetOperationOptions.isDoNotDiscovery(rootOptions)? false : true; resourceShadow = handleError(ex, repositoryShadow, FailedOperation.GET, resource, null, compensate, task, parentResult); return resourceShadow; } catch (GenericFrameworkException e) { throw new SystemException(e); } catch (ObjectAlreadyExistsException e) { throw new SystemException(e); } } } public abstract String afterAddOnResource(PrismObject<ShadowType> shadow, ResourceType resource, RefinedObjectClassDefinition objectClassDefinition, OperationResult parentResult) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException; public String addShadow(PrismObject<ShadowType> shadow, OperationProvisioningScriptsType scripts, ResourceType resource, ProvisioningOperationOptions options, Task task, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, ObjectAlreadyExistsException, SchemaException, ObjectNotFoundException, ConfigurationException, SecurityViolationException { Validate.notNull(shadow, "Object to add must not be null."); InternalMonitor.recordShadowChangeOperation(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Start adding shadow object:\n{}", shadow.debugDump()); } if (resource == null) { resource = getResource(shadow, parentResult); } PrismContainer<?> attributesContainer = shadow.findContainer( ShadowType.F_ATTRIBUTES); if (attributesContainer == null || attributesContainer.isEmpty()) { // throw new SchemaException("Attempt to add shadow without any attributes: " + shadowType); handleError(new SchemaException("Attempt to add shadow without any attributes: " + shadow), shadow, FailedOperation.ADD, resource, null, true, task, parentResult); } preprocessEntitlements(shadow, resource, parentResult); RefinedObjectClassDefinition objectClassDefinition; try { objectClassDefinition = determineObjectClassDefinition(shadow, resource); applyAttributesDefinition(shadow, resource); shadowManager.setKindIfNecessary(shadow.asObjectable(), objectClassDefinition); accessChecker.checkAdd(resource, shadow, objectClassDefinition, parentResult); ConnectorInstance connector = getConnectorInstance(resource, parentResult); shadow = resouceObjectConverter.addResourceObject(connector, resource, shadow, objectClassDefinition, scripts, parentResult); } catch (Exception ex) { shadow = handleError(ex, shadow, FailedOperation.ADD, resource, null, ProvisioningOperationOptions.isCompletePostponed(options), task, parentResult); return shadow.getOid(); } // This is where the repo shadow is created (if needed) String oid = afterAddOnResource(shadow, resource, objectClassDefinition, parentResult); shadow.setOid(oid); ObjectDelta<ShadowType> delta = ObjectDelta.createAddDelta(shadow); ResourceOperationDescription operationDescription = createSuccessOperationDescription(shadow, resource, delta, task, parentResult); operationListener.notifySuccess(operationDescription, task, parentResult); return oid; } private ResourceOperationDescription createSuccessOperationDescription(PrismObject<ShadowType> shadowType, ResourceType resource, ObjectDelta delta, Task task, OperationResult parentResult) { ResourceOperationDescription operationDescription = new ResourceOperationDescription(); operationDescription.setCurrentShadow(shadowType); operationDescription.setResource(resource.asPrismObject()); if (task != null){ operationDescription.setSourceChannel(task.getChannel()); } operationDescription.setObjectDelta(delta); operationDescription.setResult(parentResult); return operationDescription; } public abstract void afterModifyOnResource(PrismObject<ShadowType> shadow, Collection<? extends ItemDelta> modifications, OperationResult parentResult) throws SchemaException, ObjectNotFoundException; public abstract Collection<? extends ItemDelta> beforeModifyOnResource(PrismObject<ShadowType> shadow, ProvisioningOperationOptions options, Collection<? extends ItemDelta> modifications) throws SchemaException; public String modifyShadow(PrismObject<ShadowType> shadow, ResourceType resource, String oid, Collection<? extends ItemDelta> modifications, OperationProvisioningScriptsType scripts, ProvisioningOperationOptions options, Task task, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, ObjectNotFoundException, SchemaException, ConfigurationException, SecurityViolationException { Validate.notNull(shadow, "Object to modify must not be null."); Validate.notNull(oid, "OID must not be null."); Validate.notNull(modifications, "Object modification must not be null."); InternalMonitor.recordShadowChangeOperation(); if (resource == null) { resource = getResource(shadow, parentResult); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Modifying resource with oid {}, object:\n{}", resource.getOid(), shadow.debugDump()); } RefinedObjectClassDefinition objectClassDefinition = applyAttributesDefinition(shadow, resource); accessChecker.checkModify(resource, shadow, modifications, objectClassDefinition, parentResult); preprocessEntitlements(modifications, resource, parentResult); modifications = beforeModifyOnResource(shadow, options, modifications); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Applying change: {}", DebugUtil.debugDump(modifications)); } Collection<PropertyModificationOperation> sideEffectChanges = null; ConnectorInstance connector = getConnectorInstance(resource, parentResult); try { sideEffectChanges = resouceObjectConverter.modifyResourceObject(connector, resource, objectClassDefinition, shadow, scripts, modifications, parentResult); } catch (Exception ex) { LOGGER.debug("Provisioning exception: {}:{}, attempting to handle it", new Object[] { ex.getClass(), ex.getMessage(), ex }); try { shadow = handleError(ex, shadow, FailedOperation.MODIFY, resource, modifications, ProvisioningOperationOptions.isCompletePostponed(options), task, parentResult); parentResult.computeStatus(); } catch (ObjectAlreadyExistsException e) { parentResult.recordFatalError( "While compensating communication problem for modify operation got: " + ex.getMessage(), ex); throw new SystemException(e); } return shadow.getOid(); } afterModifyOnResource(shadow, modifications, parentResult); Collection<PropertyDelta<?>> renameDeltas = distillRenameDeltas(modifications, shadow, objectClassDefinition); Collection<? extends ItemDelta> sideEffectDelta = convertToPropertyDelta(sideEffectChanges); if (renameDeltas != null) { ((Collection) sideEffectDelta).addAll(renameDeltas); } if (!sideEffectDelta.isEmpty()) { try { repositoryService.modifyObject(shadow.getCompileTimeClass(), oid, sideEffectDelta, parentResult); } catch (ObjectAlreadyExistsException ex) { parentResult.recordFatalError("Side effect changes could not be applied", ex); LOGGER.error("Side effect changes could not be applied. " + ex.getMessage(), ex); throw new SystemException("Side effect changes could not be applied. " + ex.getMessage(), ex); } } ObjectDelta<ShadowType> delta = ObjectDelta.createModifyDelta(shadow.getOid(), modifications, shadow.getCompileTimeClass(), prismContext); ResourceOperationDescription operationDescription = createSuccessOperationDescription(shadow, resource, delta, task, parentResult); operationListener.notifySuccess(operationDescription, task, parentResult); parentResult.recordSuccess(); return oid; } private Collection<PropertyDelta<?>> distillRenameDeltas(Collection<? extends ItemDelta> modifications, PrismObject<ShadowType> shadow, RefinedObjectClassDefinition objectClassDefinition) throws SchemaException { PropertyDelta<String> nameDelta = (PropertyDelta<String>) ItemDelta.findItemDelta(modifications, new ItemPath(ShadowType.F_ATTRIBUTES, ConnectorFactoryIcfImpl.ICFS_NAME), ItemDelta.class); if (nameDelta == null){ return null; } PrismProperty<String> name = nameDelta.getPropertyNew(); String newName = name.getRealValue(); Collection<PropertyDelta<?>> deltas = new ArrayList<PropertyDelta<?>>(); // $shadow/attributes/icfs:name String normalizedNewName = shadowManager.getNormalizedAttributeValue(name.getValue(), objectClassDefinition.findAttributeDefinition(name.getElementName())); PropertyDelta<String> cloneNameDelta = nameDelta.clone(); cloneNameDelta.clearValuesToReplace(); cloneNameDelta.setValueToReplace(new PrismPropertyValue<String>(normalizedNewName)); deltas.add(cloneNameDelta); // $shadow/name if (!newName.equals(shadow.asObjectable().getName().getOrig())){ PropertyDelta<?> shadowNameDelta = PropertyDelta.createModificationReplaceProperty(ShadowType.F_NAME, shadow.getDefinition(), new PolyString(newName)); deltas.add(shadowNameDelta); } return deltas; } private Collection<? extends ItemDelta> convertToPropertyDelta( Collection<PropertyModificationOperation> sideEffectChanges) { Collection<PropertyDelta> sideEffectDelta = new ArrayList<PropertyDelta>(); if (sideEffectChanges != null) { for (PropertyModificationOperation mod : sideEffectChanges){ sideEffectDelta.add(mod.getPropertyDelta()); } } return sideEffectDelta; } public void deleteShadow(PrismObject<ShadowType> shadow, ProvisioningOperationOptions options, OperationProvisioningScriptsType scripts, ResourceType resource, Task task, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, ObjectNotFoundException, SchemaException, ConfigurationException, SecurityViolationException { Validate.notNull(shadow, "Object to delete must not be null."); Validate.notNull(parentResult, "Operation result must not be null."); InternalMonitor.recordShadowChangeOperation(); if (resource == null) { try { resource = getResource(shadow, parentResult); } catch (ObjectNotFoundException ex) { // if the force option is set, delete shadow from the repo // although the resource does not exists.. if (ProvisioningOperationOptions.isForce(options)) { parentResult.muteLastSubresultError(); getRepositoryService().deleteObject(ShadowType.class, shadow.getOid(), parentResult); parentResult.recordHandledError("Resource defined in shadow does not exists. Shadow was deleted from the repository."); return; } } RefinedObjectClassDefinition objectClassDefinition = applyAttributesDefinition(shadow, resource); ConnectorInstance connector = getConnectorInstance(resource, parentResult); LOGGER.trace("Deleting obeject {} from the resource {}.", shadow, resource); if (shadow.asObjectable().getFailedOperationType() == null || (shadow.asObjectable().getFailedOperationType() != null && FailedOperationTypeType.ADD != shadow.asObjectable().getFailedOperationType())) { try { resouceObjectConverter.deleteResourceObject(connector, resource, shadow, objectClassDefinition, scripts, parentResult); } catch (Exception ex) { try { handleError(ex, shadow, FailedOperation.DELETE, resource, null, ProvisioningOperationOptions.isCompletePostponed(options), task, parentResult); } catch (ObjectAlreadyExistsException e) { e.printStackTrace(); } return; } } LOGGER.trace("Detele object with oid {} form repository.", shadow.getOid()); try { getRepositoryService().deleteObject(ShadowType.class, shadow.getOid(), parentResult); ObjectDelta<ShadowType> delta = ObjectDelta.createDeleteDelta(shadow.getCompileTimeClass(), shadow.getOid(), prismContext); ResourceOperationDescription operationDescription = createSuccessOperationDescription(shadow, resource, delta, task, parentResult); operationListener.notifySuccess(operationDescription, task, parentResult); } catch (ObjectNotFoundException ex) { parentResult.recordFatalError("Can't delete object " + shadow + ". Reason: " + ex.getMessage(), ex); throw new ObjectNotFoundException("An error occured while deleting resource object " + shadow + "whith identifiers " + shadow + ": " + ex.getMessage(), ex); } LOGGER.trace("Object deleted from repository successfully."); parentResult.recordSuccess(); resourceTypeManager.modifyResourceAvailabilityStatus(resource.asPrismObject(), AvailabilityStatusType.UP, parentResult); } } public void applyDefinition(ObjectDelta<ShadowType> delta, ShadowType shadowTypeWhenNoOid, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { PrismObject<ShadowType> shadow = null; ResourceShadowDiscriminator discriminator = null; if (delta.isAdd()) { shadow = delta.getObjectToAdd(); } else if (delta.isModify()) { if (delta instanceof ShadowDiscriminatorObjectDelta) { // This one does not have OID, it has to be specially processed discriminator = ((ShadowDiscriminatorObjectDelta) delta).getDiscriminator(); } else { String shadowOid = delta.getOid(); if (shadowOid == null) { if (shadowTypeWhenNoOid == null) { throw new IllegalArgumentException("No OID in object delta " + delta + " and no externally-supplied shadow is present as well."); } shadow = shadowTypeWhenNoOid.asPrismObject(); } else { shadow = repositoryService.getObject(delta.getObjectTypeClass(), shadowOid, null, parentResult); } } } else { // Delete delta, nothing to do at all return; } if (shadow == null) { ResourceType resource = resourceTypeManager.getResource(discriminator.getResourceOid(), parentResult).asObjectable(); applyAttributesDefinition(delta, discriminator, resource); } else { ResourceType resource = getResource(shadow, parentResult); applyAttributesDefinition(delta, shadow, resource); } } public void applyDefinition(PrismObject<ShadowType> shadow, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { ResourceType resource = getResource(shadow, parentResult); applyAttributesDefinition(shadow, resource); } public void applyDefinition(final ObjectQuery query, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { ObjectFilter filter = query.getFilter(); String resourceOid = null; QName objectClassName = null; if (filter instanceof AndFilter){ List<? extends ObjectFilter> conditions = ((AndFilter) filter).getConditions(); resourceOid = ProvisioningUtil.getResourceOidFromFilter(conditions); objectClassName = ProvisioningUtil.getValueFromFilter(conditions, ShadowType.F_OBJECT_CLASS); } PrismObject<ResourceType> resource = resourceTypeManager.getResource(resourceOid, result); final RefinedObjectClassDefinition objectClassDef = determineObjectClassDefinition(objectClassName, resource.asObjectable(), query); applyDefinition(query, objectClassDef); } public void applyDefinition(final ObjectQuery query, final RefinedObjectClassDefinition objectClassDef) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { if (query == null) { return; } ObjectFilter filter = query.getFilter(); if (filter == null) { return; } final ItemPath attributesPath = new ItemPath(ShadowType.F_ATTRIBUTES); com.evolveum.midpoint.prism.query.Visitor visitor = new com.evolveum.midpoint.prism.query.Visitor() { @Override public void visit(ObjectFilter filter) { if (filter instanceof ValueFilter) { ValueFilter<?> valueFilter = (ValueFilter<?>)filter; ItemDefinition definition = valueFilter.getDefinition(); if (definition == null) { ItemPath itemPath = valueFilter.getFullPath(); if (attributesPath.equals(valueFilter.getParentPath())) { QName attributeName = valueFilter.getElementName(); ResourceAttributeDefinition attributeDefinition = objectClassDef.findAttributeDefinition(attributeName); if (attributeDefinition == null) { throw new TunnelException( new SchemaException("No definition for attribute "+attributeName+" in query "+query)); } valueFilter.setDefinition(attributeDefinition); } } } } }; try { filter.accept(visitor); } catch (TunnelException te) { SchemaException e = (SchemaException)te.getCause(); throw e; } } protected ResourceType getResource(PrismObject<ShadowType> shadow, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { String resourceOid = ShadowUtil.getResourceOid(shadow.asObjectable()); if (resourceOid == null) { throw new SchemaException("Shadow " + shadow + " does not have an resource OID"); } return resourceTypeManager.getResource(resourceOid, parentResult).asObjectable(); } @SuppressWarnings("rawtypes") protected PrismObject<ShadowType> handleError(Exception ex, PrismObject<ShadowType> shadow, FailedOperation op, ResourceType resource, Collection<? extends ItemDelta> modifications, boolean compensate, Task task, OperationResult parentResult) throws SchemaException, GenericFrameworkException, CommunicationException, ObjectNotFoundException, ObjectAlreadyExistsException, ConfigurationException, SecurityViolationException { // do not set result in the shadow in case of get operation, it will // resilted to misleading information // by get operation we do not modify the result in the shadow, so only // fetch result in this case needs to be set if (FailedOperation.GET != op) { shadow = extendShadow(shadow, parentResult, resource, modifications); } else { shadow.asObjectable().setResource(resource); } ErrorHandler handler = errorHandlerFactory.createErrorHandler(ex); if (handler == null) { parentResult.recordFatalError("Error without a handler. Reason: " + ex.getMessage(), ex); throw new SystemException(ex.getMessage(), ex); } LOGGER.debug("Handling provisioning exception {}:{}", new Object[] { ex.getClass(), ex.getMessage() }); LOGGER.trace("Handling provisioning exception {}:{}", new Object[] { ex.getClass(), ex.getMessage(), ex }); return handler.handleError(shadow.asObjectable(), op, ex, compensate, task, parentResult).asPrismObject(); } private PrismObject<ShadowType> extendShadow(PrismObject<ShadowType> shadow, OperationResult shadowResult, ResourceType resource, Collection<? extends ItemDelta> modifications) throws SchemaException { ShadowType shadowType = shadow.asObjectable(); shadowType.setResult(shadowResult.createOperationResultType()); shadowType.setResource(resource); if (modifications != null) { ObjectDelta<? extends ObjectType> objectDelta = ObjectDelta.createModifyDelta(shadow.getOid(), modifications, shadowType.getClass(), prismContext); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Storing delta to shadow:\n{}", objectDelta.debugDump()); } ObjectDeltaType objectDeltaType = DeltaConvertor.toObjectDeltaType(objectDelta); shadowType.setObjectChange(objectDeltaType); } return shadow; } //////////////////////////////////////////////////////////////////////////// // SEARCH //////////////////////////////////////////////////////////////////////////// public void listShadows(final ResourceType resource, final QName objectClass, final ShadowHandler<ShadowType> handler, final boolean readFromRepository, final OperationResult parentResult) throws CommunicationException, ObjectNotFoundException, SchemaException, ConfigurationException { InternalMonitor.recordShadowFetchOperation(); Validate.notNull(objectClass); if (resource == null) { parentResult.recordFatalError("Resource must not be null"); throw new IllegalArgumentException("Resource must not be null."); } searchObjectsIterativeInternal(objectClass, resource, null, null, handler, readFromRepository, parentResult); } public void searchObjectsIterative(final QName objectClassName, final ResourceType resourceType, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, final ShadowHandler<ShadowType> handler, final OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException { Validate.notNull(resourceType, "Resource must not be null."); Validate.notNull(objectClassName, "Object class must not be null."); Validate.notNull(parentResult, "Operation result must not be null."); LOGGER.trace("Searching objects iterative with obejct class {}, resource: {}.", objectClassName, resourceType); searchObjectsIterativeInternal(objectClassName, resourceType, query, options, handler, true, parentResult); } private void searchObjectsIterativeInternal(QName objectClassName, final ResourceType resourceType, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, final ShadowHandler<ShadowType> handler, final boolean readFromRepository, final OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { final ResourceSchema resourceSchema = resourceTypeManager.getResourceSchema(resourceType, parentResult); if (resourceSchema == null) { parentResult.recordFatalError("No schema for "+resourceType); throw new ConfigurationException("No schema for "+resourceType); } final RefinedObjectClassDefinition objectClassDef = determineObjectClassDefinition(objectClassName, resourceType, query); applyDefinition(query, objectClassDef); if (objectClassDef == null) { String message = "Object class " + objectClassName + " is not defined in schema of " + ObjectTypeUtil.toShortString(resourceType); LOGGER.error(message); parentResult.recordFatalError(message); throw new SchemaException(message); } GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); if (GetOperationOptions.isNoFetch(rootOptions)) { searchObjectsIterativeRepository(objectClassDef, resourceType, query, options, handler, parentResult); return; } // We need to record the fetch down here. Now it is certain that we are going to fetch from resource // (we do not have raw/noFetch option) InternalMonitor.recordShadowFetchOperation(); ObjectFilter filter = null; if (query != null) { filter = query.getFilter(); } ObjectQuery attributeQuery = null; List<ObjectFilter> attributeFilter = new ArrayList<ObjectFilter>(); if (filter instanceof AndFilter){ List<? extends ObjectFilter> conditions = ((AndFilter) filter).getConditions(); attributeFilter = getAttributeQuery(conditions, attributeFilter); if (attributeFilter.size() > 1){ attributeQuery = ObjectQuery.createObjectQuery(AndFilter.createAnd(attributeFilter)); } if (attributeFilter.size() < 1){ LOGGER.trace("No attribute filter defined in the query."); } if (attributeFilter.size() == 1){ attributeQuery = ObjectQuery.createObjectQuery(attributeFilter.get(0)); } } if (query != null && query.getPaging() != null){ if (attributeQuery == null){ attributeQuery = new ObjectQuery(); } attributeQuery.setPaging(query.getPaging()); } final ConnectorInstance connector = getConnectorInstance(resourceType, parentResult); ResultHandler<ShadowType> resultHandler = new ResultHandler<ShadowType>() { @Override public boolean handle(PrismObject<ShadowType> resourceShadow) { LOGGER.trace("Found resource object {}", SchemaDebugUtil.prettyPrint(resourceShadow)); PrismObject<ShadowType> resultShadow; try { // Try to find shadow that corresponds to the resource object if (readFromRepository) { PrismObject<ShadowType> repoShadow = lookupOrCreateShadowInRepository(connector, resourceShadow, objectClassDef, resourceType, parentResult); applyAttributesDefinition(repoShadow, resourceType); forceRenameIfNeeded(resourceShadow.asObjectable(), repoShadow.asObjectable(), objectClassDef, parentResult); resultShadow = completeShadow(connector, resourceShadow, repoShadow, resourceType, objectClassDef, parentResult); } else { resultShadow = resourceShadow; } } catch (SchemaException e) { // TODO: better error handling parentResult.recordFatalError("Schema error: " + e.getMessage(), e); LOGGER.error("Schema error: {}", e.getMessage(), e); return false; } catch (ConfigurationException e) { // TODO: better error handling parentResult.recordFatalError("Configuration error: " + e.getMessage(), e); LOGGER.error("Configuration error: {}", e.getMessage(), e); return false; } catch (ObjectNotFoundException e) { // TODO: better error handling parentResult.recordFatalError(e.getMessage(), e); LOGGER.error("{}", e.getMessage(), e); return false; } catch (ObjectAlreadyExistsException e) { // TODO: better error handling parentResult.recordFatalError(e.getMessage(), e); LOGGER.error("{}", e.getMessage(), e); return false; } catch (CommunicationException e) { // TODO: better error handling parentResult.recordFatalError(e.getMessage(), e); LOGGER.error("{}", e.getMessage(), e); return false; } catch (SecurityViolationException e) { // TODO: better error handling parentResult.recordFatalError(e.getMessage(), e); LOGGER.error("{}", e.getMessage(), e); return false; } catch (GenericConnectorException e) { // TODO: better error handling parentResult.recordFatalError(e.getMessage(), e); LOGGER.error("{}", e.getMessage(), e); return false; } return handler.handle(resultShadow.asObjectable()); } }; resouceObjectConverter.searchResourceObjects(connector, resourceType, objectClassDef, resultHandler, attributeQuery, parentResult); } private void searchObjectsIterativeRepository( RefinedObjectClassDefinition objectClassDef, final ResourceType resourceType, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, final ShadowHandler<ShadowType> shadowHandler, OperationResult parentResult) throws SchemaException { com.evolveum.midpoint.schema.ResultHandler<ShadowType> repoHandler = new com.evolveum.midpoint.schema.ResultHandler<ShadowType>() { @Override public boolean handle(PrismObject<ShadowType> object, OperationResult parentResult) { try { applyAttributesDefinition(object, resourceType); boolean cont = shadowHandler.handle(object.asObjectable()); parentResult.recordSuccess(); return cont; } catch (RuntimeException e) { parentResult.recordFatalError(e); throw e; } catch (SchemaException e) { parentResult.recordFatalError(e); throw new SystemException(e); } catch (ConfigurationException e) { parentResult.recordFatalError(e); throw new SystemException(e); } } }; shadowManager.searchObjectsIterativeRepository(objectClassDef, resourceType, query, options, repoHandler, parentResult); } private PrismObject<ShadowType> lookupOrCreateShadowInRepository(ConnectorInstance connector, PrismObject<ShadowType> resourceShadow, RefinedObjectClassDefinition objectClassDef, ResourceType resourceType, OperationResult parentResult) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, SecurityViolationException, GenericConnectorException { PrismObject<ShadowType> repoShadow = shadowManager.lookupShadowInRepository(resourceShadow, objectClassDef, resourceType, parentResult); if (repoShadow == null) { LOGGER.trace( "Shadow object (in repo) corresponding to the resource object (on the resource) was not found. The repo shadow will be created. The resource object:\n{}", SchemaDebugUtil.prettyPrint(resourceShadow)); PrismObject<ShadowType> conflictingShadow = shadowManager.lookupShadowByName(resourceShadow, objectClassDef, resourceType, parentResult); if (conflictingShadow != null){ applyAttributesDefinition(conflictingShadow, resourceType); conflictingShadow = completeShadow(connector, resourceShadow, conflictingShadow, resourceType, objectClassDef, parentResult); Task task = taskManager.createTaskInstance(); ResourceOperationDescription failureDescription = shadowManager.createResourceFailureDescription(conflictingShadow, resourceType, parentResult); changeNotificationDispatcher.notifyFailure(failureDescription, task, parentResult); shadowManager.deleteConflictedShadowFromRepo(conflictingShadow, parentResult); } // TODO: make sure that the resource object has appropriate definition (use objectClass and schema) // The resource object obviously exists on the resource, but appropriate shadow does not exist in the // repository we need to create the shadow to align repo state to the reality (resource) try { repoShadow = shadowManager.createRepositoryShadow( resourceShadow, resourceType, objectClassDef); String oid = repositoryService.addObject(repoShadow, null, parentResult); repoShadow.setOid(oid); } catch (ObjectAlreadyExistsException e) { // This should not happen. We haven't supplied an OID so is should not conflict LOGGER.error("Unexpected repository behavior: Object already exists: {}", e.getMessage(), e); throw new SystemException("Unexpected repository behavior: Object already exists: "+e.getMessage(),e); } } else { LOGGER.trace("Found shadow object in the repository {}", SchemaDebugUtil.prettyPrint(repoShadow)); } return repoShadow; } private List<ObjectFilter> getAttributeQuery(List<? extends ObjectFilter> conditions, List<ObjectFilter> attributeFilter) throws SchemaException{ ItemPath objectClassPath = new ItemPath(ShadowType.F_OBJECT_CLASS); ItemPath resourceRefPath = new ItemPath(ShadowType.F_RESOURCE_REF); for (ObjectFilter f : conditions){ if (f instanceof EqualFilter){ if (objectClassPath.equals(((EqualFilter) f).getFullPath())){ continue; } if (resourceRefPath.equals(((EqualFilter) f).getFullPath())){ continue; } attributeFilter.add(f); } else if (f instanceof NaryLogicalFilter){ attributeFilter = getAttributeQuery(((NaryLogicalFilter) f).getConditions(), attributeFilter); } else if (f instanceof SubstringFilter){ attributeFilter.add(f); } } return attributeFilter; } //////////////// ConnectorInstance getConnectorInstance(ResourceType resource, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { return connectorManager.getConfiguredConnectorInstance(resource.asPrismObject(), false, parentResult); } /////////////////////////////////////////////////////////////////////////// // TODO: maybe split this to a separate class /////////////////////////////////////////////////////////////////////////// public List<Change<ShadowType>> fetchChanges(ResourceType resourceType, QName objectClass, PrismProperty<?> lastToken, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, GenericFrameworkException, SchemaException, ConfigurationException, SecurityViolationException, ObjectAlreadyExistsException { InternalMonitor.recordShadowOtherOperation(); RefinedObjectClassDefinition refinedObjectClassDefinition = determineObjectClassDefinition(objectClass, resourceType); ConnectorInstance connector = getConnectorInstance(resourceType, parentResult); List<Change<ShadowType>> changes = null; try { changes = resouceObjectConverter.fetchChanges(connector, resourceType, refinedObjectClassDefinition, lastToken, parentResult); LOGGER.trace("Found {} change(s). Start processing it (them).", changes.size()); for (Iterator<Change<ShadowType>> i = changes.iterator(); i.hasNext();) { // search objects in repository Change<ShadowType> change = i.next(); processChange(resourceType, refinedObjectClassDefinition, objectClass, parentResult, change, connector); } } catch (SchemaException ex) { parentResult.recordFatalError("Schema error: " + ex.getMessage(), ex); throw ex; } catch (CommunicationException ex) { parentResult.recordFatalError("Communication error: " + ex.getMessage(), ex); throw ex; } catch (GenericFrameworkException ex) { parentResult.recordFatalError("Generic error: " + ex.getMessage(), ex); throw ex; } catch (ConfigurationException ex) { parentResult.recordFatalError("Configuration error: " + ex.getMessage(), ex); throw ex; } catch (ObjectNotFoundException ex){ parentResult.recordFatalError("Object not found error: " + ex.getMessage(), ex); throw ex; } catch (ObjectAlreadyExistsException ex){ parentResult.recordFatalError("Already exists error: " + ex.getMessage(), ex); throw ex; } parentResult.recordSuccess(); return changes; } @SuppressWarnings("rawtypes") boolean processSynchronization(Change<ShadowType> change, Task task, ResourceType resourceType, String channel, OperationResult result) throws SchemaException, ObjectNotFoundException, ObjectAlreadyExistsException { // int processedChanges = 0; // // for each change from the connector create change description // for (Change change : changes) { // // // this is the case,when we want to skip processing of change, // // because the shadow was not created or found to the resource // // object // // it may be caused with the fact, that the object which was // // created in the resource was deleted before the sync run // // such a change should be skipped to process consistent changes // if (change.getOldShadow() == null) { // PrismProperty<?> newToken = change.getToken(); // task.setExtensionProperty(newToken); // processedChanges++; // LOGGER.debug("Skipping processing change. Can't find appropriate shadow (e.g. the object was deleted on the resource meantime)."); // continue; // } ResourceObjectShadowChangeDescription shadowChangeDescription = createResourceShadowChangeDescription( change, resourceType, channel); if (LOGGER.isTraceEnabled()) { LOGGER.trace("**PROVISIONING: Created resource object shadow change description {}", SchemaDebugUtil.prettyPrint(shadowChangeDescription)); } OperationResult notifyChangeResult = new OperationResult(ShadowCache.class.getName() + "notifyChange"); notifyChangeResult.addParam("resourceObjectShadowChangeDescription", shadowChangeDescription); try { notifyResourceObjectChangeListeners(shadowChangeDescription, task, notifyChangeResult); notifyChangeResult.recordSuccess(); } catch (RuntimeException ex) { // recordFatalError(LOGGER, notifyChangeResult, "Synchronization error: " + ex.getMessage(), ex); saveAccountResult(shadowChangeDescription, change, notifyChangeResult, result); throw new SystemException("Synchronization error: " + ex.getMessage(), ex); } notifyChangeResult.computeStatus("Error by notify change operation."); boolean successfull = false; if (notifyChangeResult.isSuccess()) { deleteShadowFromRepo(change, result); successfull = true; // // get updated token from change, // // create property modification from new token // // and replace old token with the new one // PrismProperty<?> newToken = change.getToken(); // task.setExtensionProperty(newToken); // processedChanges++; } else { successfull =false; saveAccountResult(shadowChangeDescription, change, notifyChangeResult, result); } return successfull; // } // // also if no changes was detected, update token // if (changes.isEmpty() && tokenProperty != null) { // LOGGER.trace("No changes to synchronize on " + ObjectTypeUtil.toShortString(resourceType)); // task.setExtensionProperty(tokenProperty); // } // task.savePendingModifications(result); // return processedChanges; } private void notifyResourceObjectChangeListeners(ResourceObjectShadowChangeDescription change, Task task, OperationResult parentResult) { changeNotificationDispatcher.notifyChange(change, task, parentResult); } @SuppressWarnings("unchecked") private ResourceObjectShadowChangeDescription createResourceShadowChangeDescription(Change<ShadowType> change, ResourceType resourceType, String channel) { ResourceObjectShadowChangeDescription shadowChangeDescription = new ResourceObjectShadowChangeDescription(); shadowChangeDescription.setObjectDelta(change.getObjectDelta()); shadowChangeDescription.setResource(resourceType.asPrismObject()); shadowChangeDescription.setOldShadow(change.getOldShadow()); shadowChangeDescription.setCurrentShadow(change.getCurrentShadow()); if (null == channel){ shadowChangeDescription.setSourceChannel(QNameUtil.qNameToUri(SchemaConstants.CHANGE_CHANNEL_LIVE_SYNC)); } else{ shadowChangeDescription.setSourceChannel(channel); } return shadowChangeDescription; } @SuppressWarnings("rawtypes") private void saveAccountResult(ResourceObjectShadowChangeDescription shadowChangeDescription, Change change, OperationResult notifyChangeResult, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { Collection<? extends ItemDelta> shadowModification = createShadowResultModification(change, notifyChangeResult); String oid = getOidFromChange(change); // maybe better error handling is needed try{ repositoryService.modifyObject(ShadowType.class, oid, shadowModification, parentResult); } catch (SchemaException ex){ parentResult.recordPartialError("Couldn't modify object: schema violation: " + ex.getMessage(), ex); // throw ex; } catch (ObjectNotFoundException ex){ parentResult.recordWarning("Couldn't modify object: object not found: " + ex.getMessage(), ex); // throw ex; } catch (ObjectAlreadyExistsException ex){ parentResult.recordPartialError("Couldn't modify object: object already exists: " + ex.getMessage(), ex); // throw ex; } } private PrismObjectDefinition<ShadowType> getResourceObjectShadowDefinition() { // if (resourceObjectShadowDefinition == null) { return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass( ShadowType.class); // } // return resourceObjectShadowDefinition; } @SuppressWarnings("rawtypes") private Collection<? extends ItemDelta> createShadowResultModification(Change change, OperationResult shadowResult) { PrismObjectDefinition<ShadowType> shadowDefinition = getResourceObjectShadowDefinition(); Collection<ItemDelta> modifications = new ArrayList<ItemDelta>(); PropertyDelta resultDelta = PropertyDelta.createModificationReplaceProperty( ShadowType.F_RESULT, shadowDefinition, shadowResult.createOperationResultType()); modifications.add(resultDelta); if (change.getObjectDelta() != null && change.getObjectDelta().getChangeType() == ChangeType.DELETE) { PropertyDelta failedOperationTypeDelta = PropertyDelta.createModificationReplaceProperty(ShadowType.F_FAILED_OPERATION_TYPE, shadowDefinition, FailedOperationTypeType.DELETE); modifications.add(failedOperationTypeDelta); } return modifications; } private String getOidFromChange(Change change){ String shadowOid = null; if (change.getObjectDelta() != null && change.getObjectDelta().getOid() != null) { shadowOid = change.getObjectDelta().getOid(); } else { if (change.getCurrentShadow().getOid() != null) { shadowOid = change.getCurrentShadow().getOid(); } else { if (change.getOldShadow().getOid() != null) { shadowOid = change.getOldShadow().getOid(); } else { throw new IllegalArgumentException("No oid value defined for the object to synchronize."); } } } return shadowOid; } private void deleteShadowFromRepo(Change change, OperationResult parentResult) throws ObjectNotFoundException { if (change.getObjectDelta() != null && change.getObjectDelta().getChangeType() == ChangeType.DELETE && change.getOldShadow() != null) { LOGGER.debug("Deleting detected shadow object form repository."); try { repositoryService.deleteObject(ShadowType.class, change.getOldShadow().getOid(), parentResult); } catch (ObjectNotFoundException ex) { parentResult.recordFatalError("Can't find object " + change.getOldShadow() + " in repository."); throw new ObjectNotFoundException("Can't find object " + change.getOldShadow() + " in repository."); } LOGGER.debug("Shadow object deleted successfully form repository."); } } void processChange(ResourceType resourceType, RefinedObjectClassDefinition refinedObjectClassDefinition, QName objectClass, OperationResult parentResult, Change<ShadowType> change, ConnectorInstance connector) throws SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ObjectNotFoundException, GenericConnectorException, ObjectAlreadyExistsException{ if (refinedObjectClassDefinition == null){ refinedObjectClassDefinition = determineObjectClassDefinition(objectClass, resourceType); } PrismObject<ShadowType> oldShadow = change.getOldShadow(); if (oldShadow == null){ oldShadow = shadowManager.findOrCreateShadowFromChange(resourceType, change, refinedObjectClassDefinition, parentResult); } if (oldShadow != null) { applyAttributesDefinition(oldShadow, resourceType); ShadowType oldShadowType = oldShadow.asObjectable(); LOGGER.trace("Old shadow: {}", oldShadow); // skip setting other attribute when shadow is null if (oldShadow == null) { change.setOldShadow(null); return; } resouceObjectConverter.setProtectedFlag(resourceType, refinedObjectClassDefinition, oldShadow); change.setOldShadow(oldShadow); if (change.getCurrentShadow() != null) { PrismObject<ShadowType> currentShadow = completeShadow(connector, change.getCurrentShadow(), oldShadow, resourceType, refinedObjectClassDefinition, parentResult); change.setCurrentShadow(currentShadow); ShadowType currentShadowType = currentShadow.asObjectable(); forceRenameIfNeeded(currentShadowType, oldShadowType, refinedObjectClassDefinition, parentResult); } // FIXME: hack. the object delta must have oid specified. if (change.getObjectDelta() != null && change.getObjectDelta().getOid() == null) { ObjectDelta<ShadowType> objDelta = new ObjectDelta<ShadowType>(ShadowType.class, ChangeType.DELETE, prismContext); change.setObjectDelta(objDelta); change.getObjectDelta().setOid(oldShadow.getOid()); } } else { LOGGER.debug("No old shadow for synchronization event {}, the shadow must be gone in the meantime (this is probably harmless)", change); } } private void forceRenameIfNeeded(ShadowType currentShadowType, ShadowType oldShadowType, RefinedObjectClassDefinition refinedObjectClassDefinition, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, ObjectAlreadyExistsException { Collection<ResourceAttribute<?>> oldSecondaryIdentifiers = ShadowUtil.getSecondaryIdentifiers(oldShadowType); if (oldSecondaryIdentifiers.isEmpty()){ return; } if (oldSecondaryIdentifiers.size() > 1){ return; } ResourceAttribute<?> oldSecondaryIdentifier = oldSecondaryIdentifiers.iterator().next(); Object oldValue = oldSecondaryIdentifier.getRealValue(); Collection<ResourceAttribute<?>> newSecondaryIdentifiers = ShadowUtil.getSecondaryIdentifiers(currentShadowType); if (newSecondaryIdentifiers.isEmpty()){ return; } if (newSecondaryIdentifiers.size() > 1){ return; } ResourceAttribute newSecondaryIdentifier = newSecondaryIdentifiers.iterator().next(); Object newValue = newSecondaryIdentifier.getRealValue(); if (!shadowManager.compareAttribute(refinedObjectClassDefinition, newSecondaryIdentifier, oldValue)){ Collection<PropertyDelta> renameDeltas = new ArrayList<PropertyDelta>(); PropertyDelta<?> shadowNameDelta = PropertyDelta.createModificationReplaceProperty(ShadowType.F_NAME, oldShadowType.asPrismObject().getDefinition(), ProvisioningUtil.determineShadowName(currentShadowType.asPrismObject())); renameDeltas.add(shadowNameDelta); shadowNameDelta = PropertyDelta.createModificationReplaceProperty(new ItemPath(ShadowType.F_ATTRIBUTES, ConnectorFactoryIcfImpl.ICFS_NAME), oldShadowType.asPrismObject().getDefinition(), newValue); renameDeltas.add(shadowNameDelta); repositoryService.modifyObject(ShadowType.class, oldShadowType.getOid(), renameDeltas, parentResult); } } public PrismProperty<?> fetchCurrentToken(ResourceType resourceType, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException { InternalMonitor.recordShadowOtherOperation(); Validate.notNull(resourceType, "Resource must not be null."); Validate.notNull(parentResult, "Operation result must not be null."); ObjectClassComplexTypeDefinition objecClassDefinition = determineDefaultAccountObjectClassDefinition(resourceType); ConnectorInstance connector = getConnectorInstance(resourceType, parentResult); LOGGER.trace("Getting last token"); PrismProperty<?> lastToken = null; try { ResourceSchema resourceSchema = resourceTypeManager.getResourceSchema(resourceType, parentResult); if (resourceSchema == null) { throw new ConfigurationException("No schema for "+resourceType); } lastToken = resouceObjectConverter.fetchCurrentToken(connector, resourceType, objecClassDefinition, parentResult); } catch (CommunicationException e) { parentResult.recordFatalError(e.getMessage(), e); throw e; } catch (ConfigurationException e) { parentResult.recordFatalError(e.getMessage(), e); throw e; } LOGGER.trace("Got last token: {}", SchemaDebugUtil.prettyPrint(lastToken)); parentResult.recordSuccess(); return lastToken; } ////////////////////////////////////////////////////////////////////////////////////// public ObjectClassComplexTypeDefinition applyAttributesDefinition(ObjectDelta<ShadowType> delta, ResourceShadowDiscriminator discriminator, ResourceType resource) throws SchemaException, ConfigurationException { ObjectClassComplexTypeDefinition objectClassDefinition = determineObjectClassDefinition(discriminator, resource); return applyAttributesDefinition(delta, objectClassDefinition, resource); } public ObjectClassComplexTypeDefinition applyAttributesDefinition(ObjectDelta<ShadowType> delta, PrismObject<ShadowType> shadow, ResourceType resource) throws SchemaException, ConfigurationException { ObjectClassComplexTypeDefinition objectClassDefinition = determineObjectClassDefinition(shadow, resource); return applyAttributesDefinition(delta, objectClassDefinition, resource); } private ObjectClassComplexTypeDefinition applyAttributesDefinition(ObjectDelta<ShadowType> delta, ObjectClassComplexTypeDefinition objectClassDefinition, ResourceType resource) throws SchemaException, ConfigurationException { if (delta.isAdd()) { applyAttributesDefinition(delta.getObjectToAdd(), resource); } else if (delta.isModify()) { ItemPath attributesPath = new ItemPath(ShadowType.F_ATTRIBUTES); for(ItemDelta<?> modification: delta.getModifications()) { if (modification.getDefinition() == null && attributesPath.equals(modification.getParentPath())) { QName attributeName = modification.getElementName(); ResourceAttributeDefinition attributeDefinition = objectClassDefinition.findAttributeDefinition(attributeName); if (attributeDefinition == null) { throw new SchemaException("No definition for attribute "+attributeName+" in object delta "+delta); } modification.applyDefinition(attributeDefinition); } } } return objectClassDefinition; } public RefinedObjectClassDefinition applyAttributesDefinition( PrismObject<ShadowType> shadow, ResourceType resource) throws SchemaException, ConfigurationException { RefinedObjectClassDefinition objectClassDefinition = determineObjectClassDefinition(shadow, resource); PrismContainer<?> attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); if (attributesContainer != null) { if (attributesContainer instanceof ResourceAttributeContainer) { if (attributesContainer.getDefinition() == null) { attributesContainer.applyDefinition(objectClassDefinition.toResourceAttributeContainerDefinition()); } } else { // We need to convert <attributes> to ResourceAttributeContainer ResourceAttributeContainer convertedContainer = ResourceAttributeContainer.convertFromContainer( attributesContainer, objectClassDefinition); shadow.getValue().replace(attributesContainer, convertedContainer); } } // We also need to replace the entire object definition to inject correct object class definition here // If we don't do this then the patch (delta.applyTo) will not work correctly because it will not be able to // create the attribute container if needed. PrismObjectDefinition<ShadowType> objectDefinition = shadow.getDefinition(); PrismContainerDefinition<ShadowAttributesType> origAttrContainerDef = objectDefinition.findContainerDefinition(ShadowType.F_ATTRIBUTES); if (origAttrContainerDef == null || !(origAttrContainerDef instanceof ResourceAttributeContainerDefinition)) { PrismObjectDefinition<ShadowType> clonedDefinition = objectDefinition.cloneWithReplacedDefinition(ShadowType.F_ATTRIBUTES, objectClassDefinition.toResourceAttributeContainerDefinition()); shadow.setDefinition(clonedDefinition); } return objectClassDefinition; } private RefinedObjectClassDefinition determineObjectClassDefinition(PrismObject<ShadowType> shadow, ResourceType resource) throws SchemaException, ConfigurationException { ShadowType shadowType = shadow.asObjectable(); RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource, prismContext); if (refinedSchema == null) { throw new ConfigurationException("No schema definied for "+resource); } RefinedObjectClassDefinition objectClassDefinition = null; ShadowKindType kind = shadowType.getKind(); String intent = shadowType.getIntent(); QName objectClass = shadow.asObjectable().getObjectClass(); if (kind != null) { objectClassDefinition = refinedSchema.getRefinedDefinition(kind, intent); } if (objectClassDefinition == null) { // Fallback to objectclass only if (objectClass == null) { throw new SchemaException("No kind nor objectclass definied in "+shadow); } objectClassDefinition = refinedSchema.findRefinedDefinitionByObjectClassQName(null, objectClass); } if (objectClassDefinition == null) { throw new SchemaException("Definition for "+shadow+" not found (objectClass=" + PrettyPrinter.prettyPrint(objectClass) + ", kind="+kind+", intent='"+intent+"') in schema of " + resource); } return objectClassDefinition; } private ObjectClassComplexTypeDefinition determineObjectClassDefinition( ResourceShadowDiscriminator discriminator, ResourceType resource) throws SchemaException { ResourceSchema schema = RefinedResourceSchema.getResourceSchema(resource, prismContext); // HACK FIXME ObjectClassComplexTypeDefinition objectClassDefinition = schema.findObjectClassDefinition(ShadowKindType.ACCOUNT, discriminator.getIntent()); if (objectClassDefinition == null) { // Unknown objectclass throw new SchemaException("Account type " + discriminator.getIntent() + " is not known in schema of " + resource); } return objectClassDefinition; } private RefinedObjectClassDefinition determineObjectClassDefinition( QName objectClassName, ResourceType resourceType, ObjectQuery query) throws SchemaException, ConfigurationException { ShadowKindType kind = null; String intent = null; if (query != null && query.getFilter() != null) { List<? extends ObjectFilter> conditions = ((AndFilter) query.getFilter()).getConditions(); kind = ProvisioningUtil.getValueFromFilter(conditions, ShadowType.F_KIND); intent = ProvisioningUtil.getValueFromFilter(conditions, ShadowType.F_INTENT); } RefinedObjectClassDefinition objectClassDefinition; if (kind == null) { objectClassDefinition = getRefinedScema(resourceType).getRefinedDefinition(objectClassName); } else { objectClassDefinition = getRefinedScema(resourceType).getRefinedDefinition(kind, intent); } return objectClassDefinition; } private RefinedObjectClassDefinition determineObjectClassDefinition(QName objectClassName, ResourceType resourceType) throws SchemaException, ConfigurationException { return getRefinedScema(resourceType).getRefinedDefinition(objectClassName); } private ObjectClassComplexTypeDefinition determineDefaultAccountObjectClassDefinition(ResourceType resourceType) throws SchemaException, ConfigurationException { // HACK, FIXME return getRefinedScema(resourceType).getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); } private RefinedResourceSchema getRefinedScema(ResourceType resourceType) throws SchemaException, ConfigurationException { RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resourceType); if (refinedSchema == null) { throw new ConfigurationException("No schema for "+resourceType); } return refinedSchema; } /** * Make sure that the shadow is complete, e.g. that all the mandatory fields * are filled (e.g name, resourceRef, ...) Also transforms the shadow with * respect to simulated capabilities. */ private PrismObject<ShadowType> completeShadow(ConnectorInstance connector, PrismObject<ShadowType> resourceShadow, PrismObject<ShadowType> repoShadow, ResourceType resource, RefinedObjectClassDefinition objectClassDefinition, OperationResult parentResult) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, SecurityViolationException, GenericConnectorException { PrismObject<ShadowType> resultShadow = repoShadow.clone(); boolean resultIsResourceShadowClone = false; if (resultShadow == null) { resultShadow = resourceShadow.clone(); resultIsResourceShadowClone = true; } assert resultShadow.getPrismContext() != null : "No prism context in resultShadow"; ResourceAttributeContainer resourceAttributesContainer = ShadowUtil .getAttributesContainer(resourceShadow); ShadowType resultShadowType = resultShadow.asObjectable(); ShadowType repoShadowType = repoShadow.asObjectable(); ShadowType resourceShadowType = resourceShadow.asObjectable(); if (resultShadowType.getObjectClass() == null) { resultShadowType.setObjectClass(resourceAttributesContainer.getDefinition().getTypeName()); } if (resultShadowType.getName() == null) { resultShadowType.setName(new PolyStringType(ProvisioningUtil.determineShadowName(resourceShadow))); } if (resultShadowType.getResource() == null) { resultShadowType.setResourceRef(ObjectTypeUtil.createObjectRef(resource)); } // If the shadows are the same then no copy is needed. This was already copied by clone. if (!resultIsResourceShadowClone) { // Attributes resultShadow.removeContainer(ShadowType.F_ATTRIBUTES); ResourceAttributeContainer resultAttibutes = resourceAttributesContainer.clone(); accessChecker.filterGetAttributes(resultAttibutes, objectClassDefinition, parentResult); resultShadow.add(resultAttibutes); resultShadowType.setProtectedObject(resourceShadowType.isProtectedObject()); resultShadowType.setIgnored(resourceShadowType.isIgnored()); resultShadowType.setActivation(resourceShadowType.getActivation()); // Credentials ShadowType resultAccountShadow = resultShadow.asObjectable(); ShadowType resourceAccountShadow = resourceShadow.asObjectable(); resultAccountShadow.setCredentials(resourceAccountShadow.getCredentials()); } // Activation ActivationType resultActivationType = resultShadowType.getActivation(); ActivationType repoActivation = repoShadowType.getActivation(); if (repoActivation != null) { if (resultActivationType == null) { resultActivationType = new ActivationType(); resultShadowType.setActivation(resultActivationType); } resultActivationType.setId(repoActivation.getId()); // .. but we want metadata from repo resultActivationType.setDisableReason(repoActivation.getDisableReason()); resultActivationType.setEnableTimestamp(repoActivation.getEnableTimestamp()); resultActivationType.setDisableTimestamp(repoActivation.getDisableTimestamp()); resultActivationType.setArchiveTimestamp(repoActivation.getArchiveTimestamp()); resultActivationType.setValidityChangeTimestamp(repoActivation.getValidityChangeTimestamp()); } // Associations PrismContainer<ShadowAssociationType> resourceAssociationContainer = resourceShadow.findContainer(ShadowType.F_ASSOCIATION); if (resourceAssociationContainer != null) { RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); PrismContainer<ShadowAssociationType> associationContainer = resourceAssociationContainer.clone(); resultShadow.add(associationContainer); if (associationContainer != null) { for (PrismContainerValue<ShadowAssociationType> associationCVal: associationContainer.getValues()) { ResourceAttributeContainer identifierContainer = ShadowUtil.getAttributesContainer(associationCVal, ShadowAssociationType.F_IDENTIFIERS); Collection<ResourceAttribute<?>> entitlementIdentifiers = identifierContainer.getAttributes(); if (entitlementIdentifiers == null || entitlementIdentifiers.isEmpty()) { throw new IllegalStateException("No entitlement identifiers present for association "+associationCVal); } ShadowAssociationType shadowAssociationType = associationCVal.asContainerable(); QName associationName = shadowAssociationType.getName(); RefinedAssociationDefinition rEntitlementAssociation = objectClassDefinition.findEntitlementAssociation(associationName); String entitlementIntent = rEntitlementAssociation.getIntent(); RefinedObjectClassDefinition entitlementObjectClassDef = refinedSchema.getRefinedDefinition(ShadowKindType.ENTITLEMENT, entitlementIntent); PrismObject<ShadowType> entitlementShadow = (PrismObject<ShadowType>) identifierContainer.getUserData(ResourceObjectConverter.FULL_SHADOW_KEY); if (entitlementShadow == null) { entitlementShadow = resouceObjectConverter.locateResourceObject(connector, resource, entitlementIdentifiers, entitlementObjectClassDef, parentResult); } PrismObject<ShadowType> entitlementRepoShadow = lookupOrCreateShadowInRepository(connector, entitlementShadow, entitlementObjectClassDef, resource, parentResult); ObjectReferenceType shadowRefType = new ObjectReferenceType(); shadowRefType.setOid(entitlementRepoShadow.getOid()); shadowRefType.setType(ShadowType.COMPLEX_TYPE); shadowAssociationType.setShadowRef(shadowRefType); } } } // Sanity asserts to catch some exotic bugs PolyStringType resultName = resultShadow.asObjectable().getName(); assert resultName != null : "No name generated in "+resultShadow; assert !StringUtils.isEmpty(resultName.getOrig()) : "No name (orig) in "+resultShadow; assert !StringUtils.isEmpty(resultName.getNorm()) : "No name (norm) in "+resultShadow; return resultShadow; } // ENTITLEMENTS /** * Makes sure that all the entitlements have identifiers in them so this is usable by the * ResourceObjectConverter. */ private void preprocessEntitlements(PrismObject<ShadowType> shadow, final ResourceType resource, final OperationResult result) throws SchemaException, ObjectNotFoundException, ConfigurationException { Visitor visitor = new Visitor() { @Override public void visit(Visitable visitable) { try { preprocessEntitlement((PrismContainerValue<ShadowAssociationType>)visitable, resource, result); } catch (SchemaException e) { throw new TunnelException(e); } catch (ObjectNotFoundException e) { throw new TunnelException(e); } catch (ConfigurationException e) { throw new TunnelException(e); } } }; try { shadow.accept(visitor , new ItemPath( new NameItemPathSegment(ShadowType.F_ASSOCIATION), IdItemPathSegment.WILDCARD), false); } catch (TunnelException e) { Throwable cause = e.getCause(); if (cause instanceof SchemaException) { throw (SchemaException)cause; } else if (cause instanceof ObjectNotFoundException) { throw (ObjectNotFoundException)cause; } else if (cause instanceof ConfigurationException) { throw (ConfigurationException)cause; } else { throw new SystemException("Unexpected exception "+cause, cause); } } } /** * Makes sure that all the entitlements have identifiers in them so this is usable by the * ResourceObjectConverter. */ private void preprocessEntitlements(Collection<? extends ItemDelta> modifications, final ResourceType resource, final OperationResult result) throws SchemaException, ObjectNotFoundException, ConfigurationException { Visitor visitor = new Visitor() { @Override public void visit(Visitable visitable) { try { preprocessEntitlement((PrismContainerValue<ShadowAssociationType>)visitable, resource, result); } catch (SchemaException e) { throw new TunnelException(e); } catch (ObjectNotFoundException e) { throw new TunnelException(e); } catch (ConfigurationException e) { throw new TunnelException(e); } } }; try { ItemDelta.accept(modifications, visitor , new ItemPath( new NameItemPathSegment(ShadowType.F_ASSOCIATION), IdItemPathSegment.WILDCARD), false); } catch (TunnelException e) { Throwable cause = e.getCause(); if (cause instanceof SchemaException) { throw (SchemaException)cause; } else if (cause instanceof ObjectNotFoundException) { throw (ObjectNotFoundException)cause; } else if (cause instanceof ConfigurationException) { throw (ConfigurationException)cause; } else { throw new SystemException("Unexpected exception "+cause, cause); } } } private void preprocessEntitlement(PrismContainerValue<ShadowAssociationType> association, ResourceType resource, OperationResult result) throws SchemaException, ObjectNotFoundException, ConfigurationException { PrismContainer<Containerable> identifiersContainer = association.findContainer(ShadowAssociationType.F_IDENTIFIERS); if (identifiersContainer != null && !identifiersContainer.isEmpty()) { // We already have identifiers here return; } ShadowAssociationType associationType = association.asContainerable(); if (associationType.getShadowRef() == null || StringUtils.isEmpty(associationType.getShadowRef().getOid())) { throw new SchemaException("No identifiers and no OID specified in entitlements association "+association); } PrismObject<ShadowType> repoShadow; try { repoShadow = repositoryService.getObject(ShadowType.class, associationType.getShadowRef().getOid(), null, result); } catch (ObjectNotFoundException e) { throw new ObjectNotFoundException(e.getMessage()+" while resolving entitlement association OID in "+association, e); } applyAttributesDefinition(repoShadow, resource); transplantIdentifiers(association, repoShadow); } private void transplantIdentifiers(PrismContainerValue<ShadowAssociationType> association, PrismObject<ShadowType> repoShadow) throws SchemaException { PrismContainer<Containerable> identifiersContainer = association.findContainer(ShadowAssociationType.F_IDENTIFIERS); if (identifiersContainer == null) { ResourceAttributeContainer origContainer = ShadowUtil.getAttributesContainer(repoShadow); identifiersContainer = new ResourceAttributeContainer(ShadowAssociationType.F_IDENTIFIERS, origContainer.getDefinition(), prismContext); association.add(identifiersContainer); } Collection<ResourceAttribute<?>> identifiers = ShadowUtil.getIdentifiers(repoShadow); for (ResourceAttribute<?> identifier: identifiers) { identifiersContainer.add(identifier.clone()); } Collection<ResourceAttribute<?>> secondaryIdentifiers = ShadowUtil.getSecondaryIdentifiers(repoShadow); for (ResourceAttribute<?> identifier: secondaryIdentifiers) { identifiersContainer.add(identifier.clone()); } } }
fixing MID-1863 (listing resource accounts with associations)..
provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ShadowCache.java
fixing MID-1863 (listing resource accounts with associations)..
Java
bsd-3-clause
f8251c3443fbf4960c8fbb3c1ee85d8be3ff6f66
0
jMonkeyEngine/jmonkeyengine,zzuegg/jmonkeyengine,zzuegg/jmonkeyengine,zzuegg/jmonkeyengine,jMonkeyEngine/jmonkeyengine,jMonkeyEngine/jmonkeyengine,zzuegg/jmonkeyengine,jMonkeyEngine/jmonkeyengine
/* * Copyright (c) 2009-2022 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.texture; import com.jme3.renderer.Caps; import com.jme3.renderer.Renderer; import com.jme3.texture.Image.Format; import com.jme3.util.NativeObject; import java.util.ArrayList; /** * <p> * <code>FrameBuffer</code>s are rendering surfaces allowing * off-screen rendering and render-to-texture functionality. * Instead of the scene rendering to the screen, it is rendered into the * FrameBuffer, the result can be either a texture or a buffer. * <p> * A <code>FrameBuffer</code> supports two methods of rendering, * using a {@link Texture} or using a buffer. * When using a texture, the result of the rendering will be rendered * onto the texture, after which the texture can be placed on an object * and rendered as if the texture was uploaded from disk. * When using a buffer, the result is rendered onto * a buffer located on the GPU, the data of this buffer is not accessible * to the user. buffers are useful if one * wishes to retrieve only the color content of the scene, but still desires * depth testing (which requires a depth buffer). * Buffers can be copied to other framebuffers * including the main screen, by using * {@link Renderer#copyFrameBuffer(com.jme3.texture.FrameBuffer, com.jme3.texture.FrameBuffer, boolean, boolean)}. * The content of a {@link RenderBuffer} can be retrieved by using * {@link Renderer#readFrameBuffer(com.jme3.texture.FrameBuffer, java.nio.ByteBuffer) }. * <p> * <code>FrameBuffer</code>s have several attachment points, there are * several <em>color</em> attachment points and a single <em>depth</em> * attachment point. * The color attachment points support image formats such as * {@link Format#RGBA8}, allowing rendering the color content of the scene. * The depth attachment point requires a depth image format. * * @see Renderer#setFrameBuffer(com.jme3.texture.FrameBuffer) * * @author Kirill Vainer */ public class FrameBuffer extends NativeObject { public static final int SLOT_UNDEF = -1; public static final int SLOT_DEPTH = -100; public static final int SLOT_DEPTH_STENCIL = -101; private int width = 0; private int height = 0; private int samples = 1; final private ArrayList<RenderBuffer> colorBufs = new ArrayList<>(); private RenderBuffer depthBuf = null; private int colorBufIndex = 0; private boolean srgb; private Boolean mipMapsGenerationHint = null; /** * <code>RenderBuffer</code> represents either a texture or a * buffer that will be rendered to. <code>RenderBuffer</code>s * are attached to an attachment slot on a <code>FrameBuffer</code>. */ public static class RenderBuffer { Texture tex; Image.Format format; int id = -1; int slot = SLOT_UNDEF; int face = -1; int layer = -1; int level = 0; public int getLevel() { return this.level; } /** * @return The image format of the render buffer. */ public Format getFormat() { return format; } /** * @return The texture to render to for this <code>RenderBuffer</code> * or null if content should be rendered into a buffer. */ public Texture getTexture() { return tex; } /** * Do not use. * @return the buffer's ID */ public int getId() { return id; } /** * Do not use. * * @param id the desired ID */ public void setId(int id) { this.id = id; } /** * Do not use. * * @return the slot code, such as SLOT_DEPTH_STENCIL */ public int getSlot() { return slot; } public int getFace() { return face; } public void resetObject() { id = -1; } public RenderBuffer createDestructableClone() { if (tex != null) { return null; } else { RenderBuffer destructClone = new RenderBuffer(); destructClone.id = id; return destructClone; } } @Override public String toString() { if (tex != null) { return "TextureTarget[format=" + format + "]"; } else { return "BufferTarget[format=" + format + "]"; } } public int getLayer() { return this.layer; } } public static class FrameBufferTextureTarget extends RenderBuffer { private FrameBufferTextureTarget(){} void setTexture(Texture tx){ this.tex=tx; this.format=tx.getImage().getFormat(); } void setFormat(Format f){ this.format=f; } public FrameBufferTextureTarget layer(int i){ this.layer=i; return this; } public FrameBufferTextureTarget level(int i){ this.level=i; return this; } public FrameBufferTextureTarget face(TextureCubeMap.Face f){ return face(f.ordinal()); } public FrameBufferTextureTarget face(int f){ this.face=f; return this; } } public static class FrameBufferBufferTarget extends RenderBuffer { private FrameBufferBufferTarget(){} void setFormat(Format f){ this.format=f; } } public static class FrameBufferTarget { private FrameBufferTarget(){} public static FrameBufferTextureTarget newTarget(Texture tx){ FrameBufferTextureTarget t=new FrameBufferTextureTarget(); t.setTexture(tx); return t; } public static FrameBufferBufferTarget newTarget(Format format){ FrameBufferBufferTarget t=new FrameBufferBufferTarget(); t.setFormat(format); return t; } /** * Creates a frame buffer texture and sets the face position by using the face parameter. It uses * {@link TextureCubeMap} ordinal number for the face position. * * @param tx texture to add to the frame buffer * @param face face to add to the color buffer to * @return FrameBufferTexture Target */ public static FrameBufferTextureTarget newTarget(Texture tx, TextureCubeMap.Face face) { FrameBufferTextureTarget t = new FrameBufferTextureTarget(); t.face = face.ordinal(); t.setTexture(tx); return t; } } /** * A private constructor to inhibit instantiation of this class. */ private FrameBuffer() { } public void addColorTarget(FrameBufferBufferTarget colorBuf){ colorBuf.slot=colorBufs.size(); colorBufs.add(colorBuf); } public void addColorTarget(FrameBufferTextureTarget colorBuf){ // checkSetTexture(colorBuf.getTexture(), false); // TODO: this won't work for levels. colorBuf.slot=colorBufs.size(); colorBufs.add(colorBuf); } /** * Adds a texture to one of the color Buffers Array. It uses {@link TextureCubeMap} ordinal number for the * position in the color buffer ArrayList. * * @param colorBuf texture to add to the color Buffer * @param face position to add to the color buffer */ public void addColorTarget(FrameBufferTextureTarget colorBuf, TextureCubeMap.Face face) { // checkSetTexture(colorBuf.getTexture(), false); // TODO: this won't work for levels. colorBuf.slot = colorBufs.size(); colorBuf.face = face.ordinal(); colorBufs.add(colorBuf); } public void setDepthTarget(FrameBufferBufferTarget depthBuf){ if (!depthBuf.getFormat().isDepthFormat()) throw new IllegalArgumentException("Depth buffer format must be depth."); this.depthBuf = depthBuf; this.depthBuf.slot = this.depthBuf.getFormat().isDepthStencilFormat() ? SLOT_DEPTH_STENCIL : SLOT_DEPTH; } public void setDepthTarget(FrameBufferTextureTarget depthBuf){ checkSetTexture(depthBuf.getTexture(), true); this.depthBuf = depthBuf; this.depthBuf.slot = depthBuf.getTexture().getImage().getFormat().isDepthStencilFormat() ? SLOT_DEPTH_STENCIL : SLOT_DEPTH; } public int getNumColorTargets(){ return colorBufs.size(); } public RenderBuffer getColorTarget(int index){ return colorBufs.get(index); } public RenderBuffer getColorTarget() { if (colorBufs.isEmpty()) return null; if (colorBufIndex<0 || colorBufIndex>=colorBufs.size()) { return colorBufs.get(0); } return colorBufs.get(colorBufIndex); } public RenderBuffer getDepthTarget() { return depthBuf; } /** * <p> * Creates a new FrameBuffer with the given width, height, and number * of samples. If any textures are attached to this FrameBuffer, then * they must have the same number of samples as given in this constructor. * <p> * Note that if the {@link Renderer} does not expose the * {@link Caps#NonPowerOfTwoTextures}, then an exception will be thrown * if the width and height arguments are not power of two. * * @param width The width to use * @param height The height to use * @param samples The number of samples to use for a multisampled * framebuffer, or 1 if the framebuffer should be single-sampled. * * @throws IllegalArgumentException If width or height are not positive. */ public FrameBuffer(int width, int height, int samples) { super(); if (width <= 0 || height <= 0) { throw new IllegalArgumentException("FrameBuffer must have valid size."); } this.width = width; this.height = height; this.samples = samples == 0 ? 1 : samples; } protected FrameBuffer(FrameBuffer src) { super(src.id); /* for (RenderBuffer renderBuf : src.colorBufs){ RenderBuffer clone = renderBuf.createDestructableClone(); if (clone != null) this.colorBufs.add(clone); } this.depthBuf = src.depthBuf.createDestructableClone(); */ } /** * Enables the use of a depth buffer for this <code>FrameBuffer</code>. * * @param format The format to use for the depth buffer. * @throws IllegalArgumentException If <code>format</code> is not a depth format. * @deprecated Use setDepthTarget */ @Deprecated public void setDepthBuffer(Image.Format format) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } if (!format.isDepthFormat()) { throw new IllegalArgumentException("Depth buffer format must be depth."); } depthBuf = new RenderBuffer(); depthBuf.slot = format.isDepthStencilFormat() ? SLOT_DEPTH_STENCIL : SLOT_DEPTH; depthBuf.format = format; } /** * Enables the use of a color buffer for this <code>FrameBuffer</code>. * * @param format The format to use for the color buffer. * @throws IllegalArgumentException If <code>format</code> is not a color format. * @deprecated Use addColorTarget */ @Deprecated public void setColorBuffer(Image.Format format) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } if (format.isDepthFormat()) { throw new IllegalArgumentException("Color buffer format must be color/luminance."); } RenderBuffer colorBuf = new RenderBuffer(); colorBuf.slot = 0; colorBuf.format = format; colorBufs.clear(); colorBufs.add(colorBuf); } private void checkSetTexture(Texture tex, boolean depth) { Image img = tex.getImage(); if (img == null) { throw new IllegalArgumentException("Texture not initialized with RTT."); } if (depth && !img.getFormat().isDepthFormat()) { throw new IllegalArgumentException("Texture image format must be depth."); } else if (!depth && img.getFormat().isDepthFormat()) { throw new IllegalArgumentException("Texture image format must be color/luminance."); } // check that resolution matches texture resolution if (width != img.getWidth() || height != img.getHeight()) { throw new IllegalArgumentException("Texture image resolution " + "must match FB resolution"); } if (samples != tex.getImage().getMultiSamples()) { throw new IllegalStateException("Texture samples must match framebuffer samples"); } } /** * If enabled, any shaders rendering into this <code>FrameBuffer</code> * will be able to write several results into the renderbuffers * by using the <code>gl_FragData</code> array. Every slot in that * array maps into a color buffer attached to this framebuffer. * * @param enabled True to enable MRT (multiple rendering targets). */ public void setMultiTarget(boolean enabled) { if (enabled) { colorBufIndex = -1; } else { colorBufIndex = 0; } } /** * @return True if MRT (multiple rendering targets) is enabled. * @see FrameBuffer#setMultiTarget(boolean) */ public boolean isMultiTarget() { return colorBufIndex == -1; } /** * If MRT is not enabled ({@link FrameBuffer#setMultiTarget(boolean) } is false) * then this specifies the color target to which the scene should be rendered. * <p> * By default the value is 0. * * @param index The color attachment index. * @throws IllegalArgumentException If index is negative or doesn't map * to any attachment on this framebuffer. */ public void setTargetIndex(int index) { if (index < 0 || index >= 16) { throw new IllegalArgumentException("Target index must be between 0 and 16"); } if (colorBufs.size() < index) { throw new IllegalArgumentException("The target at " + index + " is not set!"); } colorBufIndex = index; setUpdateNeeded(); } /** * @return The color target to which the scene should be rendered. * * @see FrameBuffer#setTargetIndex(int) */ public int getTargetIndex() { return colorBufIndex; } /** * Set the color texture to use for this framebuffer. * This automatically clears all existing textures added previously * with {@link FrameBuffer#addColorTexture } and adds this texture as the * only target. * * @param tex The color texture to set. * @deprecated Use addColorTarget */ @Deprecated public void setColorTexture(Texture2D tex) { clearColorTargets(); addColorTexture(tex); } /** * Set the color texture array to use for this framebuffer. * This automatically clears all existing textures added previously * with {@link FrameBuffer#addColorTexture } and adds this texture as the * only target. * * @param tex The color texture array to set. * @param layer (default=-1) * @deprecated Use addColorTarget */ @Deprecated public void setColorTexture(TextureArray tex, int layer) { clearColorTargets(); addColorTexture(tex, layer); } /** * Set the color texture to use for this framebuffer. * This automatically clears all existing textures added previously * with {@link FrameBuffer#addColorTexture } and adds this texture as the * only target. * * @param tex The cube-map texture to set. * @param face The face of the cube-map to render to. * @deprecated Use addColorTarget */ @Deprecated public void setColorTexture(TextureCubeMap tex, TextureCubeMap.Face face) { clearColorTargets(); addColorTexture(tex, face); } /** * Clears all color targets that were set or added previously. */ public void clearColorTargets() { colorBufs.clear(); } /** * Add a color buffer without a texture bound to it. * If MRT is enabled, then each subsequently added texture or buffer can be * rendered to through a shader that writes to the array <code>gl_FragData</code>. * If MRT is not enabled, then the index set with {@link FrameBuffer#setTargetIndex(int) } * is rendered to by the shader. * * @param format the format of the color buffer * @see #addColorTexture(com.jme3.texture.Texture2D) * @deprecated Use addColorTarget */ @Deprecated public void addColorBuffer(Image.Format format) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } if (format.isDepthFormat()) { throw new IllegalArgumentException("Color buffer format must be color/luminance."); } RenderBuffer colorBuf = new RenderBuffer(); colorBuf.slot = colorBufs.size(); colorBuf.format = format; colorBufs.add(colorBuf); } /** * Add a color texture to use for this framebuffer. * If MRT is enabled, then each subsequently added texture can be * rendered to through a shader that writes to the array <code>gl_FragData</code>. * If MRT is not enabled, then the index set with {@link FrameBuffer#setTargetIndex(int) } * is rendered to by the shader. * * @param tex The texture to add. * @see #addColorBuffer(com.jme3.texture.Image.Format) * @deprecated Use addColorTarget */ @Deprecated public void addColorTexture(Texture2D tex) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } Image img = tex.getImage(); checkSetTexture(tex, false); RenderBuffer colorBuf = new RenderBuffer(); colorBuf.slot = colorBufs.size(); colorBuf.tex = tex; colorBuf.format = img.getFormat(); colorBufs.add(colorBuf); } /** * Add a color texture array to use for this framebuffer. * If MRT is enabled, then each subsequently added texture can be * rendered to through a shader that writes to the array <code>gl_FragData</code>. * If MRT is not enabled, then the index set with {@link FrameBuffer#setTargetIndex(int) } * is rendered to by the shader. * * @param tex The texture array to add. * @param layer (default=-1) * @deprecated Use addColorTarget */ @Deprecated public void addColorTexture(TextureArray tex, int layer) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } Image img = tex.getImage(); checkSetTexture(tex, false); RenderBuffer colorBuf = new RenderBuffer(); colorBuf.slot = colorBufs.size(); colorBuf.tex = tex; colorBuf.format = img.getFormat(); colorBuf.layer = layer; colorBufs.add(colorBuf); } /** * Add a color texture to use for this framebuffer. * If MRT is enabled, then each subsequently added texture can be * rendered to through a shader that writes to the array <code>gl_FragData</code>. * If MRT is not enabled, then the index set with {@link FrameBuffer#setTargetIndex(int) } * is rendered to by the shader. * * @param tex The cube-map texture to add. * @param face The face of the cube-map to render to. * @deprecated Use addColorTarget */ @Deprecated public void addColorTexture(TextureCubeMap tex, TextureCubeMap.Face face) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } Image img = tex.getImage(); checkSetTexture(tex, false); RenderBuffer colorBuf = new RenderBuffer(); colorBuf.slot = colorBufs.size(); colorBuf.tex = tex; colorBuf.format = img.getFormat(); colorBuf.face = face.ordinal(); colorBufs.add(colorBuf); } /** * Set the depth texture to use for this framebuffer. * * @param tex The color texture to set. * @deprecated Use setDepthTarget */ @Deprecated public void setDepthTexture(Texture2D tex) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } Image img = tex.getImage(); checkSetTexture(tex, true); depthBuf = new RenderBuffer(); depthBuf.slot = img.getFormat().isDepthStencilFormat() ? SLOT_DEPTH_STENCIL : SLOT_DEPTH; depthBuf.tex = tex; depthBuf.format = img.getFormat(); } /** * * @param tex the TextureArray to apply * @param layer (default=-1) * @deprecated Use setDepthTarget */ @Deprecated public void setDepthTexture(TextureArray tex, int layer) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } Image img = tex.getImage(); checkSetTexture(tex, true); depthBuf = new RenderBuffer(); depthBuf.slot = img.getFormat().isDepthStencilFormat() ? SLOT_DEPTH_STENCIL : SLOT_DEPTH; depthBuf.tex = tex; depthBuf.format = img.getFormat(); depthBuf.layer = layer; } /** * @return The number of color buffers attached to this texture. * @deprecated Use getNumColorTargets */ @Deprecated public int getNumColorBuffers() { return colorBufs.size(); } /** * @param index the zero-base index (&ge;0) * @return The color buffer at the given index. * @deprecated Use getColorTarget(int) */ @Deprecated public RenderBuffer getColorBuffer(int index) { return colorBufs.get(index); } /** * @return The color buffer with the index set by {@link #setTargetIndex(int)}, or null * if no color buffers are attached. * If MRT is disabled, the first color buffer is returned. * @deprecated Use getColorTarget() */ @Deprecated public RenderBuffer getColorBuffer() { if (colorBufs.isEmpty()) { return null; } if (colorBufIndex < 0 || colorBufIndex >= colorBufs.size()) { return colorBufs.get(0); } return colorBufs.get(colorBufIndex); } /** * @return The depth buffer attached to this FrameBuffer, or null * if no depth buffer is attached * @deprecated Use getDepthTarget() */ @Deprecated public RenderBuffer getDepthBuffer() { return depthBuf; } /** * @return The height in pixels of this framebuffer. */ public int getHeight() { return height; } /** * @return The width in pixels of this framebuffer. */ public int getWidth() { return width; } /** * @return The number of samples when using a multisample framebuffer, or * 1 if this is a single-sampled framebuffer. */ public int getSamples() { return samples; } @Override public String toString() { StringBuilder sb = new StringBuilder(); String mrtStr = colorBufIndex >= 0 ? "" + colorBufIndex : "mrt"; sb.append("FrameBuffer[format=").append(width).append("x").append(height) .append("x").append(samples).append(", drawBuf=").append(mrtStr).append("]\n"); if (depthBuf != null) { sb.append("Depth => ").append(depthBuf).append("\n"); } for (RenderBuffer colorBuf : colorBufs) { sb.append("Color(").append(colorBuf.slot) .append(") => ").append(colorBuf).append("\n"); } return sb.toString(); } @Override public void resetObject() { this.id = -1; for (int i = 0; i < colorBufs.size(); i++) { colorBufs.get(i).resetObject(); } if (depthBuf != null) { depthBuf.resetObject(); } setUpdateNeeded(); } @Override public void deleteObject(Object rendererObject) { ((Renderer) rendererObject).deleteFrameBuffer(this); } @Override public NativeObject createDestructableClone() { return new FrameBuffer(this); } @Override public long getUniqueId() { return ((long) OBJTYPE_FRAMEBUFFER << 32) | ((long) id); } /** * Specifies that the color values stored in this framebuffer are in SRGB * format. * * The FrameBuffer must have an SRGB texture attached. * * The Renderer must expose the {@link Caps#Srgb sRGB pipeline} capability * for this option to take any effect. * * Rendering operations performed on this framebuffer shall undergo a linear * -&gt; sRGB color space conversion when this flag is enabled. If * {@link com.jme3.material.RenderState#getBlendMode() blending} is enabled, it will be * performed in linear space by first decoding the stored sRGB pixel values * into linear, combining with the shader result, and then converted back to * sRGB upon being written into the framebuffer. * * @param srgb If the framebuffer color values should be stored in sRGB * color space. * * @throws IllegalStateException If the texture attached to this framebuffer * is not sRGB. */ public void setSrgb(boolean srgb) { this.srgb = srgb; } /** * Determines if this framebuffer contains SRGB data. * * @return True if the framebuffer color values are in SRGB space, false if * in linear space. */ public boolean isSrgb() { return srgb; } /** * Hints the renderer to generate mipmaps for this framebuffer if necessary * @param v true to enable, null to use the default value for the renderer (default to null) */ public void setMipMapsGenerationHint(Boolean v) { mipMapsGenerationHint = v; } public Boolean getMipMapsGenerationHint() { return mipMapsGenerationHint; } }
jme3-core/src/main/java/com/jme3/texture/FrameBuffer.java
/* * Copyright (c) 2009-2021 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.texture; import com.jme3.renderer.Caps; import com.jme3.renderer.Renderer; import com.jme3.texture.Image.Format; import com.jme3.util.NativeObject; import java.util.ArrayList; /** * <p> * <code>FrameBuffer</code>s are rendering surfaces allowing * off-screen rendering and render-to-texture functionality. * Instead of the scene rendering to the screen, it is rendered into the * FrameBuffer, the result can be either a texture or a buffer. * <p> * A <code>FrameBuffer</code> supports two methods of rendering, * using a {@link Texture} or using a buffer. * When using a texture, the result of the rendering will be rendered * onto the texture, after which the texture can be placed on an object * and rendered as if the texture was uploaded from disk. * When using a buffer, the result is rendered onto * a buffer located on the GPU, the data of this buffer is not accessible * to the user. buffers are useful if one * wishes to retrieve only the color content of the scene, but still desires * depth testing (which requires a depth buffer). * Buffers can be copied to other framebuffers * including the main screen, by using * {@link Renderer#copyFrameBuffer(com.jme3.texture.FrameBuffer, com.jme3.texture.FrameBuffer, boolean, boolean)}. * The content of a {@link RenderBuffer} can be retrieved by using * {@link Renderer#readFrameBuffer(com.jme3.texture.FrameBuffer, java.nio.ByteBuffer) }. * <p> * <code>FrameBuffer</code>s have several attachment points, there are * several <em>color</em> attachment points and a single <em>depth</em> * attachment point. * The color attachment points support image formats such as * {@link Format#RGBA8}, allowing rendering the color content of the scene. * The depth attachment point requires a depth image format. * * @see Renderer#setFrameBuffer(com.jme3.texture.FrameBuffer) * * @author Kirill Vainer */ public class FrameBuffer extends NativeObject { public static final int SLOT_UNDEF = -1; public static final int SLOT_DEPTH = -100; public static final int SLOT_DEPTH_STENCIL = -101; private int width = 0; private int height = 0; private int samples = 1; final private ArrayList<RenderBuffer> colorBufs = new ArrayList<>(); private RenderBuffer depthBuf = null; private int colorBufIndex = 0; private boolean srgb; private Boolean mipsGenerationHint = null; /** * <code>RenderBuffer</code> represents either a texture or a * buffer that will be rendered to. <code>RenderBuffer</code>s * are attached to an attachment slot on a <code>FrameBuffer</code>. */ public static class RenderBuffer { Texture tex; Image.Format format; int id = -1; int slot = SLOT_UNDEF; int face = -1; int layer = -1; int level = 0; public int getLevel() { return this.level; } /** * @return The image format of the render buffer. */ public Format getFormat() { return format; } /** * @return The texture to render to for this <code>RenderBuffer</code> * or null if content should be rendered into a buffer. */ public Texture getTexture() { return tex; } /** * Do not use. * @return the buffer's ID */ public int getId() { return id; } /** * Do not use. * * @param id the desired ID */ public void setId(int id) { this.id = id; } /** * Do not use. * * @return the slot code, such as SLOT_DEPTH_STENCIL */ public int getSlot() { return slot; } public int getFace() { return face; } public void resetObject() { id = -1; } public RenderBuffer createDestructableClone() { if (tex != null) { return null; } else { RenderBuffer destructClone = new RenderBuffer(); destructClone.id = id; return destructClone; } } @Override public String toString() { if (tex != null) { return "TextureTarget[format=" + format + "]"; } else { return "BufferTarget[format=" + format + "]"; } } public int getLayer() { return this.layer; } } public static class FrameBufferTextureTarget extends RenderBuffer { private FrameBufferTextureTarget(){} void setTexture(Texture tx){ this.tex=tx; this.format=tx.getImage().getFormat(); } void setFormat(Format f){ this.format=f; } public FrameBufferTextureTarget layer(int i){ this.layer=i; return this; } public FrameBufferTextureTarget level(int i){ this.level=i; return this; } public FrameBufferTextureTarget face(TextureCubeMap.Face f){ return face(f.ordinal()); } public FrameBufferTextureTarget face(int f){ this.face=f; return this; } } public static class FrameBufferBufferTarget extends RenderBuffer { private FrameBufferBufferTarget(){} void setFormat(Format f){ this.format=f; } } public static class FrameBufferTarget { private FrameBufferTarget(){} public static FrameBufferTextureTarget newTarget(Texture tx){ FrameBufferTextureTarget t=new FrameBufferTextureTarget(); t.setTexture(tx); return t; } public static FrameBufferBufferTarget newTarget(Format format){ FrameBufferBufferTarget t=new FrameBufferBufferTarget(); t.setFormat(format); return t; } /** * Creates a frame buffer texture and sets the face position by using the face parameter. It uses * {@link TextureCubeMap} ordinal number for the face position. * * @param tx texture to add to the frame buffer * @param face face to add to the color buffer to * @return FrameBufferTexture Target */ public static FrameBufferTextureTarget newTarget(Texture tx, TextureCubeMap.Face face) { FrameBufferTextureTarget t = new FrameBufferTextureTarget(); t.face = face.ordinal(); t.setTexture(tx); return t; } } /** * A private constructor to inhibit instantiation of this class. */ private FrameBuffer() { } public void addColorTarget(FrameBufferBufferTarget colorBuf){ colorBuf.slot=colorBufs.size(); colorBufs.add(colorBuf); } public void addColorTarget(FrameBufferTextureTarget colorBuf){ // checkSetTexture(colorBuf.getTexture(), false); // TODO: this won't work for levels. colorBuf.slot=colorBufs.size(); colorBufs.add(colorBuf); } /** * Adds a texture to one of the color Buffers Array. It uses {@link TextureCubeMap} ordinal number for the * position in the color buffer ArrayList. * * @param colorBuf texture to add to the color Buffer * @param face position to add to the color buffer */ public void addColorTarget(FrameBufferTextureTarget colorBuf, TextureCubeMap.Face face) { // checkSetTexture(colorBuf.getTexture(), false); // TODO: this won't work for levels. colorBuf.slot = colorBufs.size(); colorBuf.face = face.ordinal(); colorBufs.add(colorBuf); } public void setDepthTarget(FrameBufferBufferTarget depthBuf){ if (!depthBuf.getFormat().isDepthFormat()) throw new IllegalArgumentException("Depth buffer format must be depth."); this.depthBuf = depthBuf; this.depthBuf.slot = this.depthBuf.getFormat().isDepthStencilFormat() ? SLOT_DEPTH_STENCIL : SLOT_DEPTH; } public void setDepthTarget(FrameBufferTextureTarget depthBuf){ checkSetTexture(depthBuf.getTexture(), true); this.depthBuf = depthBuf; this.depthBuf.slot = depthBuf.getTexture().getImage().getFormat().isDepthStencilFormat() ? SLOT_DEPTH_STENCIL : SLOT_DEPTH; } public int getNumColorTargets(){ return colorBufs.size(); } public RenderBuffer getColorTarget(int index){ return colorBufs.get(index); } public RenderBuffer getColorTarget() { if (colorBufs.isEmpty()) return null; if (colorBufIndex<0 || colorBufIndex>=colorBufs.size()) { return colorBufs.get(0); } return colorBufs.get(colorBufIndex); } public RenderBuffer getDepthTarget() { return depthBuf; } /** * <p> * Creates a new FrameBuffer with the given width, height, and number * of samples. If any textures are attached to this FrameBuffer, then * they must have the same number of samples as given in this constructor. * <p> * Note that if the {@link Renderer} does not expose the * {@link Caps#NonPowerOfTwoTextures}, then an exception will be thrown * if the width and height arguments are not power of two. * * @param width The width to use * @param height The height to use * @param samples The number of samples to use for a multisampled * framebuffer, or 1 if the framebuffer should be single-sampled. * * @throws IllegalArgumentException If width or height are not positive. */ public FrameBuffer(int width, int height, int samples) { super(); if (width <= 0 || height <= 0) { throw new IllegalArgumentException("FrameBuffer must have valid size."); } this.width = width; this.height = height; this.samples = samples == 0 ? 1 : samples; } protected FrameBuffer(FrameBuffer src) { super(src.id); /* for (RenderBuffer renderBuf : src.colorBufs){ RenderBuffer clone = renderBuf.createDestructableClone(); if (clone != null) this.colorBufs.add(clone); } this.depthBuf = src.depthBuf.createDestructableClone(); */ } /** * Enables the use of a depth buffer for this <code>FrameBuffer</code>. * * @param format The format to use for the depth buffer. * @throws IllegalArgumentException If <code>format</code> is not a depth format. * @deprecated Use setDepthTarget */ @Deprecated public void setDepthBuffer(Image.Format format) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } if (!format.isDepthFormat()) { throw new IllegalArgumentException("Depth buffer format must be depth."); } depthBuf = new RenderBuffer(); depthBuf.slot = format.isDepthStencilFormat() ? SLOT_DEPTH_STENCIL : SLOT_DEPTH; depthBuf.format = format; } /** * Enables the use of a color buffer for this <code>FrameBuffer</code>. * * @param format The format to use for the color buffer. * @throws IllegalArgumentException If <code>format</code> is not a color format. * @deprecated Use addColorTarget */ @Deprecated public void setColorBuffer(Image.Format format) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } if (format.isDepthFormat()) { throw new IllegalArgumentException("Color buffer format must be color/luminance."); } RenderBuffer colorBuf = new RenderBuffer(); colorBuf.slot = 0; colorBuf.format = format; colorBufs.clear(); colorBufs.add(colorBuf); } private void checkSetTexture(Texture tex, boolean depth) { Image img = tex.getImage(); if (img == null) { throw new IllegalArgumentException("Texture not initialized with RTT."); } if (depth && !img.getFormat().isDepthFormat()) { throw new IllegalArgumentException("Texture image format must be depth."); } else if (!depth && img.getFormat().isDepthFormat()) { throw new IllegalArgumentException("Texture image format must be color/luminance."); } // check that resolution matches texture resolution if (width != img.getWidth() || height != img.getHeight()) { throw new IllegalArgumentException("Texture image resolution " + "must match FB resolution"); } if (samples != tex.getImage().getMultiSamples()) { throw new IllegalStateException("Texture samples must match framebuffer samples"); } } /** * If enabled, any shaders rendering into this <code>FrameBuffer</code> * will be able to write several results into the renderbuffers * by using the <code>gl_FragData</code> array. Every slot in that * array maps into a color buffer attached to this framebuffer. * * @param enabled True to enable MRT (multiple rendering targets). */ public void setMultiTarget(boolean enabled) { if (enabled) { colorBufIndex = -1; } else { colorBufIndex = 0; } } /** * @return True if MRT (multiple rendering targets) is enabled. * @see FrameBuffer#setMultiTarget(boolean) */ public boolean isMultiTarget() { return colorBufIndex == -1; } /** * If MRT is not enabled ({@link FrameBuffer#setMultiTarget(boolean) } is false) * then this specifies the color target to which the scene should be rendered. * <p> * By default the value is 0. * * @param index The color attachment index. * @throws IllegalArgumentException If index is negative or doesn't map * to any attachment on this framebuffer. */ public void setTargetIndex(int index) { if (index < 0 || index >= 16) { throw new IllegalArgumentException("Target index must be between 0 and 16"); } if (colorBufs.size() < index) { throw new IllegalArgumentException("The target at " + index + " is not set!"); } colorBufIndex = index; setUpdateNeeded(); } /** * @return The color target to which the scene should be rendered. * * @see FrameBuffer#setTargetIndex(int) */ public int getTargetIndex() { return colorBufIndex; } /** * Set the color texture to use for this framebuffer. * This automatically clears all existing textures added previously * with {@link FrameBuffer#addColorTexture } and adds this texture as the * only target. * * @param tex The color texture to set. * @deprecated Use addColorTarget */ @Deprecated public void setColorTexture(Texture2D tex) { clearColorTargets(); addColorTexture(tex); } /** * Set the color texture array to use for this framebuffer. * This automatically clears all existing textures added previously * with {@link FrameBuffer#addColorTexture } and adds this texture as the * only target. * * @param tex The color texture array to set. * @param layer (default=-1) * @deprecated Use addColorTarget */ @Deprecated public void setColorTexture(TextureArray tex, int layer) { clearColorTargets(); addColorTexture(tex, layer); } /** * Set the color texture to use for this framebuffer. * This automatically clears all existing textures added previously * with {@link FrameBuffer#addColorTexture } and adds this texture as the * only target. * * @param tex The cube-map texture to set. * @param face The face of the cube-map to render to. * @deprecated Use addColorTarget */ @Deprecated public void setColorTexture(TextureCubeMap tex, TextureCubeMap.Face face) { clearColorTargets(); addColorTexture(tex, face); } /** * Clears all color targets that were set or added previously. */ public void clearColorTargets() { colorBufs.clear(); } /** * Add a color buffer without a texture bound to it. * If MRT is enabled, then each subsequently added texture or buffer can be * rendered to through a shader that writes to the array <code>gl_FragData</code>. * If MRT is not enabled, then the index set with {@link FrameBuffer#setTargetIndex(int) } * is rendered to by the shader. * * @param format the format of the color buffer * @see #addColorTexture(com.jme3.texture.Texture2D) * @deprecated Use addColorTarget */ @Deprecated public void addColorBuffer(Image.Format format) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } if (format.isDepthFormat()) { throw new IllegalArgumentException("Color buffer format must be color/luminance."); } RenderBuffer colorBuf = new RenderBuffer(); colorBuf.slot = colorBufs.size(); colorBuf.format = format; colorBufs.add(colorBuf); } /** * Add a color texture to use for this framebuffer. * If MRT is enabled, then each subsequently added texture can be * rendered to through a shader that writes to the array <code>gl_FragData</code>. * If MRT is not enabled, then the index set with {@link FrameBuffer#setTargetIndex(int) } * is rendered to by the shader. * * @param tex The texture to add. * @see #addColorBuffer(com.jme3.texture.Image.Format) * @deprecated Use addColorTarget */ @Deprecated public void addColorTexture(Texture2D tex) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } Image img = tex.getImage(); checkSetTexture(tex, false); RenderBuffer colorBuf = new RenderBuffer(); colorBuf.slot = colorBufs.size(); colorBuf.tex = tex; colorBuf.format = img.getFormat(); colorBufs.add(colorBuf); } /** * Add a color texture array to use for this framebuffer. * If MRT is enabled, then each subsequently added texture can be * rendered to through a shader that writes to the array <code>gl_FragData</code>. * If MRT is not enabled, then the index set with {@link FrameBuffer#setTargetIndex(int) } * is rendered to by the shader. * * @param tex The texture array to add. * @param layer (default=-1) * @deprecated Use addColorTarget */ @Deprecated public void addColorTexture(TextureArray tex, int layer) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } Image img = tex.getImage(); checkSetTexture(tex, false); RenderBuffer colorBuf = new RenderBuffer(); colorBuf.slot = colorBufs.size(); colorBuf.tex = tex; colorBuf.format = img.getFormat(); colorBuf.layer = layer; colorBufs.add(colorBuf); } /** * Add a color texture to use for this framebuffer. * If MRT is enabled, then each subsequently added texture can be * rendered to through a shader that writes to the array <code>gl_FragData</code>. * If MRT is not enabled, then the index set with {@link FrameBuffer#setTargetIndex(int) } * is rendered to by the shader. * * @param tex The cube-map texture to add. * @param face The face of the cube-map to render to. * @deprecated Use addColorTarget */ @Deprecated public void addColorTexture(TextureCubeMap tex, TextureCubeMap.Face face) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } Image img = tex.getImage(); checkSetTexture(tex, false); RenderBuffer colorBuf = new RenderBuffer(); colorBuf.slot = colorBufs.size(); colorBuf.tex = tex; colorBuf.format = img.getFormat(); colorBuf.face = face.ordinal(); colorBufs.add(colorBuf); } /** * Set the depth texture to use for this framebuffer. * * @param tex The color texture to set. * @deprecated Use setDepthTarget */ @Deprecated public void setDepthTexture(Texture2D tex) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } Image img = tex.getImage(); checkSetTexture(tex, true); depthBuf = new RenderBuffer(); depthBuf.slot = img.getFormat().isDepthStencilFormat() ? SLOT_DEPTH_STENCIL : SLOT_DEPTH; depthBuf.tex = tex; depthBuf.format = img.getFormat(); } /** * * @param tex the TextureArray to apply * @param layer (default=-1) * @deprecated Use setDepthTarget */ @Deprecated public void setDepthTexture(TextureArray tex, int layer) { if (id != -1) { throw new UnsupportedOperationException("FrameBuffer already initialized."); } Image img = tex.getImage(); checkSetTexture(tex, true); depthBuf = new RenderBuffer(); depthBuf.slot = img.getFormat().isDepthStencilFormat() ? SLOT_DEPTH_STENCIL : SLOT_DEPTH; depthBuf.tex = tex; depthBuf.format = img.getFormat(); depthBuf.layer = layer; } /** * @return The number of color buffers attached to this texture. * @deprecated Use getNumColorTargets */ @Deprecated public int getNumColorBuffers() { return colorBufs.size(); } /** * @param index the zero-base index (&ge;0) * @return The color buffer at the given index. * @deprecated Use getColorTarget(int) */ @Deprecated public RenderBuffer getColorBuffer(int index) { return colorBufs.get(index); } /** * @return The color buffer with the index set by {@link #setTargetIndex(int)}, or null * if no color buffers are attached. * If MRT is disabled, the first color buffer is returned. * @deprecated Use getColorTarget() */ @Deprecated public RenderBuffer getColorBuffer() { if (colorBufs.isEmpty()) { return null; } if (colorBufIndex < 0 || colorBufIndex >= colorBufs.size()) { return colorBufs.get(0); } return colorBufs.get(colorBufIndex); } /** * @return The depth buffer attached to this FrameBuffer, or null * if no depth buffer is attached * @deprecated Use getDepthTarget() */ @Deprecated public RenderBuffer getDepthBuffer() { return depthBuf; } /** * @return The height in pixels of this framebuffer. */ public int getHeight() { return height; } /** * @return The width in pixels of this framebuffer. */ public int getWidth() { return width; } /** * @return The number of samples when using a multisample framebuffer, or * 1 if this is a single-sampled framebuffer. */ public int getSamples() { return samples; } @Override public String toString() { StringBuilder sb = new StringBuilder(); String mrtStr = colorBufIndex >= 0 ? "" + colorBufIndex : "mrt"; sb.append("FrameBuffer[format=").append(width).append("x").append(height) .append("x").append(samples).append(", drawBuf=").append(mrtStr).append("]\n"); if (depthBuf != null) { sb.append("Depth => ").append(depthBuf).append("\n"); } for (RenderBuffer colorBuf : colorBufs) { sb.append("Color(").append(colorBuf.slot) .append(") => ").append(colorBuf).append("\n"); } return sb.toString(); } @Override public void resetObject() { this.id = -1; for (int i = 0; i < colorBufs.size(); i++) { colorBufs.get(i).resetObject(); } if (depthBuf != null) { depthBuf.resetObject(); } setUpdateNeeded(); } @Override public void deleteObject(Object rendererObject) { ((Renderer) rendererObject).deleteFrameBuffer(this); } @Override public NativeObject createDestructableClone() { return new FrameBuffer(this); } @Override public long getUniqueId() { return ((long) OBJTYPE_FRAMEBUFFER << 32) | ((long) id); } /** * Specifies that the color values stored in this framebuffer are in SRGB * format. * * The FrameBuffer must have an SRGB texture attached. * * The Renderer must expose the {@link Caps#Srgb sRGB pipeline} capability * for this option to take any effect. * * Rendering operations performed on this framebuffer shall undergo a linear * -&gt; sRGB color space conversion when this flag is enabled. If * {@link com.jme3.material.RenderState#getBlendMode() blending} is enabled, it will be * performed in linear space by first decoding the stored sRGB pixel values * into linear, combining with the shader result, and then converted back to * sRGB upon being written into the framebuffer. * * @param srgb If the framebuffer color values should be stored in sRGB * color space. * * @throws IllegalStateException If the texture attached to this framebuffer * is not sRGB. */ public void setSrgb(boolean srgb) { this.srgb = srgb; } /** * Determines if this framebuffer contains SRGB data. * * @return True if the framebuffer color values are in SRGB space, false if * in linear space. */ public boolean isSrgb() { return srgb; } /** * Hints the renderer to generate mipmaps for this framebuffer if necessary * @param v true to enable, null to use the default value for the renderer (default to null) */ public void setMipMapsGenerationHint(Boolean v) { mipsGenerationHint = v; } public Boolean getMipMapsGenerationHint() { return mipsGenerationHint; } }
FrameBuffer: rename a private field for clarity
jme3-core/src/main/java/com/jme3/texture/FrameBuffer.java
FrameBuffer: rename a private field for clarity
Java
mit
52cfa5578376779ec5395aee553206d45a6b5c87
0
cloudaddy/cloudaddys-project,cloudaddy/cloudaddys-project
package edu.neu.cloudaddy.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.thymeleaf.TemplateEngine; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; import org.thymeleaf.templateresolver.TemplateResolver; @EnableWebMvc @Configuration @ComponentScan(basePackages = "edu.neu.cloudaddy") @PropertySource("classpath:application.properties") @Import({ WebSecurityConfig.class }) public class AppConfig extends WebMvcConfigurerAdapter{ private static final String TEMPLATE_RESOLVER_PREFIX = "/resource/templates/"; private static final String TEMPLATE_RESOLVER_SUFFIX = ".html"; private static final String TEMPLATE_RESOLVER_TEMPLATE_MODE = "HTML5"; @Value("${mySql.url}") private String mysqlUrl; @Value("${mySql.username}") private String mysqlUsername; @Value("${mySql.password}") private String password; @Bean(name = "dataSource") public DriverManagerDataSource dataSource() { DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver"); driverManagerDataSource.setUrl(mysqlUrl); driverManagerDataSource.setUsername(mysqlUsername); driverManagerDataSource.setPassword(password); return driverManagerDataSource; } @Bean public ViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine((SpringTemplateEngine) templateEngine()); return viewResolver; } @Bean public TemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } @Bean public TemplateResolver templateResolver() { TemplateResolver templateResolver = new ServletContextTemplateResolver(); templateResolver.setPrefix(TEMPLATE_RESOLVER_PREFIX); templateResolver.setSuffix(TEMPLATE_RESOLVER_SUFFIX); templateResolver.setTemplateMode(TEMPLATE_RESOLVER_TEMPLATE_MODE); return templateResolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/") .setCachePeriod(31556926); registry.addResourceHandler("/assets/**").addResourceLocations("/assets/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/img/**").addResourceLocations("/img/"); } }
src/main/java/edu/neu/cloudaddy/config/AppConfig.java
package edu.neu.cloudaddy.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.thymeleaf.TemplateEngine; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; import org.thymeleaf.templateresolver.TemplateResolver; @EnableWebMvc @Configuration @ComponentScan(basePackages = "edu.neu.cloudaddy") @Import({ WebSecurityConfig.class }) public class AppConfig extends WebMvcConfigurerAdapter{ private static final String TEMPLATE_RESOLVER_PREFIX = "/resource/templates/"; private static final String TEMPLATE_RESOLVER_SUFFIX = ".html"; private static final String TEMPLATE_RESOLVER_TEMPLATE_MODE = "HTML5"; @Bean(name = "dataSource") public DriverManagerDataSource dataSource() { DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver"); driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/clouddaddy"); driverManagerDataSource.setUsername("root"); driverManagerDataSource.setPassword("admin"); return driverManagerDataSource; } @Bean public ViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine((SpringTemplateEngine) templateEngine()); return viewResolver; } @Bean public TemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } @Bean public TemplateResolver templateResolver() { TemplateResolver templateResolver = new ServletContextTemplateResolver(); templateResolver.setPrefix(TEMPLATE_RESOLVER_PREFIX); templateResolver.setSuffix(TEMPLATE_RESOLVER_SUFFIX); templateResolver.setTemplateMode(TEMPLATE_RESOLVER_TEMPLATE_MODE); return templateResolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/") .setCachePeriod(31556926); registry.addResourceHandler("/assets/**").addResourceLocations("/assets/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/img/**").addResourceLocations("/img/"); } }
add appconfig
src/main/java/edu/neu/cloudaddy/config/AppConfig.java
add appconfig
Java
mit
5e53f5acd058a3783871823dbead8256a2877df9
0
awesome-raccoons/gqt
import javafx.scene.control.TextField; /** * Created by Johannes on 15.10.2015. */ public class NumberTextField extends TextField { public NumberTextField(final int defaultValue) { this.setText(Integer.toString(defaultValue)); } @Override public final void replaceText(final int start, final int end, final String text) { if (validate(text)) { super.replaceText(start, end, text); } } @Override public final void replaceSelection(final String text) { if (validate(text)) { super.replaceSelection(text); } } private boolean validate(final String text) { return "".equals(text) || text.matches("[0-9]"); } public final int getValue() { String val = this.getText(); try { return Integer.parseInt(val); } catch (NumberFormatException e) { return 0; } } }
src/main/java/NumberTextField.java
import javafx.scene.control.TextField; /** * Created by Johannes on 15.10.2015. */ public class NumberTextField extends TextField { public NumberTextField(final int defaultValue) { this.setText(Integer.toString(defaultValue)); } @Override public final void replaceText(final int start, final int end, final String text) { if (validate(text)) { super.replaceText(start, end, text); } } @Override public final void replaceSelection(final String text) { if (validate(text)) { super.replaceSelection(text); } } private boolean validate(final String text) { return ("".equals(text) || text.matches("[0-9]")); } public final int getValue() { String val = this.getText(); try { return Integer.parseInt(val); } catch (NumberFormatException e) { return 0; } } }
frigg2
src/main/java/NumberTextField.java
frigg2
Java
mit
35e0686301a1700a39f92d3f05de2c6fd09637a2
0
UCSD/now-mobile,UCSD/campus-mobile,UCSD/now-mobile,UCSD/campus-mobile,UCSD/now-mobile,UCSD/campus-mobile,UCSD/campus-mobile,UCSD/campus-mobile,UCSD/campus-mobile
package edu.ucsd; import android.app.Application; import android.util.Log; import com.facebook.react.ReactApplication; import com.learnium.RNDeviceInfo.RNDeviceInfo; import com.psykar.cookiemanager.CookieManagerPackage; import com.oblador.vectoricons.VectorIconsPackage; import com.joshblour.reactnativepermissions.ReactNativePermissionsPackage; import com.idehub.GoogleAnalyticsBridge.GoogleAnalyticsBridgePackage; import com.microsoft.codepush.react.CodePush; import com.ivanwu.googleapiavailabilitybridge.ReactNativeGooglePlayServicesPackage; import com.airbnb.android.react.maps.MapsPackage; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override protected String getJSBundleFile() { return CodePush.getJSBundleFile(); } @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new RNDeviceInfo(), new CookieManagerPackage(), new VectorIconsPackage(), new ReactNativePermissionsPackage(), new GoogleAnalyticsBridgePackage(), new CodePush(null, getApplicationContext(), BuildConfig.DEBUG), new ReactNativeGooglePlayServicesPackage(), new MapsPackage() ); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
android/app/src/main/java/edu/ucsd/MainApplication.java
package edu.ucsd; import android.app.Application; import android.util.Log; import com.facebook.react.ReactApplication; <<<<<<< HEAD import com.learnium.RNDeviceInfo.RNDeviceInfo; ======= import com.psykar.cookiemanager.CookieManagerPackage; >>>>>>> v5.1-hotfix import com.oblador.vectoricons.VectorIconsPackage; import com.joshblour.reactnativepermissions.ReactNativePermissionsPackage; import com.idehub.GoogleAnalyticsBridge.GoogleAnalyticsBridgePackage; import com.microsoft.codepush.react.CodePush; import com.ivanwu.googleapiavailabilitybridge.ReactNativeGooglePlayServicesPackage; import com.airbnb.android.react.maps.MapsPackage; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override protected String getJSBundleFile() { return CodePush.getJSBundleFile(); } @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), <<<<<<< HEAD new RNDeviceInfo(), ======= new CookieManagerPackage(), >>>>>>> v5.1-hotfix new VectorIconsPackage(), new ReactNativePermissionsPackage(), new GoogleAnalyticsBridgePackage(), new CodePush(null, getApplicationContext(), BuildConfig.DEBUG), new ReactNativeGooglePlayServicesPackage(), new MapsPackage() ); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
Resolve MainApplication.java
android/app/src/main/java/edu/ucsd/MainApplication.java
Resolve MainApplication.java
Java
mit
8553d9791075598b6bbc7a0b06226aebf35b5f89
0
BloomBooks/BloomReader,BloomBooks/BloomReader
package org.sil.bloom.reader; import android.app.Activity; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import java.io.File; import static org.sil.bloom.reader.IOUtilities.BLOOM_BUNDLE_FILE_EXTENSION; import static org.sil.bloom.reader.IOUtilities.BLOOMD_FILE_EXTENSION; public class BookFinderTask extends AsyncTask<Void, Void, Void> { private Activity activity; private BookSearchListener bookSearchListener; public BookFinderTask(Activity activity, BookSearchListener bookSearchListener) { this.activity = activity; this.bookSearchListener = bookSearchListener; } @Override public Void doInBackground(Void... v) { // Scan public on-device storage String externalStoragePath = Environment.getExternalStorageDirectory().getPath(); scan(new File(externalStoragePath)); // Hackishly find sdcard and scan that too File[] publicBloomReaderDirs = activity.getExternalFilesDirs(null); for (File dir : publicBloomReaderDirs) { // Google Play Console proves dir can be null somehow if (dir != null && dir.getPath().contains("Android")) { while (!dir.getName().equals("Android")) dir = dir.getParentFile(); dir = dir.getParentFile(); // The parent directory of Android/ if (!dir.getPath().equals(externalStoragePath)) { scan(dir); } } } return null; } @Override public void onPostExecute(Void v) { bookSearchListener.onSearchComplete(); } private void scan(File root) { if (root != null) { File[] list = root.listFiles(); if (list == null) return; for (File f : list) { // Log.d("BookSearch", f.getName() + " is dir: " // + Boolean.toString(f.isDirectory()) + " is file: " + Boolean.toString(f.isFile())); if (f.isFile()) { if (f.getName().endsWith(BLOOM_BUNDLE_FILE_EXTENSION)) foundNewBundle(f); else if (f.getName().endsWith(BLOOMD_FILE_EXTENSION)) foundNewBook(f); } else if (f.isDirectory()) { scan(f); } } } } private void foundNewBook(final File bloomd) { activity.runOnUiThread(new Runnable() { @Override public void run() { bookSearchListener.onNewBloomd(bloomd); } }); } private void foundNewBundle(final File bundle) { activity.runOnUiThread(new Runnable() { @Override public void run() { bookSearchListener.onNewBloomBundle(bundle); } }); } public interface BookSearchListener { void onNewBloomd(File bloomdFile); void onNewBloomBundle(File bundleFile); void onSearchComplete(); } }
app/src/main/java/org/sil/bloom/reader/BookFinderTask.java
package org.sil.bloom.reader; import android.app.Activity; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import java.io.File; import static org.sil.bloom.reader.IOUtilities.BLOOM_BUNDLE_FILE_EXTENSION; import static org.sil.bloom.reader.IOUtilities.BLOOMD_FILE_EXTENSION; public class BookFinderTask extends AsyncTask<Void, Void, Void> { private Activity activity; private BookSearchListener bookSearchListener; public BookFinderTask(Activity activity, BookSearchListener bookSearchListener) { this.activity = activity; this.bookSearchListener = bookSearchListener; } @Override public Void doInBackground(Void... v) { // Scan public on-device storage String externalStoragePath = Environment.getExternalStorageDirectory().getPath(); scan(new File(externalStoragePath)); // Hackishly find sdcard and scan that too File[] publicBloomReaderDirs = activity.getExternalFilesDirs(null); for (File dir : publicBloomReaderDirs) { if (dir.getPath().contains("Android")) { while (!dir.getName().equals("Android")) dir = dir.getParentFile(); dir = dir.getParentFile(); // The parent directory of Android/ if (!dir.getPath().equals(externalStoragePath)) { scan(dir); } } } return null; } @Override public void onPostExecute(Void v) { bookSearchListener.onSearchComplete(); } private void scan(File root) { if (root != null) { File[] list = root.listFiles(); if (list == null) return; for (File f : list) { // Log.d("BookSearch", f.getName() + " is dir: " // + Boolean.toString(f.isDirectory()) + " is file: " + Boolean.toString(f.isFile())); if (f.isFile()) { if (f.getName().endsWith(BLOOM_BUNDLE_FILE_EXTENSION)) foundNewBundle(f); else if (f.getName().endsWith(BLOOMD_FILE_EXTENSION)) foundNewBook(f); } else if (f.isDirectory()) { scan(f); } } } } private void foundNewBook(final File bloomd) { activity.runOnUiThread(new Runnable() { @Override public void run() { bookSearchListener.onNewBloomd(bloomd); } }); } private void foundNewBundle(final File bundle) { activity.runOnUiThread(new Runnable() { @Override public void run() { bookSearchListener.onNewBloomBundle(bundle); } }); } public interface BookSearchListener { void onNewBloomd(File bloomdFile); void onNewBloomBundle(File bundleFile); void onSearchComplete(); } }
Fix NullPointerException exposed in Play Console
app/src/main/java/org/sil/bloom/reader/BookFinderTask.java
Fix NullPointerException exposed in Play Console
Java
mit
4f0cd643307894825c2b48233d74903e5631160b
0
jbosboom/streamjit,jbosboom/streamjit
package edu.mit.streamjit.impl.compiler.types; import static com.google.common.base.Preconditions.*; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import edu.mit.streamjit.impl.compiler.Klass; import edu.mit.streamjit.impl.compiler.Module; import edu.mit.streamjit.util.ReflectionUtils; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; /** * A TypeFactory makes Types on behalf of a Module. * @author Jeffrey Bosboom <[email protected]> * @since 4/7/2013 */ public final class TypeFactory implements Iterable<Type> { static { //We depend on this because we use an IdentityHashMap. assert ReflectionUtils.usesObjectEquality(Klass.class); Class<?>[] TYPE_CLASSES = { WrapperType.class, ArrayType.class, ReferenceType.class, PrimitiveType.class, VoidType.class }; MethodHandles.Lookup lookup = MethodHandles.lookup(); ImmutableList.Builder<MethodHandle> builder = ImmutableList.builder(); for (Class<?> c : TYPE_CLASSES) { //Don't try to construct abstract classes. (Doing so results in an //InstantiationException from inside the MethodHandle machinery with //no message string, which is a bit confusing.) assert !java.lang.reflect.Modifier.isAbstract(c.getModifiers()) : c; try { builder.add(lookup.findConstructor(c, java.lang.invoke.MethodType.methodType(void.class, Klass.class))); } catch (NoSuchMethodException | IllegalAccessException ex) { throw new AssertionError(ex); } } typeCtors = builder.build(); } private static final ImmutableList<MethodHandle> typeCtors; private final Module parent; private final Map<Klass, ReturnType> typeMap = new IdentityHashMap<>(); private final Iterable<Type> iterable = Iterables.unmodifiableIterable(Iterables.<Type>concat(typeMap.values())); public TypeFactory(Module parent) { assert ReflectionUtils.calledDirectlyFrom(Module.class); this.parent = checkNotNull(parent); } public ReturnType getType(Klass klass) { ReturnType t = typeMap.get(klass); if (t == null) { t = makeType(klass); typeMap.put(klass, t); } return t; } public VoidType getVoidType() { return (VoidType)getType(parent.getKlass(void.class)); } public RegularType getRegularType(Klass klass) { return (RegularType)getType(klass); } public PrimitiveType getPrimitiveType(Klass klass) { return (PrimitiveType)getType(klass); } public ReferenceType getReferenceType(Klass klass) { return (ReferenceType)getType(klass); } public ArrayType getArrayType(Klass klass) { return (ArrayType)getType(klass); } public WrapperType getWrapperType(Klass klass) { return (WrapperType)getType(klass); } public <T extends ReturnType> T getType(Klass klass, Class<T> typeClass) { return typeClass.cast(getType(klass)); } /** * Returns all the types created by this TypeFactory. There are no * guarantees on iteration order. Calling methods on this TypeFactory while * the iteration is in progress may result in * ConcurrentModificationException. Types present during one iteration may * not be present during another, depending on this TypeFactory's caching * policy. * @return an iterator over Types created by this TypeFactory */ @Override public Iterator<Type> iterator() { return iterable.iterator(); } private ReturnType makeType(Klass klass) { //Rather than have logic select which type to use, we just try them in //inverse-topological order (most specific first). Pretty ugly. for (MethodHandle h : typeCtors) try { return (ReturnType)h.invoke(klass); } catch (IllegalArgumentException ex) { continue; } catch (Throwable t) { Thread.currentThread().stop(t); } throw new AssertionError("No type for "+klass); } }
src/edu/mit/streamjit/impl/compiler/types/TypeFactory.java
package edu.mit.streamjit.impl.compiler.types; import static com.google.common.base.Preconditions.*; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import edu.mit.streamjit.impl.compiler.Klass; import edu.mit.streamjit.impl.compiler.Module; import edu.mit.streamjit.util.ReflectionUtils; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; /** * A TypeFactory makes Types on behalf of a Module. * @author Jeffrey Bosboom <[email protected]> * @since 4/7/2013 */ public final class TypeFactory implements Iterable<Type> { static { //We depend on this because we use an IdentityHashMap. assert ReflectionUtils.usesObjectEquality(Klass.class); Class<?>[] TYPE_CLASSES = { WrapperType.class, ArrayType.class, ReferenceType.class, PrimitiveType.class, RegularType.class, VoidType.class, ReturnType.class }; MethodHandles.Lookup lookup = MethodHandles.lookup(); ImmutableList.Builder<MethodHandle> builder = ImmutableList.builder(); for (Class<?> c : TYPE_CLASSES) try { builder.add(lookup.findConstructor(c, java.lang.invoke.MethodType.methodType(void.class, Klass.class))); } catch (NoSuchMethodException | IllegalAccessException ex) { throw new AssertionError(ex); } typeCtors = builder.build(); } private static final ImmutableList<MethodHandle> typeCtors; private final Module parent; private final Map<Klass, ReturnType> typeMap = new IdentityHashMap<>(); private final Iterable<Type> iterable = Iterables.unmodifiableIterable(Iterables.<Type>concat(typeMap.values())); public TypeFactory(Module parent) { assert ReflectionUtils.calledDirectlyFrom(Module.class); this.parent = checkNotNull(parent); } public ReturnType getType(Klass klass) { ReturnType t = typeMap.get(klass); if (t == null) { t = makeType(klass); typeMap.put(klass, t); } return t; } public VoidType getVoidType() { return (VoidType)getType(parent.getKlass(void.class)); } public RegularType getRegularType(Klass klass) { return (RegularType)getType(klass); } public PrimitiveType getPrimitiveType(Klass klass) { return (PrimitiveType)getType(klass); } public ReferenceType getReferenceType(Klass klass) { return (ReferenceType)getType(klass); } public ArrayType getArrayType(Klass klass) { return (ArrayType)getType(klass); } public WrapperType getWrapperType(Klass klass) { return (WrapperType)getType(klass); } public <T extends ReturnType> T getType(Klass klass, Class<T> typeClass) { return typeClass.cast(getType(klass)); } /** * Returns all the types created by this TypeFactory. There are no * guarantees on iteration order. Calling methods on this TypeFactory while * the iteration is in progress may result in * ConcurrentModificationException. Types present during one iteration may * not be present during another, depending on this TypeFactory's caching * policy. * @return an iterator over Types created by this TypeFactory */ @Override public Iterator<Type> iterator() { return iterable.iterator(); } private ReturnType makeType(Klass klass) { //Rather than have logic select which type to use, we just try them in //inverse-topological order (most specific first). Pretty ugly. for (MethodHandle h : typeCtors) try { return (ReturnType)h.invoke(klass); } catch (IllegalArgumentException ex) { continue; } catch (Throwable t) { Thread.currentThread().stop(t); } throw new AssertionError("No type for "+klass); } }
TypeFactory: don't instantiate abstract classes
src/edu/mit/streamjit/impl/compiler/types/TypeFactory.java
TypeFactory: don't instantiate abstract classes
Java
mit
6a236142bff417168da870fd8622454ad52b88ca
0
AstromechZA/HoughCircleDetection
package org.uct.cs.hough; import org.uct.cs.hough.display.PopUp; import org.uct.cs.hough.processors.*; import org.uct.cs.hough.reader.ImageLoader; import org.uct.cs.hough.reader.ShortImageBuffer; import org.uct.cs.hough.util.Circle; import org.uct.cs.hough.util.CircleAdder; import org.uct.cs.hough.util.Constants; import org.uct.cs.hough.util.Timer; import org.uct.cs.hough.writer.ImageWriter; import java.io.IOException; import java.util.List; class CliDriver { private static final int MIN_RADIUS = 10; private static final int MAX_RADIUS = 100; private static final int CENTER_THRESHOLD = 240; private static final int EDGE_THRESHOLD = 220; public static void main(String[] args) { try { try(Timer ignored = new Timer("total")) { ShortImageBuffer original = ImageLoader.load("samples/testseq100007.gif"); ignored.print("read"); ShortImageBuffer edges = Thresholder.threshold( Normalizer.norm( SobelEdgeDetector.apply( Normalizer.norm(original) ) ), EDGE_THRESHOLD ); ignored.print("edge detector"); HoughFilter houghFilter = new HoughFilter(MIN_RADIUS, MAX_RADIUS, true); ShortImageBuffer houghed = houghFilter.run(edges); HoughFilter.HoughSpace space = houghFilter.getLastHoughSpace(); ignored.print("hough filter"); List<Circle> circles = BestPointFinder.find(houghed, space, CENTER_THRESHOLD, Constants.BYTE); ignored.print("circle collect"); PopUp.Show(CircleAdder.Draw(edges.toImage(), circles), "Detected Circles"); ignored.print("circle draw"); ImageWriter.Save(houghed.toImage(), "samples/out.png", ImageWriter.ImageFormat.PNG); ignored.print("save"); } } catch (IOException e) { e.printStackTrace(); } } }
src/org/uct/cs/hough/CliDriver.java
package org.uct.cs.hough; import org.uct.cs.hough.display.PopUp; import org.uct.cs.hough.processors.*; import org.uct.cs.hough.reader.ImageLoader; import org.uct.cs.hough.reader.ShortImageBuffer; import org.uct.cs.hough.util.Circle; import org.uct.cs.hough.util.CircleAdder; import org.uct.cs.hough.util.Constants; import org.uct.cs.hough.util.Timer; import org.uct.cs.hough.writer.ImageWriter; import java.io.IOException; import java.util.List; class CliDriver { private static final int MIN_RADIUS = 10; private static final int MAX_RADIUS = 100; private static final int CENTER_THRESHOLD = 240; private static final int EDGE_THRESHOLD = 220; public static void main(String[] args) { try { Timer ignored = new Timer("Circle Detector"); ShortImageBuffer original = ImageLoader.load("samples/testseq100007.gif"); ignored.print("read"); ShortImageBuffer edges = Thresholder.threshold( Normalizer.norm( SobelEdgeDetector.apply( Normalizer.norm(original) ) ), EDGE_THRESHOLD ); ignored.print("edge detector"); HoughFilter houghFilter = new HoughFilter(MIN_RADIUS, MAX_RADIUS, true); ShortImageBuffer houghed = houghFilter.run(edges); HoughFilter.HoughSpace space = houghFilter.getLastHoughSpace(); ignored.print("hough filter"); List<Circle> circles = BestPointFinder.find(houghed, space, CENTER_THRESHOLD, Constants.BYTE); ignored.print("circle collect"); PopUp.Show(CircleAdder.Draw(edges.toImage(), circles), "Detected Circles"); ignored.print("circle draw"); ImageWriter.Save(houghed.toImage(), "samples/out.png", ImageWriter.ImageFormat.PNG); ignored.print("save"); } catch (IOException e) { e.printStackTrace(); } } }
Moved to trywithresource
src/org/uct/cs/hough/CliDriver.java
Moved to trywithresource
Java
mit
f8936375547c79573786ca58c4022de10f3f811e
0
ohtuprojekti/OKKoPa,ohtuprojekti/OKKoPa
package fi.helsinki.cs.okkopa; import com.google.zxing.NotFoundException; import fi.helsinki.cs.okkopa.mail.read.EmailRead; import fi.helsinki.cs.okkopa.mail.read.MailRead; import fi.helsinki.cs.okkopa.mail.send.OKKoPaAuthenticatedMessage; import fi.helsinki.cs.okkopa.mail.send.OKKoPaMessage; import fi.helsinki.cs.okkopa.qr.DocumentException; import fi.helsinki.cs.okkopa.qr.ExamPaper; import fi.helsinki.cs.okkopa.qr.PDFProcessor; import fi.helsinki.cs.okkopa.qr.PDFProcessorImpl; import fi.helsinki.cs.okkopa.qr.PDFSplitter; import fi.helsinki.cs.okkopa.qr.QRCodeReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class OkkopaRunner implements Runnable { private PDFProcessor pDFProcessor; private EmailRead server; @Autowired public OkkopaRunner(EmailRead server) { this.server = server; pDFProcessor = new PDFProcessorImpl(new PDFSplitter(), new QRCodeReader()); } @Override public void run() { try { // TEST System.out.println("1. merkki"); server.connect(); System.out.println("2. merkki"); while (true) { ArrayList<InputStream> attachments = server.getNextAttachment(); if (attachments == null) { System.out.println("Ei lisää viestejä."); break; } for (InputStream inputStream : attachments) { // PDF to exam papers List<ExamPaper> processPDF = processPdf(inputStream); for (ExamPaper examPaper : processPDF) { sendEmail(examPaper); } IOUtils.closeQuietly(inputStream); } } } catch (NoSuchProviderException ex) { // TODO System.out.println("ei provideria"); } catch (MessagingException ex) { // TODO System.out.println("messaging ex " + ex); } catch (IOException ex) { // TODO System.out.println("io ex"); } finally { server.close(); } } private void sendEmail(ExamPaper examPaper) { try { Properties props = Settings.SMTPPROPS; Properties salasanat = Settings.PWDPROPS; OKKoPaMessage msg = new OKKoPaAuthenticatedMessage("[email protected]", "[email protected]", props, "okkopa2.2013", salasanat.getProperty("smtpPassword")); msg.addPDFAttachment(examPaper.getPdfStream(), "liite.pdf"); msg.setSubject("testipdf"); msg.setText("katso liite " + examPaper.getQRCodeString()); msg.send(); System.out.println("lähetetty"); } catch (MessagingException ex) { System.out.println(ex); } catch (IOException ex) { System.out.println(ex); } } private List<ExamPaper> processPdf(InputStream inputStream) { List<ExamPaper> okPapers = new ArrayList<>(); List<ExamPaper> processPDF = new ArrayList<>(); try { processPDF = pDFProcessor.splitPDF(inputStream); } catch (IOException ex) { // Not pdf-format System.out.println("Not pdf-format"); } catch (DocumentException ex) { // Odd number of pages System.out.println("Odd number of pages"); } catch (COSVisitorException ex) { Logger.getLogger(OkkopaRunner.class.getName()).log(Level.SEVERE, null, ex); } for (ExamPaper examPaper : processPDF) { try { examPaper.setQRCodeString(pDFProcessor.readQRCode(examPaper)); okPapers.add(examPaper); } catch (Exception ex) { // QR code not found System.out.println("QR code not found"); } } return okPapers; } }
src/main/java/fi/helsinki/cs/okkopa/OkkopaRunner.java
package fi.helsinki.cs.okkopa; import com.google.zxing.NotFoundException; import fi.helsinki.cs.okkopa.mail.read.EmailRead; import fi.helsinki.cs.okkopa.mail.read.MailRead; import fi.helsinki.cs.okkopa.mail.send.OKKoPaAuthenticatedMessage; import fi.helsinki.cs.okkopa.mail.send.OKKoPaMessage; import fi.helsinki.cs.okkopa.qr.DocumentException; import fi.helsinki.cs.okkopa.qr.ExamPaper; import fi.helsinki.cs.okkopa.qr.PDFProcessor; import fi.helsinki.cs.okkopa.qr.PDFProcessorImpl; import fi.helsinki.cs.okkopa.qr.PDFSplitter; import fi.helsinki.cs.okkopa.qr.QRCodeReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class OkkopaRunner implements Runnable { private PDFProcessor pDFProcessor; @Autowired private EmailRead server; public OkkopaRunner() { pDFProcessor = new PDFProcessorImpl(new PDFSplitter(), new QRCodeReader()); } @Override public void run() { try { // TEST System.out.println("1. merkki"); server.connect(); System.out.println("2. merkki"); while (true) { ArrayList<InputStream> attachments = server.getNextAttachment(); if (attachments == null) { System.out.println("Ei lisää viestejä."); break; } for (InputStream inputStream : attachments) { // PDF to exam papers List<ExamPaper> processPDF = processPdf(inputStream); for (ExamPaper examPaper : processPDF) { sendEmail(examPaper); } IOUtils.closeQuietly(inputStream); } } } catch (NoSuchProviderException ex) { // TODO System.out.println("ei provideria"); } catch (MessagingException ex) { // TODO System.out.println("messaging ex " + ex); } catch (IOException ex) { // TODO System.out.println("io ex"); } finally { server.close(); } } private void sendEmail(ExamPaper examPaper) { try { Properties props = Settings.SMTPPROPS; Properties salasanat = Settings.PWDPROPS; OKKoPaMessage msg = new OKKoPaAuthenticatedMessage("[email protected]", "[email protected]", props, "okkopa2.2013", salasanat.getProperty("smtpPassword")); msg.addPDFAttachment(examPaper.getPdfStream(), "liite.pdf"); msg.setSubject("testipdf"); msg.setText("katso liite " + examPaper.getQRCodeString()); msg.send(); System.out.println("lähetetty"); } catch (MessagingException ex) { System.out.println(ex); } catch (IOException ex) { System.out.println(ex); } } private List<ExamPaper> processPdf(InputStream inputStream) { List<ExamPaper> okPapers = new ArrayList<>(); List<ExamPaper> processPDF = new ArrayList<>(); try { processPDF = pDFProcessor.splitPDF(inputStream); } catch (IOException ex) { // Not pdf-format System.out.println("Not pdf-format"); } catch (DocumentException ex) { // Odd number of pages System.out.println("Odd number of pages"); } catch (COSVisitorException ex) { Logger.getLogger(OkkopaRunner.class.getName()).log(Level.SEVERE, null, ex); } for (ExamPaper examPaper : processPDF) { try { examPaper.setQRCodeString(pDFProcessor.readQRCode(examPaper)); okPapers.add(examPaper); } catch (Exception ex) { // QR code not found System.out.println("QR code not found"); } } return okPapers; } }
Nothing big.
src/main/java/fi/helsinki/cs/okkopa/OkkopaRunner.java
Nothing big.
Java
mit
519d957d6b87ca158a933e5a5c1b238d491b56b0
0
hsbp/burnstation3
package org.hsbp.burnstation3; import android.app.Activity; import android.os.Bundle; import android.os.AsyncTask; import android.widget.*; import java.util.*; import java.net.*; import java.io.*; import org.apache.commons.io.IOUtils; import org.json.*; public class Main extends Activity { public final static String ID = "id"; public static final String UTF_8 = "UTF-8"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String[] test = {"foo", "bar", "baz"}; int[] widgets = {R.id.tracks, R.id.playlist}; for (int widget : widgets) { ListView lv = (ListView)findViewById(widget); lv.setAdapter(new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, test)); } new AlbumListFillTask().execute(); } private class AlbumListFillTask extends AsyncTask<Void, Void, List<? extends Map<String, ?>>> { public final static String NAME = "name"; public final static String ARTIST_NAME = "artist_name"; @Override protected List<? extends Map<String, ?>> doInBackground(Void... ignored) { List<Map<String, String>> albums = new ArrayList<Map<String, String>>(); try { JSONArray api_result = getArrayFromApi("albums", "&order=popularity_week"); for (int i = 0; i < api_result.length(); i++) { try { Map<String, String> album = new HashMap<String, String>(); JSONObject item = api_result.getJSONObject(i); album.put(ARTIST_NAME, item.getString(ARTIST_NAME)); album.put(NAME, item.getString(NAME)); album.put(ID, item.getString(ID)); albums.add(album); } catch (JSONException je) { je.printStackTrace(); // TODO report API error } } } catch (JSONException je) { je.printStackTrace(); // TODO report API error } catch (IOException ioe) { ioe.printStackTrace(); // TODO report API error } return albums; } @Override protected void onPostExecute(List<? extends Map<String, ?>> result) { ListView lv = (ListView)findViewById(R.id.albums); final String[] map_from = {NAME, ARTIST_NAME}; final int[] map_to = {R.id.album_name, R.id.album_artist}; lv.setAdapter(new SimpleAdapter(Main.this, result, R.layout.albums_item, map_from, map_to)); } } private static JSONArray getArrayFromApi(String resource, String parameters) throws IOException, JSONException { URL api = new URL("http://10.0.2.2:5000/albums.json"); // TODO use real API HttpURLConnection urlConnection = (HttpURLConnection) api.openConnection(); try { String response = IOUtils.toString(urlConnection.getInputStream(), UTF_8); JSONObject object = (JSONObject) new JSONTokener(response).nextValue(); return object.getJSONArray("results"); } finally { urlConnection.disconnect(); } } }
src/org/hsbp/burnstation3/Main.java
package org.hsbp.burnstation3; import android.app.Activity; import android.os.Bundle; import android.os.AsyncTask; import android.widget.*; import java.util.*; import java.net.*; import java.io.*; import org.apache.commons.io.IOUtils; import org.json.*; public class Main extends Activity { public static final String UTF_8 = "UTF-8"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String[] test = {"foo", "bar", "baz"}; int[] widgets = {R.id.tracks, R.id.playlist}; for (int widget : widgets) { ListView lv = (ListView)findViewById(widget); lv.setAdapter(new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, test)); } new AlbumListFillTask().execute(); } private class AlbumListFillTask extends AsyncTask<Void, Void, List<? extends Map<String, ?>>> { public final static String NAME = "name"; public final static String ARTIST_NAME = "artist_name"; @Override protected List<? extends Map<String, ?>> doInBackground(Void... ignored) { List<Map<String, String>> albums = new ArrayList<Map<String, String>>(); try { JSONArray api_result = getArrayFromApi("albums", "&order=popularity_week"); for (int i = 0; i < api_result.length(); i++) { try { Map<String, String> album = new HashMap<String, String>(); JSONObject item = api_result.getJSONObject(i); album.put(ARTIST_NAME, item.getString(ARTIST_NAME)); album.put(NAME, item.getString(NAME)); albums.add(album); } catch (JSONException je) { je.printStackTrace(); // TODO report API error } } } catch (JSONException je) { je.printStackTrace(); // TODO report API error } catch (IOException ioe) { ioe.printStackTrace(); // TODO report API error } return albums; } @Override protected void onPostExecute(List<? extends Map<String, ?>> result) { ListView lv = (ListView)findViewById(R.id.albums); final String[] map_from = {NAME, ARTIST_NAME}; final int[] map_to = {R.id.album_name, R.id.album_artist}; lv.setAdapter(new SimpleAdapter(Main.this, result, R.layout.albums_item, map_from, map_to)); } } private static JSONArray getArrayFromApi(String resource, String parameters) throws IOException, JSONException { URL api = new URL("http://10.0.2.2:5000/albums.json"); // TODO use real API HttpURLConnection urlConnection = (HttpURLConnection) api.openConnection(); try { String response = IOUtils.toString(urlConnection.getInputStream(), UTF_8); JSONObject object = (JSONObject) new JSONTokener(response).nextValue(); return object.getJSONArray("results"); } finally { urlConnection.disconnect(); } } }
Main: store ID in album map
src/org/hsbp/burnstation3/Main.java
Main: store ID in album map
Java
mit
1f1fdc53da89f787a3d4008e5cb37ea784503f85
0
mercadopago/px-android,mercadopago/px-android,mercadopago/px-android
package com.mercadopago; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.support.v4.view.MotionEventCompat; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import com.google.gson.reflect.TypeToken; import com.mercadopago.adapters.IdentificationTypesAdapter; import com.mercadopago.callbacks.Callback; import com.mercadopago.callbacks.FailureRecovery; import com.mercadopago.callbacks.PaymentMethodSelectionCallback; import com.mercadopago.controllers.PaymentMethodGuessingController; import com.mercadopago.core.MercadoPago; import com.mercadopago.fragments.CardBackFragment; import com.mercadopago.fragments.CardFrontFragment; import com.mercadopago.fragments.CardIdentificationFragment; import com.mercadopago.model.ApiException; import com.mercadopago.model.BankDeal; import com.mercadopago.model.CardNumber; import com.mercadopago.model.CardToken; import com.mercadopago.model.Cardholder; import com.mercadopago.model.Identification; import com.mercadopago.model.IdentificationType; import com.mercadopago.model.Issuer; import com.mercadopago.model.PaymentMethod; import com.mercadopago.model.PaymentPreference; import com.mercadopago.model.SecurityCode; import com.mercadopago.model.Setting; import com.mercadopago.model.Token; import com.mercadopago.mptracker.MPTracker; import com.mercadopago.util.ApiUtil; import com.mercadopago.util.ErrorUtil; import com.mercadopago.util.JsonUtil; import com.mercadopago.util.LayoutUtil; import com.mercadopago.util.MPAnimationUtils; import com.mercadopago.views.MPEditText; import com.mercadopago.views.MPTextView; import java.lang.reflect.Type; import java.util.List; public class GuessingCardActivity extends FrontCardActivity { // Activity parameters protected String mPublicKey; protected List<PaymentMethod> mPaymentMethodList; // Input controls private MPTextView mToolbarButton; private MPEditText mCardHolderNameEditText; private MPEditText mCardNumberEditText; private MPEditText mCardExpiryDateEditText; private MPEditText mCardSecurityCodeEditText; private MPEditText mCardIdentificationNumberEditText; private MPTextView mErrorTextView; private LinearLayout mSecurityCodeEditView; private LinearLayout mInputContainer; private Spinner mIdentificationTypeSpinner; private LinearLayout mIdentificationTypeContainer; private LinearLayout mIdentificationNumberContainer; private ScrollView mScrollView; private ProgressBar mProgressBar; private FrameLayout mBackButton; private FrameLayout mNextButton; private FrameLayout mBackInactiveButton; private FrameLayout mErrorContainer; private LinearLayout mButtonContainer; private View mCardBackground; private LinearLayout mCardNumberInput; private LinearLayout mCardholderNameInput; private LinearLayout mCardExpiryDateInput; private LinearLayout mCardIdNumberInput; private View mFrontView; private View mBackView; //Card container private CardFrontFragment mFrontFragment; private CardBackFragment mBackFragment; private CardIdentificationFragment mCardIdentificationFragment; // Local vars private MercadoPago mMercadoPago; private PaymentPreference mPaymentPreference; private CardToken mCardToken; private Token mToken; private Identification mIdentification; private Issuer mSelectedIssuer; private IdentificationType mSelectedIdentificationType; private boolean mIdentificationNumberRequired; private String mCardSideState; private String mCurrentEditingEditText; protected PaymentMethodGuessingController mPaymentMethodGuessingController; private boolean mIsSecurityCodeRequired; private int mCardSecurityCodeLength; private int mCardNumberLength; private String mSecurityCodeLocation; private boolean mIssuerFound; @Override protected void onResume() { super.onResume(); if (mCardSideState == null) { mCardSideState = CARD_SIDE_FRONT; } openKeyboard(); } @Override protected void onDestroy() { if (showingFront() && mFrontFragment != null) { mFrontFragment.setCardColor(CardInterface.NEUTRAL_CARD_COLOR); } super.onDestroy(); } @Override public void onBackPressed() { checkFlipCardToFront(true); MPTracker.getInstance().trackEvent("GUESSING_CARD", "BACK_PRESSED", 2, mPublicKey, BuildConfig.VERSION_NAME, this); Intent returnIntent = new Intent(); returnIntent.putExtra("backButtonPressed", true); setResult(RESULT_CANCELED, returnIntent); finish(); } private void initializeToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.mpsdkToolbar); mToolbarButton = (MPTextView) findViewById(R.id.mpsdkButtonText); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } if (toolbar != null) { toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } if (mDecorationPreference != null) { if (mDecorationPreference.hasColors()) { if (toolbar != null) { decorateToolbar(toolbar); } } } LayoutUtil.showProgressLayout(this); } private void decorateToolbar(Toolbar toolbar) { if (mDecorationPreference.isDarkFontEnabled()) { mToolbarButton.setTextColor(mDecorationPreference.getDarkFontColor(this)); Drawable upArrow = toolbar.getNavigationIcon(); if (upArrow != null) { upArrow.setColorFilter(mDecorationPreference.getDarkFontColor(this), PorterDuff.Mode.SRC_ATOP); } getSupportActionBar().setHomeAsUpIndicator(upArrow); } toolbar.setBackgroundColor(mDecorationPreference.getLighterColor()); } @Override protected void setContentView() { setContentView(R.layout.mpsdk_activity_new_card_form); } @Override protected void validateActivityParameters() throws IllegalStateException { if (mPublicKey == null) { throw new IllegalStateException(); } } @Override protected void onBeforeCreation() { if (onlyPortrait()) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } @Override protected void onValidStart() { if (!onlyPortrait()) { setLandscapeModeInitialLayout(); } initializeToolbar(); setListeners(); openKeyboard(mCardNumberEditText); mCurrentEditingEditText = CardInterface.CARD_NUMBER_INPUT; mMercadoPago = new MercadoPago.Builder() .setContext(getActivity()) .setPublicKey(mPublicKey) .build(); getBankDealsAsync(); if (mPaymentMethodList == null) { getPaymentMethodsAsync(); } else { startGuessingForm(); } } private boolean onlyPortrait() { return getResources().getBoolean(R.bool.only_portrait); } private void setLandscapeModeInitialLayout() { mCardExpiryDateInput.setVisibility(View.VISIBLE); mSecurityCodeEditView.setVisibility(View.VISIBLE); } @Override protected void onInvalidStart(String message) { Intent returnIntent = new Intent(); setResult(RESULT_CANCELED, returnIntent); finish(); } @Override protected void initializeFragments(Bundle savedInstanceState) { mIssuerFound = true; mErrorState = CardInterface.NORMAL_STATE; mCardToken = new CardToken("", null, null, "", "", "", ""); mIsSecurityCodeRequired = true; mCardSecurityCodeLength = CARD_DEFAULT_SECURITY_CODE_LENGTH; mCardNumberLength = CARD_NUMBER_MAX_LENGTH; mSecurityCodeLocation = null; if (mFrontFragment == null) { mFrontFragment = new CardFrontFragment(); mFrontFragment.setDecorationPreference(mDecorationPreference); } if (mBackFragment == null) { mBackFragment = new CardBackFragment(); mBackFragment.setDecorationPreference(mDecorationPreference); } if (mCardIdentificationFragment == null) { mCardIdentificationFragment = new CardIdentificationFragment(); } if (savedInstanceState == null) { initializeFrontFragment(); initializeBackFragment(); } } private void initializeFrontFragment() { mFrontView = findViewById(R.id.mpsdkActivityNewCardContainerFront); mCardSideState = CARD_SIDE_FRONT; getSupportFragmentManager() .beginTransaction() .add(R.id.mpsdkActivityNewCardContainerFront, mFrontFragment) .commit(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { mFrontView.setAlpha(1.0f); } } private void initializeBackFragment() { mBackView = findViewById(R.id.mpsdkActivityNewCardContainerBack); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { getSupportFragmentManager() .beginTransaction() .add(R.id.mpsdkActivityNewCardContainerBack, mBackFragment) .commit(); mBackView.setAlpha(0); } } @Override protected void initializeControls() { mCardNumberEditText = (MPEditText) findViewById(R.id.mpsdkCardNumber); mCardHolderNameEditText = (MPEditText) findViewById(R.id.mpsdkCardholderName); mCardExpiryDateEditText = (MPEditText) findViewById(R.id.mpsdkCardExpiryDate); mCardSecurityCodeEditText = (MPEditText) findViewById(R.id.mpsdkCardSecurityCode); mCardIdentificationNumberEditText = (MPEditText) findViewById(R.id.mpsdkCardIdentificationNumber); mSecurityCodeEditView = (LinearLayout) findViewById(R.id.mpsdkCardSecurityCodeContainer); mInputContainer = (LinearLayout) findViewById(R.id.mpsdkNewCardInputContainer); mIdentificationTypeSpinner = (Spinner) findViewById(R.id.mpsdkCardIdentificationType); mIdentificationTypeContainer = (LinearLayout) findViewById(R.id.mpsdkCardIdentificationTypeContainer); mIdentificationNumberContainer = (LinearLayout) findViewById(R.id.mpsdkCardIdentificationNumberContainer); mProgressBar = (ProgressBar) findViewById(R.id.mpsdkProgressBar); mBackButton = (FrameLayout) findViewById(R.id.mpsdkBackButton); mNextButton = (FrameLayout) findViewById(R.id.mpsdkNextButton); mBackInactiveButton = (FrameLayout) findViewById(R.id.mpsdkBackInactiveButton); mButtonContainer = (LinearLayout) findViewById(R.id.mpsdkButtonContainer); mErrorContainer = (FrameLayout) findViewById(R.id.mpsdkErrorContainer); mErrorTextView = (MPTextView) findViewById(R.id.mpsdkErrorTextView); mScrollView = (ScrollView) findViewById(R.id.mpsdkScrollViewContainer); mCardNumberInput = (LinearLayout) findViewById(R.id.mpsdkCardNumberInput); mCardholderNameInput = (LinearLayout) findViewById(R.id.mpsdkCardholderNameInput); mCardExpiryDateInput = (LinearLayout) findViewById(R.id.mpsdkExpiryDateInput); mCardIdNumberInput = (LinearLayout) findViewById(R.id.mpsdkCardIdentificationInput); mProgressBar.setVisibility(View.GONE); mIdentificationTypeContainer.setVisibility(View.GONE); mIdentificationNumberContainer.setVisibility(View.GONE); mButtonContainer.setVisibility(View.VISIBLE); mCardBackground = findViewById(R.id.mpsdkCardBackground); if (mDecorationPreference != null && mDecorationPreference.hasColors()) { mCardBackground.setBackgroundColor(mDecorationPreference.getLighterColor()); } fullScrollDown(); } private void fullScrollDown() { Runnable r = new Runnable() { public void run() { mScrollView.fullScroll(View.FOCUS_DOWN); } }; mScrollView.post(r); r.run(); } @Override protected void getActivityParameters() { mPublicKey = this.getIntent().getStringExtra("publicKey"); mPaymentPreference = JsonUtil.getInstance().fromJson(this.getIntent().getStringExtra("paymentPreference"), PaymentPreference.class); mToken = JsonUtil.getInstance().fromJson(this.getIntent().getStringExtra("token"), Token.class); try { Type listType = new TypeToken<List<PaymentMethod>>() { }.getType(); mPaymentMethodList = JsonUtil.getInstance().getGson().fromJson(this.getIntent().getStringExtra("paymentMethodList"), listType); } catch (Exception ex) { mPaymentMethodList = null; } mIdentification = new Identification(); mIdentificationNumberRequired = false; if (mPaymentPreference == null) { mPaymentPreference = new PaymentPreference(); } } protected void setListeners() { setCardNumberFocusListener(); setCardNameFocusListener(); setCardExpiryDateFocusListener(); setCardSecurityCodeFocusListener(); setCardIdentificationFocusListener(); setNavigationButtonsListeners(); setSecurityCodeTextWatcher(); setIdentificationNumberTextWatcher(); setCardholderNameTextWatcher(); setExpiryDateTextWatcher(); } public void openKeyboard(MPEditText ediText) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(ediText, InputMethodManager.SHOW_IMPLICIT); fullScrollDown(); } private void setNavigationButtonsListeners() { mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { validateCurrentEditText(); } }); mBackButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mCurrentEditingEditText.equals(CARD_NUMBER_INPUT)) { checkIsEmptyOrValid(); } } }); } private void openKeyboard() { if (mCurrentEditingEditText == null) { mCurrentEditingEditText = CARD_NUMBER_INPUT; } switch (mCurrentEditingEditText) { case CARD_NUMBER_INPUT: openKeyboard(mCardNumberEditText); break; case CARDHOLDER_NAME_INPUT: openKeyboard(mCardHolderNameEditText); break; case CARD_EXPIRYDATE_INPUT: openKeyboard(mCardExpiryDateEditText); break; case CARD_SECURITYCODE_INPUT: openKeyboard(mCardSecurityCodeEditText); break; case CARD_IDENTIFICATION_INPUT: openKeyboard(mCardIdentificationNumberEditText); break; } } private boolean validateCurrentEditText() { switch (mCurrentEditingEditText) { case CARD_NUMBER_INPUT: if (validateCardNumber(true)) { mCardNumberInput.setVisibility(View.GONE); mCardExpiryDateInput.setVisibility(View.VISIBLE); mCardHolderNameEditText.requestFocus(); return true; } return false; case CARDHOLDER_NAME_INPUT: if (validateCardName(true)) { mCardholderNameInput.setVisibility(View.GONE); if (isSecurityCodeRequired()) { mSecurityCodeEditView.setVisibility(View.VISIBLE); } else if (mIdentificationNumberRequired) { mIdentificationTypeContainer.setVisibility(View.VISIBLE); } mCardExpiryDateEditText.requestFocus(); return true; } return false; case CARD_EXPIRYDATE_INPUT: if (validateExpiryDate(true)) { mCardExpiryDateInput.setVisibility(View.GONE); if (isSecurityCodeRequired()) { mCardSecurityCodeEditText.requestFocus(); if (mIdentificationNumberRequired) { mIdentificationTypeContainer.setVisibility(View.VISIBLE); } } else if (mIdentificationNumberRequired) { mCardIdentificationNumberEditText.requestFocus(); mCardIdNumberInput.setVisibility(View.VISIBLE); } else { createToken(); } return true; } return false; case CARD_SECURITYCODE_INPUT: if (validateSecurityCode(true)) { mSecurityCodeEditView.setVisibility(View.GONE); if (mIdentificationNumberRequired) { mCardIdentificationNumberEditText.requestFocus(); mCardIdNumberInput.setVisibility(View.VISIBLE); } else { createToken(); } return true; } return false; case CARD_IDENTIFICATION_INPUT: if (validateIdentificationNumber(true)) { createToken(); return true; } return false; } return false; } private boolean checkIsEmptyOrValid() { switch (mCurrentEditingEditText) { case CARDHOLDER_NAME_INPUT: if (TextUtils.isEmpty(mCardHolderName) || validateCardName(true)) { if (onlyPortrait()) { mCardExpiryDateInput.setVisibility(View.GONE); } mCardNumberInput.setVisibility(View.VISIBLE); mCardNumberEditText.requestFocus(); return true; } return false; case CARD_EXPIRYDATE_INPUT: if (mExpiryMonth == null || validateExpiryDate(true)) { if (onlyPortrait()) { mIdentificationTypeContainer.setVisibility(View.GONE); mSecurityCodeEditView.setVisibility(View.GONE); mCardIdNumberInput.setVisibility(View.GONE); } mCardholderNameInput.setVisibility(View.VISIBLE); mCardHolderNameEditText.requestFocus(); return true; } return false; case CARD_SECURITYCODE_INPUT: if (TextUtils.isEmpty(mSecurityCode) || validateSecurityCode(true)) { if (onlyPortrait()) { mIdentificationTypeContainer.setVisibility(View.GONE); mCardIdNumberInput.setVisibility(View.GONE); } mCardExpiryDateInput.setVisibility(View.VISIBLE); mCardExpiryDateEditText.requestFocus(); return true; } return false; case CARD_IDENTIFICATION_INPUT: if (TextUtils.isEmpty(mCardIdentificationNumber) || validateIdentificationNumber(true)) { if (onlyPortrait()) { mCardIdNumberInput.setVisibility(View.GONE); } if (isSecurityCodeRequired()) { mSecurityCodeEditView.setVisibility(View.VISIBLE); mCardSecurityCodeEditText.requestFocus(); } else { mCardExpiryDateInput.setVisibility(View.VISIBLE); mCardExpiryDateEditText.requestFocus(); } return true; } return false; } return false; } protected void getPaymentMethodsAsync() { mMercadoPago.getPaymentMethods(new Callback<List<PaymentMethod>>() { @Override public void success(List<PaymentMethod> paymentMethods) { if (isActivityActive()) { mPaymentMethodList = paymentMethods; startGuessingForm(); } } @Override public void failure(ApiException apiException) { if (isActivityActive()) { setFailureRecovery(new FailureRecovery() { @Override public void recover() { getPaymentMethodsAsync(); } }); ApiUtil.showApiExceptionError(getActivity(), apiException); } } }); } protected void getBankDealsAsync() { mMercadoPago.getBankDeals(new Callback<List<BankDeal>>() { @Override public void success(final List<BankDeal> bankDeals) { if (bankDeals != null && bankDeals.size() >= 1) { mToolbarButton.setText(getString(R.string.mpsdk_bank_deals_action)); mToolbarButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MercadoPago.StartActivityBuilder() .setActivity(getActivity()) .setPublicKey(mPublicKey) .setDecorationPreference(mDecorationPreference) .setBankDeals(bankDeals) .startBankDealsActivity(); } }); } } @Override public void failure(ApiException apiException) { if (isActivityActive()) { setFailureRecovery(new FailureRecovery() { @Override public void recover() { getBankDealsAsync(); } }); ApiUtil.showApiExceptionError(getActivity(), apiException); } } }); } protected void startGuessingForm() { initializeGuessingCardNumberController(); setCardNumberListener(); } @Override public IdentificationType getCardIdentificationType() { return mSelectedIdentificationType; } @Override public void initializeCardByToken() { if (mToken == null) { return; } if (mToken.getFirstSixDigits() != null) { mCardNumberEditText.setText(mToken.getFirstSixDigits()); } if (mToken.getCardholder() != null && mToken.getCardholder().getName() != null) { mCardHolderNameEditText.setText(mToken.getCardholder().getName()); } if (mToken.getExpirationMonth() != null && mToken.getExpirationYear() != null) { mCardExpiryDateEditText.append(mToken.getExpirationMonth().toString()); mCardExpiryDateEditText.append(mToken.getExpirationYear().toString().substring(2, 4)); } if (mToken.getCardholder() != null && mToken.getCardholder().getIdentification() != null) { String number = mToken.getCardholder().getIdentification().getNumber(); if (number != null) { saveCardIdentificationNumber(number); mCardIdentificationNumberEditText.setText(number); } } mCardNumberEditText.requestFocus(); } protected void initializeGuessingCardNumberController() { List<PaymentMethod> supportedPaymentMethods = mPaymentPreference .getSupportedPaymentMethods(mPaymentMethodList); mPaymentMethodGuessingController = new PaymentMethodGuessingController( supportedPaymentMethods, mPaymentPreference.getDefaultPaymentTypeId(), mPaymentPreference.getExcludedPaymentTypes()); } public void setCardNumberListener() { mCardNumberEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() == 1) { openKeyboard(mCardNumberEditText); } if (before == 0 && needsMask(s)) { mCardNumberEditText.append(" "); } if (before == 1 && needsMask(s)) { mCardNumberEditText.getText().delete(s.length() - 1, s.length()); } } @Override public void afterTextChanged(Editable s) { checkChangeErrorView(); mCardNumberEditText.toggleLineColorOnError(false); } }); mCardNumberEditText.addTextChangedListener(new CardNumberTextWatcher( mPaymentMethodGuessingController, new PaymentMethodSelectionCallback() { @Override public void onPaymentMethodListSet(List<PaymentMethod> paymentMethodList) { if (paymentMethodList.size() == 0 || paymentMethodList.size() > 1) { blockCardNumbersInput(mCardNumberEditText); setErrorView(getString(R.string.mpsdk_invalid_payment_method)); } else { onPaymentMethodSet(paymentMethodList.get(0)); } } @Override public void onPaymentMethodSet(PaymentMethod paymentMethod) { if (mCurrentPaymentMethod == null) { mCurrentPaymentMethod = paymentMethod; fadeInColor(getCardColor(paymentMethod)); changeCardImage(getCardImage(paymentMethod)); manageSettings(); manageAdditionalInfoNeeded(); mFrontFragment.populateCardNumber(getCardNumber()); } } @Override public void onPaymentMethodCleared() { clearErrorView(); clearCardNumbersInput(mCardNumberEditText); if (mCurrentPaymentMethod == null) return; mCurrentPaymentMethod = null; setSecurityCodeLocation(null); setSecurityCodeRequired(true); mSecurityCode = ""; mCardSecurityCodeEditText.getText().clear(); mCardToken = new CardToken("", null, null, "", "", "", ""); mIdentificationNumberRequired = true; fadeOutColor(); clearCardImage(); clearSecurityCodeFront(); } })); } private boolean needsMask(CharSequence s) { if (mCardNumberLength == CARD_NUMBER_AMEX_LENGTH || mCardNumberLength == CARD_NUMBER_DINERS_LENGTH) { return s.length() == 4 || s.length() == 11; } else { return s.length() == 4 || s.length() == 9 || s.length() == 14; } } private void initCardState() { if (mCardSideState == null) { mCardSideState = CARD_SIDE_FRONT; } } protected boolean showingIdentification() { initCardState(); return mCardSideState.equals(CARD_IDENTIFICATION); } protected boolean showingBack() { initCardState(); return mCardSideState.equals(CARD_SIDE_BACK); } protected boolean showingFront() { initCardState(); return mCardSideState.equals(CARD_SIDE_FRONT); } public void checkFlipCardToFront(boolean showBankDeals) { if (showingBack() || showingIdentification()) { if (showingBack()) { showFrontFragmentFromBack(); } else if (showingIdentification()) { getSupportFragmentManager().popBackStack(); mCardSideState = CARD_SIDE_FRONT; } if (showBankDeals) { mToolbarButton.setVisibility(View.VISIBLE); } } } private void showFrontFragmentFromBack() { mCardSideState = CARD_SIDE_FRONT; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { getWindow().setFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); float distance = mCardBackground.getResources().getDimension(R.dimen.mpsdk_card_camera_distance); float scale = getResources().getDisplayMetrics().density; float cameraDistance = scale * distance; MPAnimationUtils.flipToFront(this, cameraDistance, mFrontView, mBackView); } else { getSupportFragmentManager().popBackStack(); } } public void checkFlipCardToBack(boolean showBankDeals) { if (showingFront()) { startBackFragment(); } else if (showingIdentification()) { getSupportFragmentManager().popBackStack(); mCardSideState = CARD_SIDE_BACK; if (showBankDeals) { mToolbarButton.setVisibility(View.VISIBLE); } } } public void checkTransitionCardToId() { if (!mIdentificationNumberRequired) { return; } if (showingFront() || showingBack()) { startIdentificationFragment(); } } private void startIdentificationFragment() { mToolbarButton.setVisibility(View.GONE); int container = R.id.mpsdkActivityNewCardContainerFront; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { if (showingBack()) { container = R.id.mpsdkActivityNewCardContainerBack; } else if (showingFront()) { container = R.id.mpsdkActivityNewCardContainerFront; } } mCardSideState = CARD_IDENTIFICATION; getSupportFragmentManager() .beginTransaction() .setCustomAnimations(R.anim.mpsdk_appear_from_right, R.anim.mpsdk_dissapear_to_left, R.anim.mpsdk_appear_from_left, R.anim.mpsdk_dissapear_to_right) .replace(container, mCardIdentificationFragment) .addToBackStack("IDENTIFICATION_FRAGMENT") .commit(); } private void startBackFragment() { mCardSideState = CARD_SIDE_BACK; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { mBackFragment.populateViews(); getWindow().setFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); float distance = mCardBackground.getResources().getDimension(R.dimen.mpsdk_card_camera_distance); float scale = getResources().getDisplayMetrics().density; float cameraDistance = scale * distance; MPAnimationUtils.flipToBack(this, cameraDistance, mFrontView, mBackView); } else { getSupportFragmentManager() .beginTransaction() .setCustomAnimations(R.anim.mpsdk_from_middle_left, R.anim.mpsdk_to_middle_left, R.anim.mpsdk_from_middle_left, R.anim.mpsdk_to_middle_left) .replace(R.id.mpsdkActivityNewCardContainerFront, mBackFragment, "BACK_FRAGMENT") .addToBackStack(null) .commit(); } } public void manageSettings() { String bin = mPaymentMethodGuessingController.getSavedBin(); List<Setting> settings = mCurrentPaymentMethod.getSettings(); Setting setting = Setting.getSettingByBin(settings, bin); if (setting == null) { ApiUtil.showApiExceptionError(getActivity(), null); return; } CardNumber cardNumber = setting.getCardNumber(); Integer length = CardInterface.CARD_NUMBER_MAX_LENGTH; if (cardNumber != null && cardNumber.getLength() != null) { length = cardNumber.getLength(); } setCardNumberLength(length); if (mCurrentPaymentMethod.isSecurityCodeRequired(bin)) { SecurityCode securityCode = setting.getSecurityCode(); setSecurityCodeRestrictions(true, securityCode); setSecurityCodeViewRestrictions(securityCode); showSecurityCodeView(); } else { mSecurityCode = ""; setSecurityCodeRestrictions(false, null); hideSecurityCodeView(); } } public void manageAdditionalInfoNeeded() { if (mCurrentPaymentMethod == null) return; mIdentificationNumberRequired = mCurrentPaymentMethod.isIdentificationNumberRequired(); if (mIdentificationNumberRequired) { mIdentificationNumberContainer.setVisibility(View.VISIBLE); mMercadoPago.getIdentificationTypes(new Callback<List<IdentificationType>>() { @Override public void success(List<IdentificationType> identificationTypes) { if (isActivityActive()) { if (identificationTypes.isEmpty()) { ErrorUtil.startErrorActivity(getActivity(), getString(R.string.mpsdk_standard_error_message), "identification types call is empty at GuessingCardActivity", false); } else { mSelectedIdentificationType = identificationTypes.get(0); mIdentificationTypeSpinner.setAdapter(new IdentificationTypesAdapter(getActivity(), identificationTypes)); mIdentificationTypeContainer.setVisibility(View.VISIBLE); if (!onlyPortrait()) { mCardIdNumberInput.setVisibility(View.VISIBLE); } } } } @Override public void failure(ApiException apiException) { if (isActivityActive()) { setFailureRecovery(new FailureRecovery() { @Override public void recover() { manageAdditionalInfoNeeded(); } }); ApiUtil.showApiExceptionError(getActivity(), apiException); } } }); } } private void showSecurityCodeView() { mSecurityCodeEditView.setVisibility(View.VISIBLE); } private void hideSecurityCodeView() { clearSecurityCodeFront(); mSecurityCodeEditView.setVisibility(View.GONE); } public void blockCardNumbersInput(MPEditText text) { int maxLength = MercadoPago.BIN_LENGTH; setInputMaxLength(text, maxLength); } public void clearCardNumbersInput(MPEditText text) { int maxLength = CardInterface.CARD_NUMBER_MAX_LENGTH; setInputMaxLength(text, maxLength); } public void setInputMaxLength(MPEditText text, int maxLength) { InputFilter[] fArray = new InputFilter[1]; fArray[0] = new InputFilter.LengthFilter(maxLength); text.setFilters(fArray); } private void setCardNumberLength(int maxLength) { mCardNumberLength = maxLength; int spaces = CARD_DEFAULT_AMOUNT_SPACES; if (maxLength == CARD_NUMBER_DINERS_LENGTH || maxLength == CARD_NUMBER_AMEX_LENGTH) { spaces = CARD_AMEX_DINERS_AMOUNT_SPACES; } setInputMaxLength(mCardNumberEditText, mCardNumberLength + spaces); } private void setSecurityCodeViewRestrictions(SecurityCode securityCode) { //Location if (securityCode.getCardLocation().equals(CardInterface.CARD_SIDE_BACK)) { clearSecurityCodeFront(); mSecurityCode = mCardSecurityCodeEditText.getText().toString(); } else if (securityCode.getCardLocation().equals(CardInterface.CARD_SIDE_FRONT)) { mCardSecurityCodeEditText.setOnClickListener(null); mFrontFragment.setCardSecurityView(); } //Length setEditTextMaxLength(mCardSecurityCodeEditText, securityCode.getLength()); } private void setEditTextMaxLength(MPEditText editText, int maxLength) { InputFilter[] filters = new InputFilter[1]; filters[0] = new InputFilter.LengthFilter(maxLength); editText.setFilters(filters); } private void setCardSecurityCodeErrorView(String message, boolean requestFocus) { if (!isSecurityCodeRequired()) { return; } setErrorView(message); if (requestFocus) { mCardSecurityCodeEditText.toggleLineColorOnError(true); mCardSecurityCodeEditText.requestFocus(); } } @Override public int getCardNumberLength() { return mCardNumberLength; } @Override public int getSecurityCodeLength() { return mCardSecurityCodeLength; } @Override public String getSecurityCodeLocation() { if (mSecurityCodeLocation == null) { return CardInterface.CARD_SIDE_BACK; } else { return mSecurityCodeLocation; } } private void setCardIdentificationErrorView(String message, boolean requestFocus) { setErrorView(message); if (requestFocus) { mCardIdentificationNumberEditText.toggleLineColorOnError(true); mCardIdentificationNumberEditText.requestFocus(); } } private void clearSecurityCodeFront() { mFrontFragment.hideCardSecurityView(); setCardSecurityCodeFocusListener(); } public void fadeInColor(int color) { if (!showingBack() && mFrontFragment != null) { mFrontFragment.fadeInColor(color); } } public void fadeOutColor() { if (!showingBack() && mFrontFragment != null) { mFrontFragment.fadeOutColor(CardInterface.NEUTRAL_CARD_COLOR); } } public void changeCardImage(int image) { mFrontFragment.transitionImage(image); } public void clearCardImage() { mFrontFragment.clearImage(); } private void setCardNumberFocusListener() { mCardNumberEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { validateCurrentEditText(); return true; } else if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { validateCurrentEditText(); return true; } return false; } }); mCardNumberEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); if (action == MotionEvent.ACTION_DOWN) { openKeyboard(mCardNumberEditText); } return true; } }); mCardNumberEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { mFrontFragment.setFontColor(); if (hasFocus) { MPTracker.getInstance().trackScreen("CARD_NUMBER", 2, mPublicKey, BuildConfig.VERSION_NAME, getActivity()); disableBackInputButton(); openKeyboard(mCardNumberEditText); checkFlipCardToFront(true); mCurrentEditingEditText = CARD_NUMBER_INPUT; } } }); } private void disableBackInputButton() { mBackButton.setVisibility(View.GONE); mBackInactiveButton.setVisibility(View.VISIBLE); } private void enableBackInputButton() { mBackButton.setVisibility(View.VISIBLE); mBackInactiveButton.setVisibility(View.GONE); } private void setCardNameFocusListener() { mCardHolderNameEditText.setFilters(new InputFilter[]{new InputFilter.AllCaps()}); mCardHolderNameEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { validateCurrentEditText(); return true; } else if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { validateCurrentEditText(); return true; } return false; } }); mCardHolderNameEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); if (action == MotionEvent.ACTION_DOWN) { openKeyboard(mCardHolderNameEditText); } return true; } }); mCardHolderNameEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { mFrontFragment.setFontColor(); if (hasFocus) { MPTracker.getInstance().trackScreen("CARD_HOLDER_NAME", 2, mPublicKey, BuildConfig.VERSION_NAME, getActivity()); enableBackInputButton(); openKeyboard(mCardHolderNameEditText); checkFlipCardToFront(true); mCurrentEditingEditText = CARDHOLDER_NAME_INPUT; } } }); } private void setCardExpiryDateFocusListener() { mCardExpiryDateEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { validateCurrentEditText(); return true; } else if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { validateCurrentEditText(); return true; } return false; } }); mCardExpiryDateEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); if (action == MotionEvent.ACTION_DOWN) { openKeyboard(mCardExpiryDateEditText); } return true; } }); mCardExpiryDateEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { mFrontFragment.setFontColor(); if (hasFocus) { MPTracker.getInstance().trackScreen("CARD_EXPIRY_DATE", 2, mPublicKey, BuildConfig.VERSION_NAME, getActivity()); enableBackInputButton(); openKeyboard(mCardExpiryDateEditText); checkFlipCardToFront(true); mCurrentEditingEditText = CARD_EXPIRYDATE_INPUT; } } }); } private void setCardSecurityCodeFocusListener() { mCardSecurityCodeEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { validateCurrentEditText(); return true; } else if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { validateCurrentEditText(); return true; } else if (actionId == EditorInfo.IME_ACTION_DONE) { createToken(); return true; } return false; } }); mCardSecurityCodeEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); if (action == MotionEvent.ACTION_DOWN) { openKeyboard(mCardSecurityCodeEditText); } return true; } }); mCardSecurityCodeEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { mFrontFragment.setFontColor(); if (hasFocus && (mCurrentEditingEditText.equals(CARD_EXPIRYDATE_INPUT) || mCurrentEditingEditText.equals(CARD_IDENTIFICATION_INPUT) || mCurrentEditingEditText.equals(CARD_SECURITYCODE_INPUT))) { MPTracker.getInstance().trackScreen("CARD_SECURITY_CODE", 2, mPublicKey, BuildConfig.VERSION_NAME, getActivity()); enableBackInputButton(); openKeyboard(mCardSecurityCodeEditText); mCurrentEditingEditText = CARD_SECURITYCODE_INPUT; if (mSecurityCodeLocation == null || mSecurityCodeLocation.equals(CardInterface.CARD_SIDE_BACK)) { checkFlipCardToBack(true); } else { checkFlipCardToFront(true); } } } }); } public void setCardIdentificationFocusListener() { mIdentificationTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { mSelectedIdentificationType = (IdentificationType) mIdentificationTypeSpinner.getSelectedItem(); if (mSelectedIdentificationType != null) { mIdentification.setType(mSelectedIdentificationType.getId()); setEditTextMaxLength(mCardIdentificationNumberEditText, mSelectedIdentificationType.getMaxLength()); if (mSelectedIdentificationType.getType().equals("number")) { mCardIdentificationNumberEditText.setInputType(InputType.TYPE_CLASS_NUMBER); } else { mCardIdentificationNumberEditText.setInputType(InputType.TYPE_CLASS_TEXT); } if (!mCardIdentificationNumberEditText.getText().toString().isEmpty()) { validateIdentificationNumber(true); } } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); mIdentificationTypeSpinner.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (mCurrentEditingEditText.equals(CARD_SECURITYCODE_INPUT)) { return false; } checkTransitionCardToId(); mCardIdentificationNumberEditText.requestFocus(); return false; } }); mCardIdentificationNumberEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { validateCurrentEditText(); return true; } else if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { validateCurrentEditText(); return true; } return false; } }); mCardIdentificationNumberEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); if (action == MotionEvent.ACTION_DOWN) { openKeyboard(mCardIdentificationNumberEditText); } return true; } }); mCardIdentificationNumberEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { mFrontFragment.setFontColor(); if (hasFocus) { MPTracker.getInstance().trackScreen("IDENTIFICATION_NUMBER", 2, mPublicKey, BuildConfig.VERSION_NAME, getActivity()); enableBackInputButton(); openKeyboard(mCardIdentificationNumberEditText); checkTransitionCardToId(); mCurrentEditingEditText = CARD_IDENTIFICATION_INPUT; } } }); } public void setSecurityCodeTextWatcher() { mCardSecurityCodeEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (showingBack() && mBackFragment != null) { mBackFragment.onSecurityTextChanged(s); } else if (mFrontFragment != null) { mFrontFragment.onSecurityTextChanged(s); } if (s.length() == mCardSecurityCodeLength) { mSecurityCode = s.toString(); } } @Override public void afterTextChanged(Editable s) { checkChangeErrorView(); mCardSecurityCodeEditText.toggleLineColorOnError(false); if (showingBack() && mBackFragment != null) { mBackFragment.afterSecurityTextChanged(s); } else if (mFrontFragment != null) { mFrontFragment.afterSecurityTextChanged(s); } } }); } public void setIdentificationNumberTextWatcher() { mCardIdentificationNumberEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (showingIdentification() && mCardIdentificationFragment != null) { mCardIdentificationFragment.onNumberTextChanged(s, start, before, count); } if (mSelectedIdentificationType != null && mSelectedIdentificationType.getMaxLength() != null) { if (s.length() == mSelectedIdentificationType.getMaxLength()) { mIdentification.setNumber(s.toString()); validateIdentificationNumber(false); } } } @Override public void afterTextChanged(Editable s) { checkChangeErrorView(); mCardIdentificationNumberEditText.toggleLineColorOnError(false); if (showingIdentification() && mCardIdentificationFragment != null) { mCardIdentificationFragment.afterNumberTextChanged(s); } } }); } public void setCardholderNameTextWatcher() { mCardHolderNameEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { checkChangeErrorView(); mCardHolderNameEditText.toggleLineColorOnError(false); } }); } public void setExpiryDateTextWatcher() { mCardExpiryDateEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() == 2 && before == 0) { mCardExpiryDateEditText.append("/"); } if (s.length() == 2 && before == 1) { mCardExpiryDateEditText.getText().delete(s.length() - 1, s.length()); } } @Override public void afterTextChanged(Editable s) { checkChangeErrorView(); mCardExpiryDateEditText.toggleLineColorOnError(false); } }); } @Override public boolean isSecurityCodeRequired() { return mIsSecurityCodeRequired; } public void setSecurityCodeRequired(boolean required) { this.mIsSecurityCodeRequired = required; } public void setSecurityCodeLength(int length) { this.mCardSecurityCodeLength = length; } public void setSecurityCodeLocation(String location) { this.mSecurityCodeLocation = location; } public void setSecurityCodeRestrictions(boolean isRequired, SecurityCode securityCode) { setSecurityCodeRequired(isRequired); if (securityCode == null) { setSecurityCodeLocation(null); setSecurityCodeLength(CARD_DEFAULT_SECURITY_CODE_LENGTH); return; } setSecurityCodeLocation(securityCode.getCardLocation()); setSecurityCodeLength(securityCode.getLength()); } private void createToken() { LayoutUtil.hideKeyboard(this); mInputContainer.setVisibility(View.GONE); mProgressBar.setVisibility(View.VISIBLE); mBackButton.setVisibility(View.GONE); mNextButton.setVisibility(View.GONE); mMercadoPago.createToken(mCardToken, new Callback<Token>() { @Override public void success(Token token) { if (isActivityActive()) { mToken = token; checkStartIssuersActivity(); } } @Override public void failure(ApiException apiException) { if (isActivityActive()) { setFailureRecovery(new FailureRecovery() { @Override public void recover() { createToken(); } }); ApiUtil.showApiExceptionError(getActivity(), apiException); } } }); } private boolean validateCardNumber(boolean requestFocus) { mCardToken.setCardNumber(getCardNumber()); try { if (mCurrentPaymentMethod == null) { if (getCardNumber() == null || getCardNumber().length() < MercadoPago.BIN_LENGTH) { throw new RuntimeException(getString(R.string.mpsdk_invalid_card_number_incomplete)); } else if (getCardNumber().length() == MercadoPago.BIN_LENGTH) { throw new RuntimeException(getString(R.string.mpsdk_invalid_payment_method)); } else { throw new RuntimeException(getString(R.string.mpsdk_invalid_payment_method)); } } mCardToken.validateCardNumber(this, mCurrentPaymentMethod); clearErrorView(); return true; } catch (Exception e) { setErrorView(e.getMessage()); if (requestFocus) { mCardNumberEditText.toggleLineColorOnError(true); mCardNumberEditText.requestFocus(); } return false; } } private boolean validateCardName(boolean requestFocus) { Cardholder cardHolder = new Cardholder(); cardHolder.setName(mCardHolderName); cardHolder.setIdentification(mIdentification); mCardToken.setCardholder(cardHolder); if (mCardToken.validateCardholderName()) { clearErrorView(); return true; } else { setErrorView(getString(R.string.mpsdk_invalid_empty_name)); if (requestFocus) { mCardHolderNameEditText.toggleLineColorOnError(true); mCardHolderNameEditText.requestFocus(); } return false; } } private boolean validateExpiryDate(boolean requestFocus) { Integer month = (mExpiryMonth == null ? null : Integer.valueOf(mExpiryMonth)); Integer year = (mExpiryYear == null ? null : Integer.valueOf(mExpiryYear)); mCardToken.setExpirationMonth(month); mCardToken.setExpirationYear(year); if (mCardToken.validateExpiryDate()) { clearErrorView(); return true; } else { setErrorView(getString(R.string.mpsdk_invalid_expiry_date)); if (requestFocus) { mCardExpiryDateEditText.toggleLineColorOnError(true); mCardExpiryDateEditText.requestFocus(); } return false; } } public boolean validateSecurityCode(boolean requestFocus) { mCardToken.setSecurityCode(mSecurityCode); try { mCardToken.validateSecurityCode(this, mCurrentPaymentMethod); clearErrorView(); return true; } catch (Exception e) { setCardSecurityCodeErrorView(e.getMessage(), requestFocus); return false; } } public boolean validateIdentificationNumber(boolean requestFocus) { mIdentification.setNumber(getCardIdentificationNumber()); mCardToken.getCardholder().setIdentification(mIdentification); boolean ans = mCardToken.validateIdentificationNumber(mSelectedIdentificationType); if (ans) { clearErrorView(); mCardIdentificationNumberEditText.toggleLineColorOnError(false); } else { setCardIdentificationErrorView(getString(R.string.mpsdk_invalid_identification_number), requestFocus); } return ans; } public void checkChangeErrorView() { if (mErrorState.equals(ERROR_STATE)) { clearErrorView(); } } public void setErrorView(String message) { mButtonContainer.setVisibility(View.GONE); mErrorContainer.setVisibility(View.VISIBLE); mErrorTextView.setText(message); mErrorState = CardInterface.ERROR_STATE; } public void clearErrorView() { mButtonContainer.setVisibility(View.VISIBLE); mErrorContainer.setVisibility(View.GONE); mErrorTextView.setText(""); mErrorState = CardInterface.NORMAL_STATE; } public void checkStartIssuersActivity() { mMercadoPago.getIssuers(mCurrentPaymentMethod.getId(), mPaymentMethodGuessingController.getSavedBin(), new Callback<List<Issuer>>() { @Override public void success(List<Issuer> issuers) { if (isActivityActive()) { if (issuers.isEmpty()) { ErrorUtil.startErrorActivity(getActivity(), getString(R.string.mpsdk_standard_error_message), "issuers call is empty at GuessingCardActivity", false); } else if (issuers.size() == 1) { mSelectedIssuer = issuers.get(0); mIssuerFound = true; finishWithResult(); } else { startIssuersActivity(issuers); } } } @Override public void failure(ApiException apiException) { if (isActivityActive()) { setFailureRecovery(new FailureRecovery() { @Override public void recover() { checkStartIssuersActivity(); } }); ApiUtil.showApiExceptionError(getActivity(), apiException); } } }); } private void setIssuerDefaultAnimation() { overridePendingTransition(R.anim.mpsdk_slide_right_to_left_in, R.anim.mpsdk_slide_right_to_left_out); } private void setIssuerSelectedAnimation() { overridePendingTransition(R.anim.mpsdk_hold, R.anim.mpsdk_hold); } public void startIssuersActivity(final List<Issuer> issuers) { new MercadoPago.StartActivityBuilder() .setActivity(getActivity()) .setPublicKey(mPublicKey) .setPaymentMethod(mCurrentPaymentMethod) .setToken(mToken) .setIssuers(issuers) .setDecorationPreference(mDecorationPreference) .startIssuersActivity(); overridePendingTransition(R.anim.mpsdk_slide_right_to_left_in, R.anim.mpsdk_slide_right_to_left_out); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == MercadoPago.ISSUERS_REQUEST_CODE) { if (resultCode == RESULT_OK) { Bundle bundle = data.getExtras(); mSelectedIssuer = JsonUtil.getInstance().fromJson(bundle.getString("issuer"), Issuer.class); checkFlipCardToFront(false); mIssuerFound = false; finishWithResult(); } else if (resultCode == RESULT_CANCELED) { finish(); } } else if (requestCode == ErrorUtil.ERROR_REQUEST_CODE) { if (resultCode == RESULT_OK) { recoverFromFailure(); } else { setResult(resultCode, data); finish(); } } } private void finishWithResult() { Intent returnIntent = new Intent(); returnIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(mCurrentPaymentMethod)); returnIntent.putExtra("token", JsonUtil.getInstance().toJson(mToken)); returnIntent.putExtra("issuer", JsonUtil.getInstance().toJson(mSelectedIssuer)); setResult(RESULT_OK, returnIntent); finish(); if (mIssuerFound) { setIssuerDefaultAnimation(); } else { setIssuerSelectedAnimation(); } } private static class CardNumberTextWatcher implements TextWatcher { private PaymentMethodGuessingController mController; private PaymentMethodSelectionCallback mCallback; private String mBin; public CardNumberTextWatcher(PaymentMethodGuessingController controller, PaymentMethodSelectionCallback callback) { this.mController = controller; this.mCallback = callback; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (mController == null) return; String number = s.toString().replaceAll("\\s", ""); if (number.length() == MercadoPago.BIN_LENGTH - 1) { mCallback.onPaymentMethodCleared(); } else if (number.length() >= MercadoPago.BIN_LENGTH) { mBin = number.subSequence(0, MercadoPago.BIN_LENGTH).toString(); List<PaymentMethod> list = mController.guessPaymentMethodsByBin(mBin); mCallback.onPaymentMethodListSet(list); } } } }
sdk/src/main/java/com/mercadopago/GuessingCardActivity.java
package com.mercadopago; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.support.v4.view.MotionEventCompat; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import com.google.gson.reflect.TypeToken; import com.mercadopago.adapters.IdentificationTypesAdapter; import com.mercadopago.callbacks.Callback; import com.mercadopago.callbacks.FailureRecovery; import com.mercadopago.callbacks.PaymentMethodSelectionCallback; import com.mercadopago.controllers.PaymentMethodGuessingController; import com.mercadopago.core.MercadoPago; import com.mercadopago.fragments.CardBackFragment; import com.mercadopago.fragments.CardFrontFragment; import com.mercadopago.fragments.CardIdentificationFragment; import com.mercadopago.model.ApiException; import com.mercadopago.model.BankDeal; import com.mercadopago.model.CardNumber; import com.mercadopago.model.CardToken; import com.mercadopago.model.Cardholder; import com.mercadopago.model.Identification; import com.mercadopago.model.IdentificationType; import com.mercadopago.model.Issuer; import com.mercadopago.model.PaymentMethod; import com.mercadopago.model.PaymentPreference; import com.mercadopago.model.SecurityCode; import com.mercadopago.model.Setting; import com.mercadopago.model.Token; import com.mercadopago.mptracker.MPTracker; import com.mercadopago.util.ApiUtil; import com.mercadopago.util.ErrorUtil; import com.mercadopago.util.JsonUtil; import com.mercadopago.util.LayoutUtil; import com.mercadopago.util.MPAnimationUtils; import com.mercadopago.views.MPEditText; import com.mercadopago.views.MPTextView; import java.lang.reflect.Type; import java.util.List; public class GuessingCardActivity extends FrontCardActivity { // Activity parameters protected String mPublicKey; protected List<PaymentMethod> mPaymentMethodList; // Input controls private MPTextView mToolbarButton; private MPEditText mCardHolderNameEditText; private MPEditText mCardNumberEditText; private MPEditText mCardExpiryDateEditText; private MPEditText mCardSecurityCodeEditText; private MPEditText mCardIdentificationNumberEditText; private MPTextView mErrorTextView; private LinearLayout mSecurityCodeEditView; private LinearLayout mInputContainer; private Spinner mIdentificationTypeSpinner; private LinearLayout mIdentificationTypeContainer; private LinearLayout mIdentificationNumberContainer; private ScrollView mScrollView; private ProgressBar mProgressBar; private FrameLayout mBackButton; private FrameLayout mNextButton; private FrameLayout mBackInactiveButton; private FrameLayout mErrorContainer; private LinearLayout mButtonContainer; private View mCardBackground; private LinearLayout mCardNumberInput; private LinearLayout mCardholderNameInput; private LinearLayout mCardExpiryDateInput; private LinearLayout mCardIdNumberInput; private View mFrontView; private View mBackView; //Card container private CardFrontFragment mFrontFragment; private CardBackFragment mBackFragment; private CardIdentificationFragment mCardIdentificationFragment; // Local vars private MercadoPago mMercadoPago; private PaymentPreference mPaymentPreference; private CardToken mCardToken; private Token mToken; private Identification mIdentification; private Issuer mSelectedIssuer; private IdentificationType mSelectedIdentificationType; private boolean mIdentificationNumberRequired; private String mCardSideState; private String mCurrentEditingEditText; protected PaymentMethodGuessingController mPaymentMethodGuessingController; private boolean mIsSecurityCodeRequired; private int mCardSecurityCodeLength; private int mCardNumberLength; private String mSecurityCodeLocation; private boolean mIssuerFound; @Override protected void onResume() { super.onResume(); if (mCardSideState == null) { mCardSideState = CARD_SIDE_FRONT; } openKeyboard(); } @Override protected void onDestroy() { if (showingFront() && mFrontFragment != null) { mFrontFragment.setCardColor(CardInterface.NEUTRAL_CARD_COLOR); } super.onDestroy(); } @Override public void onBackPressed() { checkFlipCardToFront(true); MPTracker.getInstance().trackEvent("GUESSING_CARD", "BACK_PRESSED", 2, mPublicKey, BuildConfig.VERSION_NAME, this); Intent returnIntent = new Intent(); returnIntent.putExtra("backButtonPressed", true); setResult(RESULT_CANCELED, returnIntent); finish(); } private void initializeToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.mpsdkToolbar); mToolbarButton = (MPTextView) findViewById(R.id.mpsdkButtonText); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } if (toolbar != null) { toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } if (mDecorationPreference != null) { if (mDecorationPreference.hasColors()) { if (toolbar != null) { decorateToolbar(toolbar); } } } LayoutUtil.showProgressLayout(this); } private void decorateToolbar(Toolbar toolbar) { if (mDecorationPreference.isDarkFontEnabled()) { mToolbarButton.setTextColor(mDecorationPreference.getDarkFontColor(this)); Drawable upArrow = toolbar.getNavigationIcon(); if (upArrow != null) { upArrow.setColorFilter(mDecorationPreference.getDarkFontColor(this), PorterDuff.Mode.SRC_ATOP); } getSupportActionBar().setHomeAsUpIndicator(upArrow); } toolbar.setBackgroundColor(mDecorationPreference.getLighterColor()); } @Override protected void setContentView() { setContentView(R.layout.mpsdk_activity_new_card_form); } @Override protected void validateActivityParameters() throws IllegalStateException { if (mPublicKey == null) { throw new IllegalStateException(); } } @Override protected void onBeforeCreation() { if (onlyPortrait()) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } @Override protected void onValidStart() { if (!onlyPortrait()) { setLandscapeModeInitialLayout(); } initializeToolbar(); setListeners(); openKeyboard(mCardNumberEditText); mCurrentEditingEditText = CardInterface.CARD_NUMBER_INPUT; mMercadoPago = new MercadoPago.Builder() .setContext(getActivity()) .setPublicKey(mPublicKey) .build(); getBankDealsAsync(); if (mPaymentMethodList == null) { getPaymentMethodsAsync(); } else { startGuessingForm(); } } private boolean onlyPortrait() { return getResources().getBoolean(R.bool.only_portrait); } private void setLandscapeModeInitialLayout() { mCardExpiryDateInput.setVisibility(View.VISIBLE); mSecurityCodeEditView.setVisibility(View.VISIBLE); } @Override protected void onInvalidStart(String message) { Intent returnIntent = new Intent(); setResult(RESULT_CANCELED, returnIntent); finish(); } @Override protected void initializeFragments(Bundle savedInstanceState) { mIssuerFound = true; mErrorState = CardInterface.NORMAL_STATE; mCardToken = new CardToken("", null, null, "", "", "", ""); mIsSecurityCodeRequired = true; mCardSecurityCodeLength = CARD_DEFAULT_SECURITY_CODE_LENGTH; mCardNumberLength = CARD_NUMBER_MAX_LENGTH; mSecurityCodeLocation = null; if (mFrontFragment == null) { mFrontFragment = new CardFrontFragment(); mFrontFragment.setDecorationPreference(mDecorationPreference); } if (mBackFragment == null) { mBackFragment = new CardBackFragment(); mBackFragment.setDecorationPreference(mDecorationPreference); } if (mCardIdentificationFragment == null) { mCardIdentificationFragment = new CardIdentificationFragment(); } if (savedInstanceState == null) { initializeFrontFragment(); initializeBackFragment(); } } private void initializeFrontFragment() { mFrontView = findViewById(R.id.mpsdkActivityNewCardContainerFront); mCardSideState = CARD_SIDE_FRONT; getSupportFragmentManager() .beginTransaction() .add(R.id.mpsdkActivityNewCardContainerFront, mFrontFragment) .commit(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { mFrontView.setAlpha(1.0f); } } private void initializeBackFragment() { mBackView = findViewById(R.id.mpsdkActivityNewCardContainerBack); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { getSupportFragmentManager() .beginTransaction() .add(R.id.mpsdkActivityNewCardContainerBack, mBackFragment) .commit(); mBackView.setAlpha(0); } } @Override protected void initializeControls() { mCardNumberEditText = (MPEditText) findViewById(R.id.mpsdkCardNumber); mCardHolderNameEditText = (MPEditText) findViewById(R.id.mpsdkCardholderName); mCardExpiryDateEditText = (MPEditText) findViewById(R.id.mpsdkCardExpiryDate); mCardSecurityCodeEditText = (MPEditText) findViewById(R.id.mpsdkCardSecurityCode); mCardIdentificationNumberEditText = (MPEditText) findViewById(R.id.mpsdkCardIdentificationNumber); mSecurityCodeEditView = (LinearLayout) findViewById(R.id.mpsdkCardSecurityCodeContainer); mInputContainer = (LinearLayout) findViewById(R.id.mpsdkNewCardInputContainer); mIdentificationTypeSpinner = (Spinner) findViewById(R.id.mpsdkCardIdentificationType); mIdentificationTypeContainer = (LinearLayout) findViewById(R.id.mpsdkCardIdentificationTypeContainer); mIdentificationNumberContainer = (LinearLayout) findViewById(R.id.mpsdkCardIdentificationNumberContainer); mProgressBar = (ProgressBar) findViewById(R.id.mpsdkProgressBar); mBackButton = (FrameLayout) findViewById(R.id.mpsdkBackButton); mNextButton = (FrameLayout) findViewById(R.id.mpsdkNextButton); mBackInactiveButton = (FrameLayout) findViewById(R.id.mpsdkBackInactiveButton); mButtonContainer = (LinearLayout) findViewById(R.id.mpsdkButtonContainer); mErrorContainer = (FrameLayout) findViewById(R.id.mpsdkErrorContainer); mErrorTextView = (MPTextView) findViewById(R.id.mpsdkErrorTextView); mScrollView = (ScrollView) findViewById(R.id.mpsdkScrollViewContainer); mCardNumberInput = (LinearLayout) findViewById(R.id.mpsdkCardNumberInput); mCardholderNameInput = (LinearLayout) findViewById(R.id.mpsdkCardholderNameInput); mCardExpiryDateInput = (LinearLayout) findViewById(R.id.mpsdkExpiryDateInput); mCardIdNumberInput = (LinearLayout) findViewById(R.id.mpsdkCardIdentificationInput); mProgressBar.setVisibility(View.GONE); mIdentificationTypeContainer.setVisibility(View.GONE); mIdentificationNumberContainer.setVisibility(View.GONE); mButtonContainer.setVisibility(View.VISIBLE); mCardBackground = findViewById(R.id.mpsdkCardBackground); if (mDecorationPreference != null && mDecorationPreference.hasColors()) { mCardBackground.setBackgroundColor(mDecorationPreference.getLighterColor()); } fullScrollDown(); } private void fullScrollDown() { Runnable r = new Runnable() { public void run() { mScrollView.fullScroll(View.FOCUS_DOWN); } }; mScrollView.post(r); r.run(); } @Override protected void getActivityParameters() { mPublicKey = this.getIntent().getStringExtra("publicKey"); mPaymentPreference = JsonUtil.getInstance().fromJson(this.getIntent().getStringExtra("paymentPreference"), PaymentPreference.class); mToken = JsonUtil.getInstance().fromJson(this.getIntent().getStringExtra("token"), Token.class); try { Type listType = new TypeToken<List<PaymentMethod>>() { }.getType(); mPaymentMethodList = JsonUtil.getInstance().getGson().fromJson(this.getIntent().getStringExtra("paymentMethodList"), listType); } catch (Exception ex) { mPaymentMethodList = null; } mIdentification = new Identification(); mIdentificationNumberRequired = false; if (mPaymentPreference == null) { mPaymentPreference = new PaymentPreference(); } } protected void setListeners() { setCardNumberFocusListener(); setCardNameFocusListener(); setCardExpiryDateFocusListener(); setCardSecurityCodeFocusListener(); setCardIdentificationFocusListener(); setNavigationButtonsListeners(); setSecurityCodeTextWatcher(); setIdentificationNumberTextWatcher(); setCardholderNameTextWatcher(); setExpiryDateTextWatcher(); } public void openKeyboard(MPEditText ediText) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(ediText, InputMethodManager.SHOW_IMPLICIT); fullScrollDown(); } private void setNavigationButtonsListeners() { mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { validateCurrentEditText(); } }); mBackButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mCurrentEditingEditText.equals(CARD_NUMBER_INPUT)) { checkIsEmptyOrValid(); } } }); } private void openKeyboard() { if (mCurrentEditingEditText == null) { mCurrentEditingEditText = CARD_NUMBER_INPUT; } switch (mCurrentEditingEditText) { case CARD_NUMBER_INPUT: openKeyboard(mCardNumberEditText); break; case CARDHOLDER_NAME_INPUT: openKeyboard(mCardHolderNameEditText); break; case CARD_EXPIRYDATE_INPUT: openKeyboard(mCardExpiryDateEditText); break; case CARD_SECURITYCODE_INPUT: openKeyboard(mCardSecurityCodeEditText); break; case CARD_IDENTIFICATION_INPUT: openKeyboard(mCardIdentificationNumberEditText); break; } } private boolean validateCurrentEditText() { switch (mCurrentEditingEditText) { case CARD_NUMBER_INPUT: if (validateCardNumber(true)) { mCardNumberInput.setVisibility(View.GONE); mCardExpiryDateInput.setVisibility(View.VISIBLE); mCardHolderNameEditText.requestFocus(); return true; } return false; case CARDHOLDER_NAME_INPUT: if (validateCardName(true)) { mCardholderNameInput.setVisibility(View.GONE); if (isSecurityCodeRequired()) { mSecurityCodeEditView.setVisibility(View.VISIBLE); } else if (mIdentificationNumberRequired) { mIdentificationTypeContainer.setVisibility(View.VISIBLE); } mCardExpiryDateEditText.requestFocus(); return true; } return false; case CARD_EXPIRYDATE_INPUT: if (validateExpiryDate(true)) { mCardExpiryDateInput.setVisibility(View.GONE); if (isSecurityCodeRequired()) { mCardSecurityCodeEditText.requestFocus(); if (mIdentificationNumberRequired) { mIdentificationTypeContainer.setVisibility(View.VISIBLE); } } else if (mIdentificationNumberRequired) { mCardIdentificationNumberEditText.requestFocus(); mCardIdNumberInput.setVisibility(View.VISIBLE); } else { createToken(); } return true; } return false; case CARD_SECURITYCODE_INPUT: if (validateSecurityCode(true)) { mSecurityCodeEditView.setVisibility(View.GONE); if (mIdentificationNumberRequired) { mCardIdentificationNumberEditText.requestFocus(); mCardIdNumberInput.setVisibility(View.VISIBLE); } else { createToken(); } return true; } return false; case CARD_IDENTIFICATION_INPUT: if (validateIdentificationNumber(true)) { createToken(); return true; } return false; } return false; } private boolean checkIsEmptyOrValid() { switch (mCurrentEditingEditText) { case CARDHOLDER_NAME_INPUT: if (TextUtils.isEmpty(mCardHolderName) || validateCardName(true)) { if (onlyPortrait()) { mCardExpiryDateInput.setVisibility(View.GONE); } mCardNumberInput.setVisibility(View.VISIBLE); mCardNumberEditText.requestFocus(); return true; } return false; case CARD_EXPIRYDATE_INPUT: if (mExpiryMonth == null || validateExpiryDate(true)) { if (onlyPortrait()) { mIdentificationTypeContainer.setVisibility(View.GONE); mSecurityCodeEditView.setVisibility(View.GONE); mCardIdNumberInput.setVisibility(View.GONE); } mCardholderNameInput.setVisibility(View.VISIBLE); mCardHolderNameEditText.requestFocus(); return true; } return false; case CARD_SECURITYCODE_INPUT: if (TextUtils.isEmpty(mSecurityCode) || validateSecurityCode(true)) { if (onlyPortrait()) { mIdentificationTypeContainer.setVisibility(View.GONE); mCardIdNumberInput.setVisibility(View.GONE); } mCardExpiryDateInput.setVisibility(View.VISIBLE); mCardExpiryDateEditText.requestFocus(); return true; } return false; case CARD_IDENTIFICATION_INPUT: if (TextUtils.isEmpty(mCardIdentificationNumber) || validateIdentificationNumber(true)) { if (onlyPortrait()) { mCardIdNumberInput.setVisibility(View.GONE); } if (isSecurityCodeRequired()) { mSecurityCodeEditView.setVisibility(View.VISIBLE); mCardSecurityCodeEditText.requestFocus(); } else { mCardExpiryDateInput.setVisibility(View.VISIBLE); mCardExpiryDateEditText.requestFocus(); } return true; } return false; } return false; } protected void getPaymentMethodsAsync() { mMercadoPago.getPaymentMethods(new Callback<List<PaymentMethod>>() { @Override public void success(List<PaymentMethod> paymentMethods) { if (isActivityActive()) { mPaymentMethodList = paymentMethods; startGuessingForm(); } } @Override public void failure(ApiException apiException) { if (isActivityActive()) { setFailureRecovery(new FailureRecovery() { @Override public void recover() { getPaymentMethodsAsync(); } }); ApiUtil.showApiExceptionError(getActivity(), apiException); } } }); } protected void getBankDealsAsync() { mMercadoPago.getBankDeals(new Callback<List<BankDeal>>() { @Override public void success(final List<BankDeal> bankDeals) { if (bankDeals != null && bankDeals.size() >= 1) { mToolbarButton.setText(getString(R.string.mpsdk_bank_deals_action)); mToolbarButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MercadoPago.StartActivityBuilder() .setActivity(getActivity()) .setPublicKey(mPublicKey) .setDecorationPreference(mDecorationPreference) .setBankDeals(bankDeals) .startBankDealsActivity(); } }); } } @Override public void failure(ApiException apiException) { if (isActivityActive()) { setFailureRecovery(new FailureRecovery() { @Override public void recover() { getBankDealsAsync(); } }); ApiUtil.showApiExceptionError(getActivity(), apiException); } } }); } protected void startGuessingForm() { initializeGuessingCardNumberController(); setCardNumberListener(); } @Override public IdentificationType getCardIdentificationType() { return mSelectedIdentificationType; } @Override public void initializeCardByToken() { if (mToken == null) { return; } if (mToken.getFirstSixDigits() != null) { mCardNumberEditText.setText(mToken.getFirstSixDigits()); } if (mToken.getCardholder() != null && mToken.getCardholder().getName() != null) { mCardHolderNameEditText.setText(mToken.getCardholder().getName()); } if (mToken.getExpirationMonth() != null && mToken.getExpirationYear() != null) { mCardExpiryDateEditText.append(mToken.getExpirationMonth().toString()); mCardExpiryDateEditText.append(mToken.getExpirationYear().toString().substring(2, 4)); } if (mToken.getCardholder() != null && mToken.getCardholder().getIdentification() != null) { String number = mToken.getCardholder().getIdentification().getNumber(); if (number != null) { saveCardIdentificationNumber(number); mCardIdentificationNumberEditText.setText(number); } } mCardNumberEditText.requestFocus(); } protected void initializeGuessingCardNumberController() { List<PaymentMethod> supportedPaymentMethods = mPaymentPreference .getSupportedPaymentMethods(mPaymentMethodList); mPaymentMethodGuessingController = new PaymentMethodGuessingController( supportedPaymentMethods, mPaymentPreference.getDefaultPaymentTypeId(), mPaymentPreference.getExcludedPaymentTypes()); } public void setCardNumberListener() { mCardNumberEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() == 1) { openKeyboard(mCardNumberEditText); } if (before == 0 && needsMask(s)) { mCardNumberEditText.append(" "); } if (before == 1 && needsMask(s)) { mCardNumberEditText.getText().delete(s.length() - 1, s.length()); } } @Override public void afterTextChanged(Editable s) { checkChangeErrorView(); mCardNumberEditText.toggleLineColorOnError(false); } }); mCardNumberEditText.addTextChangedListener(new CardNumberTextWatcher( mPaymentMethodGuessingController, new PaymentMethodSelectionCallback() { @Override public void onPaymentMethodListSet(List<PaymentMethod> paymentMethodList) { if (paymentMethodList.size() == 0 || paymentMethodList.size() > 1) { blockCardNumbersInput(mCardNumberEditText); setErrorView(getString(R.string.mpsdk_invalid_payment_method)); } else { onPaymentMethodSet(paymentMethodList.get(0)); } } @Override public void onPaymentMethodSet(PaymentMethod paymentMethod) { if (mCurrentPaymentMethod == null) { mCurrentPaymentMethod = paymentMethod; fadeInColor(getCardColor(paymentMethod)); changeCardImage(getCardImage(paymentMethod)); manageSettings(); manageAdditionalInfoNeeded(); mFrontFragment.populateCardNumber(getCardNumber()); } } @Override public void onPaymentMethodCleared() { clearErrorView(); clearCardNumbersInput(mCardNumberEditText); if (mCurrentPaymentMethod == null) return; mCurrentPaymentMethod = null; setSecurityCodeLocation(null); setSecurityCodeRequired(true); mSecurityCode = ""; mCardSecurityCodeEditText.getText().clear(); mCardToken = new CardToken("", null, null, "", "", "", ""); mIdentificationNumberRequired = true; fadeOutColor(); clearCardImage(); clearSecurityCodeFront(); } })); } private boolean needsMask(CharSequence s) { if (mCardNumberLength == CARD_NUMBER_AMEX_LENGTH || mCardNumberLength == CARD_NUMBER_DINERS_LENGTH) { return s.length() == 4 || s.length() == 11; } else { return s.length() == 4 || s.length() == 9 || s.length() == 14; } } private void initCardState() { if (mCardSideState == null) { mCardSideState = CARD_SIDE_FRONT; } } protected boolean showingIdentification() { initCardState(); return mCardSideState.equals(CARD_IDENTIFICATION); } protected boolean showingBack() { initCardState(); return mCardSideState.equals(CARD_SIDE_BACK); } protected boolean showingFront() { initCardState(); return mCardSideState.equals(CARD_SIDE_FRONT); } public void checkFlipCardToFront(boolean showBankDeals) { if (showingBack() || showingIdentification()) { if (showingBack()) { showFrontFragmentFromBack(); } else if (showingIdentification()) { getSupportFragmentManager().popBackStack(); mCardSideState = CARD_SIDE_FRONT; } if (showBankDeals) { mToolbarButton.setVisibility(View.VISIBLE); } } } private void showFrontFragmentFromBack() { mCardSideState = CARD_SIDE_FRONT; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { getWindow().setFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); float distance = mCardBackground.getResources().getDimension(R.dimen.mpsdk_card_camera_distance); float scale = getResources().getDisplayMetrics().density; float cameraDistance = scale * distance; MPAnimationUtils.flipToFront(this, cameraDistance, mFrontView, mBackView); } else { getSupportFragmentManager().popBackStack(); } } public void checkFlipCardToBack(boolean showBankDeals) { if (showingFront()) { startBackFragment(); } else if (showingIdentification()) { getSupportFragmentManager().popBackStack(); mCardSideState = CARD_SIDE_BACK; if (showBankDeals) { mToolbarButton.setVisibility(View.VISIBLE); } } } public void checkTransitionCardToId() { if (!mIdentificationNumberRequired) { return; } if (showingFront() || showingBack()) { startIdentificationFragment(); } } private void startIdentificationFragment() { mToolbarButton.setVisibility(View.GONE); int container = R.id.mpsdkActivityNewCardContainerFront; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { if (showingBack()) { container = R.id.mpsdkActivityNewCardContainerBack; } else if (showingFront()) { container = R.id.mpsdkActivityNewCardContainerFront; } } mCardSideState = CARD_IDENTIFICATION; getSupportFragmentManager() .beginTransaction() .setCustomAnimations(R.anim.mpsdk_appear_from_right, R.anim.mpsdk_dissapear_to_left, R.anim.mpsdk_appear_from_left, R.anim.mpsdk_dissapear_to_right) .replace(container, mCardIdentificationFragment) .addToBackStack("IDENTIFICATION_FRAGMENT") .commit(); } private void startBackFragment() { mCardSideState = CARD_SIDE_BACK; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { mBackFragment.populateViews(); getWindow().setFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); float distance = mCardBackground.getResources().getDimension(R.dimen.mpsdk_card_camera_distance); float scale = getResources().getDisplayMetrics().density; float cameraDistance = scale * distance; MPAnimationUtils.flipToBack(this, cameraDistance, mFrontView, mBackView); } else { getSupportFragmentManager() .beginTransaction() .setCustomAnimations(R.anim.mpsdk_from_middle_left, R.anim.mpsdk_to_middle_left, R.anim.mpsdk_from_middle_left, R.anim.mpsdk_to_middle_left) .replace(R.id.mpsdkActivityNewCardContainerFront, mBackFragment, "BACK_FRAGMENT") .addToBackStack(null) .commit(); } } public void manageSettings() { String bin = mPaymentMethodGuessingController.getSavedBin(); List<Setting> settings = mCurrentPaymentMethod.getSettings(); Setting setting = Setting.getSettingByBin(settings, bin); if (setting == null) { ApiUtil.showApiExceptionError(getActivity(), null); return; } CardNumber cardNumber = setting.getCardNumber(); Integer length = CardInterface.CARD_NUMBER_MAX_LENGTH; if (cardNumber != null && cardNumber.getLength() != null) { length = cardNumber.getLength(); } setCardNumberLength(length); if (mCurrentPaymentMethod.isSecurityCodeRequired(bin)) { SecurityCode securityCode = setting.getSecurityCode(); setSecurityCodeRestrictions(true, securityCode); setSecurityCodeViewRestrictions(securityCode); showSecurityCodeView(); } else { mSecurityCode = ""; setSecurityCodeRestrictions(false, null); hideSecurityCodeView(); } } public void manageAdditionalInfoNeeded() { if (mCurrentPaymentMethod == null) return; mIdentificationNumberRequired = mCurrentPaymentMethod.isIdentificationNumberRequired(); if (mIdentificationNumberRequired) { mIdentificationNumberContainer.setVisibility(View.VISIBLE); mMercadoPago.getIdentificationTypes(new Callback<List<IdentificationType>>() { @Override public void success(List<IdentificationType> identificationTypes) { if (isActivityActive()) { if (identificationTypes.isEmpty()) { ErrorUtil.startErrorActivity(getActivity(), getString(R.string.mpsdk_standard_error_message), "identification types call is empty at GuessingCardActivity", false); } else { mSelectedIdentificationType = identificationTypes.get(0); mIdentificationTypeSpinner.setAdapter(new IdentificationTypesAdapter(getActivity(), identificationTypes)); mIdentificationTypeContainer.setVisibility(View.VISIBLE); if (!onlyPortrait()) { mCardIdNumberInput.setVisibility(View.VISIBLE); } } } } @Override public void failure(ApiException apiException) { if (isActivityActive()) { setFailureRecovery(new FailureRecovery() { @Override public void recover() { manageAdditionalInfoNeeded(); } }); ApiUtil.showApiExceptionError(getActivity(), apiException); } } }); } } private void showSecurityCodeView() { mSecurityCodeEditView.setVisibility(View.VISIBLE); } private void hideSecurityCodeView() { clearSecurityCodeFront(); mSecurityCodeEditView.setVisibility(View.GONE); } public void blockCardNumbersInput(MPEditText text) { int maxLength = MercadoPago.BIN_LENGTH; setInputMaxLength(text, maxLength); } public void clearCardNumbersInput(MPEditText text) { int maxLength = CardInterface.CARD_NUMBER_MAX_LENGTH; setInputMaxLength(text, maxLength); } public void setInputMaxLength(MPEditText text, int maxLength) { InputFilter[] fArray = new InputFilter[1]; fArray[0] = new InputFilter.LengthFilter(maxLength); text.setFilters(fArray); } private void setCardNumberLength(int maxLength) { mCardNumberLength = maxLength; int spaces = CARD_DEFAULT_AMOUNT_SPACES; if (maxLength == CARD_NUMBER_DINERS_LENGTH || maxLength == CARD_NUMBER_AMEX_LENGTH) { spaces = CARD_AMEX_DINERS_AMOUNT_SPACES; } setInputMaxLength(mCardNumberEditText, mCardNumberLength + spaces); } private void setSecurityCodeViewRestrictions(SecurityCode securityCode) { //Location if (securityCode.getCardLocation().equals(CardInterface.CARD_SIDE_BACK)) { clearSecurityCodeFront(); mSecurityCode = mCardSecurityCodeEditText.getText().toString(); } else if (securityCode.getCardLocation().equals(CardInterface.CARD_SIDE_FRONT)) { mCardSecurityCodeEditText.setOnClickListener(null); mFrontFragment.setCardSecurityView(); } //Length setEditTextMaxLength(mCardSecurityCodeEditText, securityCode.getLength()); } private void setEditTextMaxLength(MPEditText editText, int maxLength) { InputFilter[] filters = new InputFilter[1]; filters[0] = new InputFilter.LengthFilter(maxLength); editText.setFilters(filters); } private void setCardSecurityCodeErrorView(String message, boolean requestFocus) { if (!isSecurityCodeRequired()) { return; } setErrorView(message); if (requestFocus) { mCardSecurityCodeEditText.toggleLineColorOnError(true); mCardSecurityCodeEditText.requestFocus(); } } @Override public int getCardNumberLength() { return mCardNumberLength; } @Override public int getSecurityCodeLength() { return mCardSecurityCodeLength; } @Override public String getSecurityCodeLocation() { if (mSecurityCodeLocation == null) { return CardInterface.CARD_SIDE_BACK; } else { return mSecurityCodeLocation; } } private void setCardIdentificationErrorView(String message, boolean requestFocus) { setErrorView(message); if (requestFocus) { mCardIdentificationNumberEditText.toggleLineColorOnError(true); mCardIdentificationNumberEditText.requestFocus(); } } private void clearSecurityCodeFront() { mFrontFragment.hideCardSecurityView(); setCardSecurityCodeFocusListener(); } public void fadeInColor(int color) { if (!showingBack() && mFrontFragment != null) { mFrontFragment.fadeInColor(color); } } public void fadeOutColor() { if (!showingBack() && mFrontFragment != null) { mFrontFragment.fadeOutColor(CardInterface.NEUTRAL_CARD_COLOR); } } public void changeCardImage(int image) { mFrontFragment.transitionImage(image); } public void clearCardImage() { mFrontFragment.clearImage(); } private void setCardNumberFocusListener() { mCardNumberEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { validateCurrentEditText(); return true; } return false; } }); mCardNumberEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); if (action == MotionEvent.ACTION_DOWN) { openKeyboard(mCardNumberEditText); } return true; } }); mCardNumberEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { mFrontFragment.setFontColor(); if (hasFocus) { MPTracker.getInstance().trackScreen("CARD_NUMBER", 2, mPublicKey, BuildConfig.VERSION_NAME, getActivity()); disableBackInputButton(); openKeyboard(mCardNumberEditText); checkFlipCardToFront(true); mCurrentEditingEditText = CARD_NUMBER_INPUT; } } }); } private void disableBackInputButton() { mBackButton.setVisibility(View.GONE); mBackInactiveButton.setVisibility(View.VISIBLE); } private void enableBackInputButton() { mBackButton.setVisibility(View.VISIBLE); mBackInactiveButton.setVisibility(View.GONE); } private void setCardNameFocusListener() { mCardHolderNameEditText.setFilters(new InputFilter[]{new InputFilter.AllCaps()}); mCardHolderNameEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { validateCurrentEditText(); return true; } return false; } }); mCardHolderNameEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); if (action == MotionEvent.ACTION_DOWN) { openKeyboard(mCardHolderNameEditText); } return true; } }); mCardHolderNameEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { mFrontFragment.setFontColor(); if (hasFocus) { MPTracker.getInstance().trackScreen("CARD_HOLDER_NAME", 2, mPublicKey, BuildConfig.VERSION_NAME, getActivity()); enableBackInputButton(); openKeyboard(mCardHolderNameEditText); checkFlipCardToFront(true); mCurrentEditingEditText = CARDHOLDER_NAME_INPUT; } } }); } private void setCardExpiryDateFocusListener() { mCardExpiryDateEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { validateCurrentEditText(); return true; } return false; } }); mCardExpiryDateEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); if (action == MotionEvent.ACTION_DOWN) { openKeyboard(mCardExpiryDateEditText); } return true; } }); mCardExpiryDateEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { mFrontFragment.setFontColor(); if (hasFocus) { MPTracker.getInstance().trackScreen("CARD_EXPIRY_DATE", 2, mPublicKey, BuildConfig.VERSION_NAME, getActivity()); enableBackInputButton(); openKeyboard(mCardExpiryDateEditText); checkFlipCardToFront(true); mCurrentEditingEditText = CARD_EXPIRYDATE_INPUT; } } }); } private void setCardSecurityCodeFocusListener() { mCardSecurityCodeEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { validateCurrentEditText(); return true; } else if (actionId == EditorInfo.IME_ACTION_DONE) { createToken(); return true; } return false; } }); mCardSecurityCodeEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); if (action == MotionEvent.ACTION_DOWN) { openKeyboard(mCardSecurityCodeEditText); } return true; } }); mCardSecurityCodeEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { mFrontFragment.setFontColor(); if (hasFocus && (mCurrentEditingEditText.equals(CARD_EXPIRYDATE_INPUT) || mCurrentEditingEditText.equals(CARD_IDENTIFICATION_INPUT) || mCurrentEditingEditText.equals(CARD_SECURITYCODE_INPUT))) { MPTracker.getInstance().trackScreen("CARD_SECURITY_CODE", 2, mPublicKey, BuildConfig.VERSION_NAME, getActivity()); enableBackInputButton(); openKeyboard(mCardSecurityCodeEditText); mCurrentEditingEditText = CARD_SECURITYCODE_INPUT; if (mSecurityCodeLocation == null || mSecurityCodeLocation.equals(CardInterface.CARD_SIDE_BACK)) { checkFlipCardToBack(true); } else { checkFlipCardToFront(true); } } } }); } public void setCardIdentificationFocusListener() { mIdentificationTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { mSelectedIdentificationType = (IdentificationType) mIdentificationTypeSpinner.getSelectedItem(); if (mSelectedIdentificationType != null) { mIdentification.setType(mSelectedIdentificationType.getId()); setEditTextMaxLength(mCardIdentificationNumberEditText, mSelectedIdentificationType.getMaxLength()); if (mSelectedIdentificationType.getType().equals("number")) { mCardIdentificationNumberEditText.setInputType(InputType.TYPE_CLASS_NUMBER); } else { mCardIdentificationNumberEditText.setInputType(InputType.TYPE_CLASS_TEXT); } if (!mCardIdentificationNumberEditText.getText().toString().isEmpty()) { validateIdentificationNumber(true); } } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); mIdentificationTypeSpinner.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (mCurrentEditingEditText.equals(CARD_SECURITYCODE_INPUT)) { return false; } checkTransitionCardToId(); mCardIdentificationNumberEditText.requestFocus(); return false; } }); mCardIdentificationNumberEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { validateCurrentEditText(); return true; } return false; } }); mCardIdentificationNumberEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); if (action == MotionEvent.ACTION_DOWN) { openKeyboard(mCardIdentificationNumberEditText); } return true; } }); mCardIdentificationNumberEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { mFrontFragment.setFontColor(); if (hasFocus) { MPTracker.getInstance().trackScreen("IDENTIFICATION_NUMBER", 2, mPublicKey, BuildConfig.VERSION_NAME, getActivity()); enableBackInputButton(); openKeyboard(mCardIdentificationNumberEditText); checkTransitionCardToId(); mCurrentEditingEditText = CARD_IDENTIFICATION_INPUT; } } }); } public void setSecurityCodeTextWatcher() { mCardSecurityCodeEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (showingBack() && mBackFragment != null) { mBackFragment.onSecurityTextChanged(s); } else if (mFrontFragment != null) { mFrontFragment.onSecurityTextChanged(s); } if (s.length() == mCardSecurityCodeLength) { mSecurityCode = s.toString(); } } @Override public void afterTextChanged(Editable s) { checkChangeErrorView(); mCardSecurityCodeEditText.toggleLineColorOnError(false); if (showingBack() && mBackFragment != null) { mBackFragment.afterSecurityTextChanged(s); } else if (mFrontFragment != null) { mFrontFragment.afterSecurityTextChanged(s); } } }); } public void setIdentificationNumberTextWatcher() { mCardIdentificationNumberEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (showingIdentification() && mCardIdentificationFragment != null) { mCardIdentificationFragment.onNumberTextChanged(s, start, before, count); } if (mSelectedIdentificationType != null && mSelectedIdentificationType.getMaxLength() != null) { if (s.length() == mSelectedIdentificationType.getMaxLength()) { mIdentification.setNumber(s.toString()); validateIdentificationNumber(false); } } } @Override public void afterTextChanged(Editable s) { checkChangeErrorView(); mCardIdentificationNumberEditText.toggleLineColorOnError(false); if (showingIdentification() && mCardIdentificationFragment != null) { mCardIdentificationFragment.afterNumberTextChanged(s); } } }); } public void setCardholderNameTextWatcher() { mCardHolderNameEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { checkChangeErrorView(); mCardHolderNameEditText.toggleLineColorOnError(false); } }); } public void setExpiryDateTextWatcher() { mCardExpiryDateEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() == 2 && before == 0) { mCardExpiryDateEditText.append("/"); } if (s.length() == 2 && before == 1) { mCardExpiryDateEditText.getText().delete(s.length() - 1, s.length()); } } @Override public void afterTextChanged(Editable s) { checkChangeErrorView(); mCardExpiryDateEditText.toggleLineColorOnError(false); } }); } @Override public boolean isSecurityCodeRequired() { return mIsSecurityCodeRequired; } public void setSecurityCodeRequired(boolean required) { this.mIsSecurityCodeRequired = required; } public void setSecurityCodeLength(int length) { this.mCardSecurityCodeLength = length; } public void setSecurityCodeLocation(String location) { this.mSecurityCodeLocation = location; } public void setSecurityCodeRestrictions(boolean isRequired, SecurityCode securityCode) { setSecurityCodeRequired(isRequired); if (securityCode == null) { setSecurityCodeLocation(null); setSecurityCodeLength(CARD_DEFAULT_SECURITY_CODE_LENGTH); return; } setSecurityCodeLocation(securityCode.getCardLocation()); setSecurityCodeLength(securityCode.getLength()); } private void createToken() { LayoutUtil.hideKeyboard(this); mInputContainer.setVisibility(View.GONE); mProgressBar.setVisibility(View.VISIBLE); mBackButton.setVisibility(View.GONE); mNextButton.setVisibility(View.GONE); mMercadoPago.createToken(mCardToken, new Callback<Token>() { @Override public void success(Token token) { if (isActivityActive()) { mToken = token; checkStartIssuersActivity(); } } @Override public void failure(ApiException apiException) { if (isActivityActive()) { setFailureRecovery(new FailureRecovery() { @Override public void recover() { createToken(); } }); ApiUtil.showApiExceptionError(getActivity(), apiException); } } }); } private boolean validateCardNumber(boolean requestFocus) { mCardToken.setCardNumber(getCardNumber()); try { if (mCurrentPaymentMethod == null) { if (getCardNumber() == null || getCardNumber().length() < MercadoPago.BIN_LENGTH) { throw new RuntimeException(getString(R.string.mpsdk_invalid_card_number_incomplete)); } else if (getCardNumber().length() == MercadoPago.BIN_LENGTH) { throw new RuntimeException(getString(R.string.mpsdk_invalid_payment_method)); } else { throw new RuntimeException(getString(R.string.mpsdk_invalid_payment_method)); } } mCardToken.validateCardNumber(this, mCurrentPaymentMethod); clearErrorView(); return true; } catch (Exception e) { setErrorView(e.getMessage()); if (requestFocus) { mCardNumberEditText.toggleLineColorOnError(true); mCardNumberEditText.requestFocus(); } return false; } } private boolean validateCardName(boolean requestFocus) { Cardholder cardHolder = new Cardholder(); cardHolder.setName(mCardHolderName); cardHolder.setIdentification(mIdentification); mCardToken.setCardholder(cardHolder); if (mCardToken.validateCardholderName()) { clearErrorView(); return true; } else { setErrorView(getString(R.string.mpsdk_invalid_empty_name)); if (requestFocus) { mCardHolderNameEditText.toggleLineColorOnError(true); mCardHolderNameEditText.requestFocus(); } return false; } } private boolean validateExpiryDate(boolean requestFocus) { Integer month = (mExpiryMonth == null ? null : Integer.valueOf(mExpiryMonth)); Integer year = (mExpiryYear == null ? null : Integer.valueOf(mExpiryYear)); mCardToken.setExpirationMonth(month); mCardToken.setExpirationYear(year); if (mCardToken.validateExpiryDate()) { clearErrorView(); return true; } else { setErrorView(getString(R.string.mpsdk_invalid_expiry_date)); if (requestFocus) { mCardExpiryDateEditText.toggleLineColorOnError(true); mCardExpiryDateEditText.requestFocus(); } return false; } } public boolean validateSecurityCode(boolean requestFocus) { mCardToken.setSecurityCode(mSecurityCode); try { mCardToken.validateSecurityCode(this, mCurrentPaymentMethod); clearErrorView(); return true; } catch (Exception e) { setCardSecurityCodeErrorView(e.getMessage(), requestFocus); return false; } } public boolean validateIdentificationNumber(boolean requestFocus) { mIdentification.setNumber(getCardIdentificationNumber()); mCardToken.getCardholder().setIdentification(mIdentification); boolean ans = mCardToken.validateIdentificationNumber(mSelectedIdentificationType); if (ans) { clearErrorView(); mCardIdentificationNumberEditText.toggleLineColorOnError(false); } else { setCardIdentificationErrorView(getString(R.string.mpsdk_invalid_identification_number), requestFocus); } return ans; } public void checkChangeErrorView() { if (mErrorState.equals(ERROR_STATE)) { clearErrorView(); } } public void setErrorView(String message) { mButtonContainer.setVisibility(View.GONE); mErrorContainer.setVisibility(View.VISIBLE); mErrorTextView.setText(message); mErrorState = CardInterface.ERROR_STATE; } public void clearErrorView() { mButtonContainer.setVisibility(View.VISIBLE); mErrorContainer.setVisibility(View.GONE); mErrorTextView.setText(""); mErrorState = CardInterface.NORMAL_STATE; } public void checkStartIssuersActivity() { mMercadoPago.getIssuers(mCurrentPaymentMethod.getId(), mPaymentMethodGuessingController.getSavedBin(), new Callback<List<Issuer>>() { @Override public void success(List<Issuer> issuers) { if (isActivityActive()) { if (issuers.isEmpty()) { ErrorUtil.startErrorActivity(getActivity(), getString(R.string.mpsdk_standard_error_message), "issuers call is empty at GuessingCardActivity", false); } else if (issuers.size() == 1) { mSelectedIssuer = issuers.get(0); mIssuerFound = true; finishWithResult(); } else { startIssuersActivity(issuers); } } } @Override public void failure(ApiException apiException) { if (isActivityActive()) { setFailureRecovery(new FailureRecovery() { @Override public void recover() { checkStartIssuersActivity(); } }); ApiUtil.showApiExceptionError(getActivity(), apiException); } } }); } private void setIssuerDefaultAnimation() { overridePendingTransition(R.anim.mpsdk_slide_right_to_left_in, R.anim.mpsdk_slide_right_to_left_out); } private void setIssuerSelectedAnimation() { overridePendingTransition(R.anim.mpsdk_hold, R.anim.mpsdk_hold); } public void startIssuersActivity(final List<Issuer> issuers) { new MercadoPago.StartActivityBuilder() .setActivity(getActivity()) .setPublicKey(mPublicKey) .setPaymentMethod(mCurrentPaymentMethod) .setToken(mToken) .setIssuers(issuers) .setDecorationPreference(mDecorationPreference) .startIssuersActivity(); overridePendingTransition(R.anim.mpsdk_slide_right_to_left_in, R.anim.mpsdk_slide_right_to_left_out); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == MercadoPago.ISSUERS_REQUEST_CODE) { if (resultCode == RESULT_OK) { Bundle bundle = data.getExtras(); mSelectedIssuer = JsonUtil.getInstance().fromJson(bundle.getString("issuer"), Issuer.class); checkFlipCardToFront(false); mIssuerFound = false; finishWithResult(); } else if (resultCode == RESULT_CANCELED) { finish(); } } else if (requestCode == ErrorUtil.ERROR_REQUEST_CODE) { if (resultCode == RESULT_OK) { recoverFromFailure(); } else { setResult(resultCode, data); finish(); } } } private void finishWithResult() { Intent returnIntent = new Intent(); returnIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(mCurrentPaymentMethod)); returnIntent.putExtra("token", JsonUtil.getInstance().toJson(mToken)); returnIntent.putExtra("issuer", JsonUtil.getInstance().toJson(mSelectedIssuer)); setResult(RESULT_OK, returnIntent); finish(); if (mIssuerFound) { setIssuerDefaultAnimation(); } else { setIssuerSelectedAnimation(); } } private static class CardNumberTextWatcher implements TextWatcher { private PaymentMethodGuessingController mController; private PaymentMethodSelectionCallback mCallback; private String mBin; public CardNumberTextWatcher(PaymentMethodGuessingController controller, PaymentMethodSelectionCallback callback) { this.mController = controller; this.mCallback = callback; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (mController == null) return; String number = s.toString().replaceAll("\\s", ""); if (number.length() == MercadoPago.BIN_LENGTH - 1) { mCallback.onPaymentMethodCleared(); } else if (number.length() >= MercadoPago.BIN_LENGTH) { mBin = number.subSequence(0, MercadoPago.BIN_LENGTH).toString(); List<PaymentMethod> list = mController.guessPaymentMethodsByBin(mBin); mCallback.onPaymentMethodListSet(list); } } } }
added enter key listener in card form
sdk/src/main/java/com/mercadopago/GuessingCardActivity.java
added enter key listener in card form
Java
mit
159a6992f82f53912d4e4a206a952f0bf27ef716
0
RudiaMoon/objectify-appengine,asolfre/objectify-appengine,naveen514/objectify-appengine,google-code-export/objectify-appengine,qickrooms/objectify-appengine,objectify/objectify,zenmeso/objectify-appengine
/* */ package com.googlecode.objectify.test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.testng.annotations.Test; import com.google.appengine.api.datastore.ReadPolicy.Consistency; import com.googlecode.objectify.Key; import com.googlecode.objectify.test.entity.Employee; import com.googlecode.objectify.test.entity.NamedTrivial; import com.googlecode.objectify.test.entity.Trivial; import com.googlecode.objectify.test.util.TestBase; import com.googlecode.objectify.test.util.TestObjectify; /** * Tests of basic entity manipulation. * * @author Jeff Schnitzer <[email protected]> */ public class BasicTests extends TestBase { /** */ @SuppressWarnings("unused") private static Logger log = Logger.getLogger(BasicTests.class.getName()); /** */ @Test public void testGenerateId() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin(); // Note that 5 is not the id, it's part of the payload Trivial triv = new Trivial("foo", 5); Key<Trivial> k = ofy.save().entity(triv).now(); assert k.getKind().equals(triv.getClass().getSimpleName()); assert k.getId() == triv.getId(); Key<Trivial> created = Key.create(Trivial.class, k.getId()); assert k.equals(created); Trivial fetched = ofy.load().key(k).get(); assert fetched.getId().equals(k.getId()); assert fetched.getSomeNumber() == triv.getSomeNumber(); assert fetched.getSomeString().equals(triv.getSomeString()); } /** */ @Test public void testOverwriteId() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin(); Trivial triv = new Trivial("foo", 5); Key<Trivial> k = ofy.save().entity(triv).now(); Trivial triv2 = new Trivial(k.getId(), "bar", 6); Key<Trivial> k2 = ofy.save().entity(triv2).now(); assert k2.equals(k); Trivial fetched = ofy.load().key(k).get(); assert fetched.getId() == k.getId(); assert fetched.getSomeNumber() == triv2.getSomeNumber(); assert fetched.getSomeString().equals(triv2.getSomeString()); } /** */ @Test public void testNames() throws Exception { fact.register(NamedTrivial.class); TestObjectify ofy = this.fact.begin(); NamedTrivial triv = new NamedTrivial("first", "foo", 5); Key<NamedTrivial> k = ofy.save().entity(triv).now(); assert k.getName().equals("first"); Key<NamedTrivial> createdKey = Key.create(NamedTrivial.class, "first"); assert k.equals(createdKey); NamedTrivial fetched = ofy.load().key(k).get(); assert fetched.getName().equals(k.getName()); assert fetched.getSomeNumber() == triv.getSomeNumber(); assert fetched.getSomeString().equals(triv.getSomeString()); } /** */ @Test public void testBatchOperations() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin(); Trivial triv1 = new Trivial("foo", 5); Trivial triv2 = new Trivial("foo2", 6); List<Trivial> objs = new ArrayList<Trivial>(); objs.add(triv1); objs.add(triv2); Map<Key<Trivial>, Trivial> map = ofy.save().entities(objs).now(); List<Key<Trivial>> keys = new ArrayList<Key<Trivial>>(map.keySet()); // Verify the put keys assert keys.size() == objs.size(); for (int i=0; i<objs.size(); i++) { assert keys.get(i).getId() == objs.get(i).getId(); } // Now fetch and verify the data Map<Key<Trivial>, Trivial> fetched = ofy.load().keys(keys); assert fetched.size() == keys.size(); for (Trivial triv: objs) { Trivial fetchedTriv = fetched.get(Key.create(triv)); assert triv.getSomeNumber() == fetchedTriv.getSomeNumber(); assert triv.getSomeString().equals(fetchedTriv.getSomeString()); } } /** */ @Test public void testManyToOne() throws Exception { fact.register(Employee.class); TestObjectify ofy = this.fact.begin(); Employee fred = new Employee("fred"); ofy.save().entity(fred).now(); Key<Employee> fredKey = Key.create(fred); List<Employee> employees = new ArrayList<Employee>(100); for (int i = 0; i < 100; i++) { Employee emp = new Employee("foo" + i, fredKey); employees.add(emp); } ofy.save().entities(employees).now(); assert employees.size() == 100; int count = 0; for (Employee emp: ofy.load().type(Employee.class).filter("manager", fred)) { emp.getName(); // Just to make eclipse happy count++; } assert count == 100; } /** */ @Test public void testConsistencySetting() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin().consistency(Consistency.EVENTUAL); Trivial triv = new Trivial("foo", 5); ofy.save().entity(triv).now(); } /** */ @Test public void testKeyToString() throws Exception { Key<Trivial> trivKey = Key.create(Trivial.class, 123); String stringified = trivKey.getString(); Key<Trivial> andBack = Key.create(stringified); assert trivKey.equals(andBack); } /** */ @Test public void testPutNothing() throws Exception { TestObjectify ofy = this.fact.begin(); ofy.save().entities(Collections.emptyList()).now(); } /** */ @Test public void testChunking() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin(); List<Trivial> trivs = new ArrayList<Trivial>(100); for (int i = 0; i < 100; i++) { Trivial triv = new Trivial(1000L + i, "foo" + i, i); trivs.add(triv); } ofy.save().entities(trivs).now(); assert trivs.size() == 100; int count = 0; for (Trivial triv: ofy.load().type(Trivial.class).chunk(2)) { assert triv.getSomeNumber() == count; count++; } assert count == 100; } /** */ @Test public void deleteBatch() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin(); Trivial triv1 = new Trivial("foo5", 5); Trivial triv2 = new Trivial("foo6", 6); ofy.save().entities(triv1, triv2).now(); assert ofy.load().entities(triv1, triv2).size() == 2; ofy.delete().entities(triv1, triv2).now(); Map<Key<Trivial>, Trivial> result = ofy.load().entities(triv1, triv2); System.out.println("Result is " + result); assert result.size() == 0; } /** */ @Test public void simpleFetchById() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin(); Trivial triv1 = new Trivial("foo5", 5); ofy.save().entity(triv1).now(); ofy.clear(); Trivial fetched = ofy.load().type(Trivial.class).id(triv1.getId()).get(); assert fetched.getSomeString().equals(triv1.getSomeString()); } }
src/test/java/com/googlecode/objectify/test/BasicTests.java
/* */ package com.googlecode.objectify.test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.testng.annotations.Test; import com.google.appengine.api.datastore.ReadPolicy.Consistency; import com.googlecode.objectify.Key; import com.googlecode.objectify.test.entity.Employee; import com.googlecode.objectify.test.entity.NamedTrivial; import com.googlecode.objectify.test.entity.Trivial; import com.googlecode.objectify.test.util.TestBase; import com.googlecode.objectify.test.util.TestObjectify; /** * Tests of basic entity manipulation. * * @author Jeff Schnitzer <[email protected]> */ public class BasicTests extends TestBase { /** */ @SuppressWarnings("unused") private static Logger log = Logger.getLogger(BasicTests.class.getName()); /** */ @Test public void testGenerateId() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin(); // Note that 5 is not the id, it's part of the payload Trivial triv = new Trivial("foo", 5); Key<Trivial> k = ofy.save().entity(triv).now(); assert k.getKind().equals(triv.getClass().getSimpleName()); assert k.getId() == triv.getId(); Key<Trivial> created = Key.create(Trivial.class, k.getId()); assert k.equals(created); Trivial fetched = ofy.load().key(k).get(); assert fetched.getId().equals(k.getId()); assert fetched.getSomeNumber() == triv.getSomeNumber(); assert fetched.getSomeString().equals(triv.getSomeString()); } /** */ @Test public void testOverwriteId() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin(); Trivial triv = new Trivial("foo", 5); Key<Trivial> k = ofy.save().entity(triv).now(); Trivial triv2 = new Trivial(k.getId(), "bar", 6); Key<Trivial> k2 = ofy.save().entity(triv2).now(); assert k2.equals(k); Trivial fetched = ofy.load().key(k).get(); assert fetched.getId() == k.getId(); assert fetched.getSomeNumber() == triv2.getSomeNumber(); assert fetched.getSomeString().equals(triv2.getSomeString()); } /** */ @Test public void testNames() throws Exception { fact.register(NamedTrivial.class); TestObjectify ofy = this.fact.begin(); NamedTrivial triv = new NamedTrivial("first", "foo", 5); Key<NamedTrivial> k = ofy.save().entity(triv).now(); assert k.getName().equals("first"); Key<NamedTrivial> createdKey = Key.create(NamedTrivial.class, "first"); assert k.equals(createdKey); NamedTrivial fetched = ofy.load().key(k).get(); assert fetched.getName().equals(k.getName()); assert fetched.getSomeNumber() == triv.getSomeNumber(); assert fetched.getSomeString().equals(triv.getSomeString()); } /** */ @Test public void testBatchOperations() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin(); Trivial triv1 = new Trivial("foo", 5); Trivial triv2 = new Trivial("foo2", 6); List<Trivial> objs = new ArrayList<Trivial>(); objs.add(triv1); objs.add(triv2); Map<Key<Trivial>, Trivial> map = ofy.save().entities(objs).now(); List<Key<Trivial>> keys = new ArrayList<Key<Trivial>>(map.keySet()); // Verify the put keys assert keys.size() == objs.size(); for (int i=0; i<objs.size(); i++) { assert keys.get(i).getId() == objs.get(i).getId(); } // Now fetch and verify the data Map<Key<Trivial>, Trivial> fetched = ofy.load().keys(keys); assert fetched.size() == keys.size(); for (Trivial triv: objs) { Trivial fetchedTriv = fetched.get(Key.create(triv)); assert triv.getSomeNumber() == fetchedTriv.getSomeNumber(); assert triv.getSomeString().equals(fetchedTriv.getSomeString()); } } /** */ @Test public void testManyToOne() throws Exception { fact.register(Employee.class); TestObjectify ofy = this.fact.begin(); Employee fred = new Employee("fred"); ofy.save().entity(fred).now(); Key<Employee> fredKey = Key.create(fred); List<Employee> employees = new ArrayList<Employee>(100); for (int i = 0; i < 100; i++) { Employee emp = new Employee("foo" + i, fredKey); employees.add(emp); } ofy.save().entities(employees).now(); assert employees.size() == 100; int count = 0; for (Employee emp: ofy.load().type(Employee.class).filter("manager", fred)) { emp.getName(); // Just to make eclipse happy count++; } assert count == 100; } /** */ @Test public void testConsistencySetting() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin().consistency(Consistency.EVENTUAL); Trivial triv = new Trivial("foo", 5); ofy.save().entity(triv).now(); } /** */ @Test public void testKeyToString() throws Exception { Key<Trivial> trivKey = Key.create(Trivial.class, 123); String stringified = trivKey.getString(); Key<Trivial> andBack = Key.create(stringified); assert trivKey.equals(andBack); } /** */ @Test public void testPutNothing() throws Exception { TestObjectify ofy = this.fact.begin(); ofy.save().entities(Collections.emptyList()).now(); } /** */ @Test public void testChunking() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin(); List<Trivial> trivs = new ArrayList<Trivial>(100); for (int i = 0; i < 100; i++) { Trivial triv = new Trivial(1000L + i, "foo" + i, i); trivs.add(triv); } ofy.save().entities(trivs).now(); assert trivs.size() == 100; int count = 0; for (Trivial triv: ofy.load().type(Trivial.class).chunk(2)) { assert triv.getSomeNumber() == count; count++; } assert count == 100; } /** */ @Test public void deleteBatch() throws Exception { fact.register(Trivial.class); TestObjectify ofy = this.fact.begin(); Trivial triv1 = new Trivial("foo5", 5); Trivial triv2 = new Trivial("foo6", 6); ofy.save().entities(triv1, triv2).now(); assert ofy.load().entities(triv1, triv2).size() == 2; ofy.delete().entities(triv1, triv2).now(); Map<Key<Trivial>, Trivial> result = ofy.load().entities(triv1, triv2); System.out.println("Result is " + result); assert result.size() == 0; } }
Added simple fetch-by-id test
src/test/java/com/googlecode/objectify/test/BasicTests.java
Added simple fetch-by-id test
Java
mit
6823c2f5c9ab828cfef69daecf8a81977affe514
0
nunull/QuickStarter,nunull/QuickStarter,nunull/QuickStarter,nunull/QuickStarter
package de.dqi11.quickStarter.controller; import java.awt.HeadlessException; import java.net.ConnectException; import java.util.LinkedList; import java.util.Observable; import java.util.Observer; import de.dqi11.quickStarter.gui.MainWindow; import de.dqi11.quickStarter.gui.Taskbar; import de.dqi11.quickStarter.modules.ErrorCoreModule; import de.dqi11.quickStarter.modules.ModuleAction; import de.dqi11.quickStarter.modules.Module; import de.dqi11.quickStarter.os.MacOS; import de.dqi11.quickStarter.os.OS; import de.dqi11.quickStarter.os.WinOS; /** * The main-controller. Brings everything together. */ public class MainController implements Observer { private boolean networkError = false; private LinkedList<Module> modules; private LinkedList<ModuleAction> moduleActions; private OS os; private MainWindow mainWindow; @SuppressWarnings("unused") private Taskbar taskbar; private PersitencyController persitencyController; /** * Constructor. */ public MainController() { this.modules = new LinkedList<Module>(); this.moduleActions = new LinkedList<ModuleAction>(); this.persitencyController = new PersitencyController(this); initModules(); initOS(); initGUI(); /* * Just a small test. */ if(mainWindow != null) { mainWindow.toggleApplication(); } } /** * Initializes the modules. */ private void initModules() { modules = persitencyController.getModules(); // CoreModules have to be added last, since otherwise they won't receive // errors, which were produced by other Modules. modules.add(new ErrorCoreModule(this)); } /** * Initializes the wrappers for operating-systems. */ private void initOS() { String osName = System.getProperty("os.name"); try { if( osName.contains("Windows") ) os = new WinOS(); else if( osName.contains("Mac") ) os = new MacOS(); } catch(Exception e) { } if(os != null) { os.addObserver(this); } } /** * Initializes the GUI. */ private void initGUI() { try { mainWindow = new MainWindow(); mainWindow.addObserver(this); mainWindow.init(); // TODO // SwingUtilities.invokeLater(new Runnable() { // // @Override // public void run() { // mainWindow.init(); // } // }); taskbar = new Taskbar(this); } catch(HeadlessException e) { mainWindow = null; } } /** * Gets possible actions for the given search-term. * * @param search The specific search-term. * @return a list of Advices (possible actions). */ public LinkedList<ModuleAction> invoke(Search search) { moduleActions = new LinkedList<ModuleAction>(); if(search != null) { LinkedList<Module> activeModules = new LinkedList<>(); networkError = false; for(Module m : modules) { try { ModuleAction moduleAction = m.getModuleAction(search); if(moduleAction != null) { activeModules.add(m); moduleActions.add(moduleAction); } } catch(ConnectException e) { networkError = true; } } for(Module m : activeModules) { LinkedList<Module> exceptions = m.getExceptions(); for(Module exception : exceptions) { if(activeModules.contains(exception)) { for(ModuleAction moduleAction : moduleActions) { if(moduleAction.getKey().equals(m.getKey())) { moduleActions.remove(moduleAction); break; } } } } } } return moduleActions; } /** * Updates the ModuleAction from the specific module. * * @param modulAction The new ModuleAction. * @return true if replacement was successful, false otherwise. */ public boolean updateModule(ModuleAction modulAction) { try { int index = moduleActions.lastIndexOf(modulAction); moduleActions.add(index, modulAction); moduleActions.remove(index+1); if(mainWindow != null) { mainWindow.updateModuleActions(); } return true; } catch(IndexOutOfBoundsException e) { return false; } } /** * Shuts global (OS-wide) shortcut-handlers down. */ public void shutdown() { os.shutdown(); } /** * Quits the application. */ public void quit() { shutdown(); // TODO bad style System.exit(0); } /** * Will be called from * 1. OS-classes, when the visibility of the application should be toggled, * 2. MainWindow, when ModuleActions should be updated. */ @Override public void update(Observable o, Object arg) { if(mainWindow != null) { if(o instanceof OS) { mainWindow.toggleApplication(); } else if(o instanceof MainWindow) { mainWindow.setModuleActions( invoke( new Search( mainWindow.getSearchString())));; } } } /** * Getter. * * @return true, if an networkError occurred. */ public boolean isNetworkError() { return networkError; } public OS getOS() { return os; } }
src/de/dqi11/quickStarter/controller/MainController.java
package de.dqi11.quickStarter.controller; import java.awt.HeadlessException; import java.net.ConnectException; import java.util.LinkedList; import java.util.Observable; import java.util.Observer; import de.dqi11.quickStarter.gui.MainWindow; import de.dqi11.quickStarter.gui.Taskbar; import de.dqi11.quickStarter.modules.ErrorCoreModule; import de.dqi11.quickStarter.modules.ModuleAction; import de.dqi11.quickStarter.modules.Module; import de.dqi11.quickStarter.os.MacOS; import de.dqi11.quickStarter.os.OS; import de.dqi11.quickStarter.os.WinOS; /** * The main-controller. Brings everything together. */ public class MainController implements Observer { private boolean networkError = false; private LinkedList<Module> modules; private LinkedList<ModuleAction> moduleActions; private OS os; private MainWindow mainWindow; @SuppressWarnings("unused") private Taskbar taskbar; private PersitencyController persitencyController; /** * Constructor. */ public MainController() { this.modules = new LinkedList<Module>(); this.moduleActions = new LinkedList<ModuleAction>(); this.persitencyController = new PersitencyController(this); initModules(); initOS(); initGUI(); /* * Just a small test. */ if(mainWindow != null) { mainWindow.toggleApplication(); } } /** * Initializes the modules. */ private void initModules() { modules = persitencyController.getModules(); // CoreModules have to be added last, since otherwise they won't receive // errors, which were produced by other Modules. modules.add(new ErrorCoreModule(this)); } /** * Initializes the wrappers for operating-systems. */ private void initOS() { String osName = System.getProperty("os.name"); try { if( osName.contains("Windows") ) os = new WinOS(); else if( osName.contains("Mac") ) os = new MacOS(); } catch(Exception e) { } if(os != null) { os.addObserver(this); } } /** * Initializes the GUI. */ private void initGUI() { try { mainWindow = new MainWindow(); mainWindow.addObserver(this); mainWindow.init(); // TODO // SwingUtilities.invokeLater(new Runnable() { // // @Override // public void run() { // mainWindow.init(); // } // }); taskbar = new Taskbar(this); } catch(HeadlessException e) { } } /** * Gets possible actions for the given search-term. * * @param search The specific search-term. * @return a list of Advices (possible actions). */ public LinkedList<ModuleAction> invoke(Search search) { moduleActions = new LinkedList<ModuleAction>(); if(search != null) { LinkedList<Module> activeModules = new LinkedList<>(); networkError = false; for(Module m : modules) { try { ModuleAction moduleAction = m.getModuleAction(search); if(moduleAction != null) { activeModules.add(m); moduleActions.add(moduleAction); } } catch(ConnectException e) { networkError = true; } } for(Module m : activeModules) { LinkedList<Module> exceptions = m.getExceptions(); for(Module exception : exceptions) { if(activeModules.contains(exception)) { for(ModuleAction moduleAction : moduleActions) { if(moduleAction.getKey().equals(m.getKey())) { moduleActions.remove(moduleAction); break; } } } } } } return moduleActions; } /** * Updates the ModuleAction from the specific module. * * @param modulAction The new ModuleAction. * @return true if replacement was successful, false otherwise. */ public boolean updateModule(ModuleAction modulAction) { try { int index = moduleActions.lastIndexOf(modulAction); moduleActions.add(index, modulAction); moduleActions.remove(index+1); if(mainWindow != null) { mainWindow.updateModuleActions(); } return true; } catch(IndexOutOfBoundsException e) { return false; } } /** * Shuts global (OS-wide) shortcut-handlers down. */ public void shutdown() { os.shutdown(); } /** * Quits the application. */ public void quit() { shutdown(); // TODO bad style System.exit(0); } /** * Will be called from * 1. OS-classes, when the visibility of the application should be toggled, * 2. MainWindow, when ModuleActions should be updated. */ @Override public void update(Observable o, Object arg) { if(mainWindow != null) { if(o instanceof OS) { mainWindow.toggleApplication(); } else if(o instanceof MainWindow) { mainWindow.setModuleActions( invoke( new Search( mainWindow.getSearchString())));; } } } /** * Getter. * * @return true, if an networkError occurred. */ public boolean isNetworkError() { return networkError; } public OS getOS() { return os; } }
Updates MainController
src/de/dqi11/quickStarter/controller/MainController.java
Updates MainController
Java
mpl-2.0
7f9ca0af2a388c5bb1ddb268b38b12c564f53046
0
GuadaG/TP-java
package uiDesktop; import java.awt.EventQueue; import negocio.*; import entidades.*; import javax.swing.AbstractButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JEditorPane; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.logging.Level; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; import javax.swing.JRadioButton; import javax.swing.JTextPane; import org.omg.CORBA.portable.ApplicationException; import java.awt.Color; import java.awt.SystemColor; import java.awt.Font; import javax.swing.SwingConstants; import javax.swing.JLayeredPane; public class ABMCPersonaje { private JFrame frame; private JTextField cod; private JTextField nom; private JTextField energia; private JTextField vida; private JTextField evasion; private JTextField def; private JTextField ptosTot; private CtrlABMPersonaje ctrl; private JTextField ptosDisp; public int creo=0; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ABMCPersonaje window = new ABMCPersonaje(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public ABMCPersonaje() { initialize(); ctrl = new CtrlABMPersonaje(); }; /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 513, 386); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); cod = new JTextField(); cod.setBounds(88, 97, 40, 20); frame.getContentPane().add(cod); cod.setColumns(10); JLabel lblCodigo = new JLabel("Codigo: "); lblCodigo.setBounds(34, 100, 55, 14); frame.getContentPane().add(lblCodigo); JLabel lblNombre = new JLabel("Nombre: "); lblNombre.setBounds(172, 100, 55, 14); frame.getContentPane().add(lblNombre); nom = new JTextField(); nom.setBounds(237, 97, 145, 20); frame.getContentPane().add(nom); nom.setColumns(10); JLabel lblEnergia = new JLabel("Energia"); lblEnergia.setBounds(42, 160, 46, 14); frame.getContentPane().add(lblEnergia); JLabel lblDefensa = new JLabel("Defensa"); lblDefensa.setBounds(41, 185, 58, 14); frame.getContentPane().add(lblDefensa); JLabel lblVida = new JLabel("Vida"); lblVida.setBounds(42, 210, 46, 14); frame.getContentPane().add(lblVida); JLabel lblEvasion = new JLabel("Evasion"); lblEvasion.setBounds(42, 233, 46, 14); frame.getContentPane().add(lblEvasion); JLabel lblPuntosDisponibles = new JLabel("Puntos Disp"); lblPuntosDisponibles.setHorizontalAlignment(SwingConstants.CENTER); lblPuntosDisponibles.setBounds(10, 292, 75, 28); frame.getContentPane().add(lblPuntosDisponibles); energia = new JTextField(); energia.setBounds(94, 157, 34, 20); frame.getContentPane().add(energia); energia.setColumns(10); vida = new JTextField(); vida.setColumns(10); vida.setBounds(94, 207, 34, 20); frame.getContentPane().add(vida); evasion = new JTextField(); evasion.setColumns(10); evasion.setBounds(94, 230, 34, 20); frame.getContentPane().add(evasion); def = new JTextField(); def.setBounds(93, 182, 35, 20); frame.getContentPane().add(def); def.setColumns(10); ptosTot = new JTextField(); ptosTot.setBounds(94, 261, 34, 20); frame.getContentPane().add(ptosTot); ptosTot.setColumns(10); ptosDisp = new JTextField(); ptosDisp.setBounds(94, 298, 40, 20); frame.getContentPane().add(ptosDisp); ptosDisp.setColumns(10); JLabel lblPuntosTotales = new JLabel("Puntos Totales"); lblPuntosTotales.setBounds(10, 261, 104, 20); frame.getContentPane().add(lblPuntosTotales); JButton btnModificar = new JButton("Modificar"); btnModificar.setBounds(379, 151, 89, 23); frame.getContentPane().add(btnModificar); JButton btnBuscarPorNombre = new JButton("Buscar Por Nombre"); btnBuscarPorNombre.setBounds(185, 156, 161, 23); frame.getContentPane().add(btnBuscarPorNombre); JButton btnBorrar = new JButton("Borrar"); btnBorrar.setBounds(379, 206, 89, 23); frame.getContentPane().add(btnBorrar); JTextPane condDef = new JTextPane(); condDef.setFont(new Font("Tahoma", Font.BOLD, 11)); condDef.setBackground(SystemColor.control); condDef.setBounds(138, 179, 98, 20); frame.getContentPane().add(condDef); JTextPane condEv = new JTextPane(); condEv.setFont(new Font("Tahoma", Font.BOLD, 11)); condEv.setBackground(SystemColor.control); condEv.setBounds(138, 227, 98, 20); frame.getContentPane().add(condEv); JButton exit = new JButton("EXIT"); exit.setBounds(207, 297, 89, 23); frame.getContentPane().add(exit); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); JButton btnLimpiarCampos = new JButton("Limpiar Campos"); btnLimpiarCampos.setBounds(352, 258, 135, 23); frame.getContentPane().add(btnLimpiarCampos); btnLimpiarCampos.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { limpiarCampos(); } }); JButton btnBuscarPorCodigo = new JButton("Buscar Por Codigo"); btnBuscarPorCodigo.setBounds(185, 206, 161, 23); frame.getContentPane().add(btnBuscarPorCodigo); JButton btnCrear = new JButton("Crear"); btnCrear.setBounds(379, 176, 89, 23); frame.getContentPane().add(btnCrear); JRadioButton buscar = new JRadioButton("Buscar"); buscar.setBounds(335, 34, 109, 23); frame.getContentPane().add(buscar); JRadioButton newPers = new JRadioButton("Nuevo Personaje"); newPers.setBounds(84, 34, 123, 23); frame.getContentPane().add(newPers); newPers.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { if (newPers.isSelected()==true) { btnCrear.setVisible(true); nom.setVisible(true); evasion.setVisible(true); def.setVisible(true); energia.setVisible(true); vida.setVisible(true); ptosTot.setVisible(true); ptosDisp.setVisible(true); lblEvasion.setVisible(true); lblVida.setVisible(true); lblDefensa.setVisible(true); lblEnergia.setVisible(true); lblNombre.setVisible(true); lblPuntosTotales.setVisible(true); lblPuntosDisponibles.setVisible(true); ptosDisp.setText("200"); ptosTot.setText("0"); energia.setText("0"); def.setText("0"); vida.setText("0"); evasion.setText("0"); nom.setText("Ingrese nombre"); condEv.setText("Max 80 puntos"); condDef.setText("Max 20 puntos"); btnLimpiarCampos.setVisible(true); buscar.setVisible(false); } else{ buscar.setVisible(true); nom.setVisible(false); evasion.setVisible(false); def.setVisible(false); energia.setVisible(false); vida.setVisible(false); ptosTot.setVisible(false); ptosDisp.setVisible(false); lblEvasion.setVisible(false); lblVida.setVisible(false); lblDefensa.setVisible(false); lblEnergia.setVisible(false); lblNombre.setVisible(false); lblPuntosTotales.setVisible(false); lblPuntosDisponibles.setVisible(false); condEv.setText(""); condDef.setText(""); btnCrear.setVisible(false); btnLimpiarCampos.setVisible(false); }; } }); buscar.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { if (buscar.isSelected()==true) { btnBuscarPorNombre.setVisible(true); btnBuscarPorCodigo.setVisible(true); newPers.setVisible(false); cod.setVisible(true); nom.setVisible(true); evasion.setVisible(true); def.setVisible(true); energia.setVisible(true); vida.setVisible(true); ptosTot.setVisible(true); ptosDisp.setVisible(true); lblCodigo.setVisible(true); lblEvasion.setVisible(true); lblVida.setVisible(true); lblDefensa.setVisible(true); lblEnergia.setVisible(true); lblNombre.setVisible(true); lblPuntosTotales.setVisible(true); lblPuntosDisponibles.setVisible(true); } else { btnBuscarPorNombre.setVisible(false); btnBuscarPorCodigo.setVisible(false); newPers.setVisible(true); btnModificar.setVisible(false); btnLimpiarCampos.setVisible(false); btnBorrar.setVisible(false); cod.setVisible(false); nom.setVisible(false); evasion.setVisible(false); def.setVisible(false); energia.setVisible(false); vida.setVisible(false); ptosTot.setVisible(false); ptosDisp.setVisible(false); lblCodigo.setVisible(false); lblEvasion.setVisible(false); lblVida.setVisible(false); lblDefensa.setVisible(false); lblEnergia.setVisible(false); lblNombre.setVisible(false); lblPuntosTotales.setVisible(false); lblPuntosDisponibles.setVisible(false); } } }); btnBuscarPorNombre.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { buscarPorNombre(); if(buscarPorNombre()) { btnModificar.setVisible(true); btnBorrar.setVisible(true); btnLimpiarCampos.setVisible(true); } else { btnModificar.setVisible(false); btnBorrar.setVisible(false); buscar.setSelected(false); btnBuscarPorNombre.setVisible(false); btnBuscarPorCodigo.setVisible(false); JOptionPane.showMessageDialog(null, "Ah avido un error"); cod.setVisible(false); nom.setVisible(false); evasion.setVisible(false); def.setVisible(false); energia.setVisible(false); vida.setVisible(false); ptosTot.setVisible(false); ptosDisp.setVisible(false); lblCodigo.setVisible(false); lblEvasion.setVisible(false); lblVida.setVisible(false); lblDefensa.setVisible(false); lblEnergia.setVisible(false); lblNombre.setVisible(false); lblPuntosTotales.setVisible(false); lblPuntosDisponibles.setVisible(false); } } }); btnBuscarPorCodigo.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { buscarPorCodigo(); if(buscarPorCodigo()) { btnModificar.setVisible(true); btnBorrar.setVisible(true); btnLimpiarCampos.setVisible(true); } else { btnModificar.setVisible(false); btnBorrar.setVisible(false); buscar.setSelected(false); btnBuscarPorNombre.setVisible(false); btnBuscarPorCodigo.setVisible(false); JOptionPane.showMessageDialog(null, "Ah avido un error"); cod.setVisible(false); nom.setVisible(false); evasion.setVisible(false); def.setVisible(false); energia.setVisible(false); vida.setVisible(false); ptosTot.setVisible(false); ptosDisp.setVisible(false); lblCodigo.setVisible(false); lblEvasion.setVisible(false); lblVida.setVisible(false); lblDefensa.setVisible(false); lblEnergia.setVisible(false); lblNombre.setVisible(false); lblPuntosTotales.setVisible(false); lblPuntosDisponibles.setVisible(false); } } }); btnCrear.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { creo=1; agregar(); btnCrear.setVisible(false); btnLimpiarCampos.setVisible(false); cod.setVisible(false); nom.setVisible(false); evasion.setVisible(false); def.setVisible(false); energia.setVisible(false); vida.setVisible(false); ptosTot.setVisible(false); ptosDisp.setVisible(false); lblCodigo.setVisible(false); lblEvasion.setVisible(false); lblVida.setVisible(false); lblDefensa.setVisible(false); lblEnergia.setVisible(false); lblNombre.setVisible(false); lblPuntosTotales.setVisible(false); lblPuntosDisponibles.setVisible(false); buscar.setVisible(true); newPers.setSelected(false); condEv.setText(""); condDef.setText(""); limpiarCampos(); creo=0; /*cod.setVisible(true); lblCodigo.setVisible(true); btnCrear.setVisible(false); btnBuscarPorCodigo.setVisible(true); btnBuscarPorNombre.setVisible(true); btnBorrar.setVisible(true); btnModificar.setVisible(true);*/ } }); btnModificar.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { modificar(); btnBuscarPorCodigo.setVisible(false); btnBuscarPorNombre.setVisible(false); btnModificar.setVisible(false); btnLimpiarCampos.setVisible(false); btnBorrar.setVisible(false); cod.setVisible(false); nom.setVisible(false); evasion.setVisible(false); def.setVisible(false); energia.setVisible(false); vida.setVisible(false); ptosTot.setVisible(false); ptosDisp.setVisible(false); lblCodigo.setVisible(false); lblEvasion.setVisible(false); lblVida.setVisible(false); lblDefensa.setVisible(false); lblEnergia.setVisible(false); lblNombre.setVisible(false); lblPuntosTotales.setVisible(false); lblPuntosDisponibles.setVisible(false); newPers.setVisible(true); buscar.setSelected(false); } }); btnBorrar.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { borrar(); btnBuscarPorCodigo.setVisible(false); btnBuscarPorNombre.setVisible(false); btnModificar.setVisible(false); btnLimpiarCampos.setVisible(false); btnBorrar.setVisible(false); cod.setVisible(false); nom.setVisible(false); evasion.setVisible(false); def.setVisible(false); energia.setVisible(false); vida.setVisible(false); ptosTot.setVisible(false); ptosDisp.setVisible(false); lblCodigo.setVisible(false); lblEvasion.setVisible(false); lblVida.setVisible(false); lblDefensa.setVisible(false); lblEnergia.setVisible(false); lblNombre.setVisible(false); lblPuntosTotales.setVisible(false); lblPuntosDisponibles.setVisible(false); newPers.setVisible(true); buscar.setSelected(false); } }); /*Hago que solo se puedan ver los botones de Buscar y Nuevo Personaje */ btnCrear.setVisible(false); btnBuscarPorCodigo.setVisible(false); btnBuscarPorNombre.setVisible(false); btnModificar.setVisible(false); btnLimpiarCampos.setVisible(false); btnBorrar.setVisible(false); cod.setVisible(false); nom.setVisible(false); evasion.setVisible(false); def.setVisible(false); energia.setVisible(false); vida.setVisible(false); ptosTot.setVisible(false); ptosDisp.setVisible(false); lblCodigo.setVisible(false); lblEvasion.setVisible(false); lblVida.setVisible(false); lblDefensa.setVisible(false); lblEnergia.setVisible(false); lblNombre.setVisible(false); lblPuntosTotales.setVisible(false); lblPuntosDisponibles.setVisible(false); } //Aca termina el INICIALIZE ///METODOS///////////////////// protected void agregar() { if(datosValidos(creo)){ //JOptionPane.showMessageDialog(null, "TODO OK"); Personaje p=MapearDeFormulario(); ctrl.add(p); //MapearAFormulario(p); } } protected boolean buscarPorNombre() { //creo=1; boolean ok=false; if(!nom.getText().matches("")) { Personaje p = ctrl.getPersonaje(nom.getText()); if(p!=null) { MapearAFormulario(p); ok=true; } else JOptionPane.showMessageDialog(null, "No se encontro el nombre del personaje"); } else { JOptionPane.showMessageDialog(null, "Ha habido un error amigoh\nVolve a ingresar un nombre"); limpiarCampos(); } return ok; } protected boolean buscarPorCodigo() { boolean ok=false; if(!cod.getText().matches("")) { Personaje p = ctrl.getPersonaje(Integer.parseInt(cod.getText())); if(p!=null) { MapearAFormulario(p); ok=true; } else JOptionPane.showMessageDialog(null, "No se encontro el codigo del personaje"); } else { JOptionPane.showMessageDialog(null, "Ha habido un error amigoh\nVolve a ingresar un codigo"); limpiarCampos(); } return ok; } protected void modificar() { if(cod.getText().matches("")) cod.setText("0"); if (datosValidos(creo)) { Personaje po = ctrl.getPersonaje(Integer.parseInt(cod.getText())); if(po!=null) MapearAFormulario(po); /* po tiene el personaje con su nombre antiguo, esto lo hago por si tambien decido cambiarle su nombre ademas de los atributos p va a tener el nuevo nombre (si es que lo cambie) y los atributos nuevos a update le doy el personaje modificado y el nombre del personaje original para que lo busque y modifique ese personaje*/ Personaje p=MapearDeFormulario(); ctrl.update(p, po.getNombre()); limpiarCampos();} /*if(p!=null) JOptionPane.showMessageDialog(null, "Nombre: "+p.getNombre()+" Energia:");*/ } protected void borrar() { //if(datosValidos()){ //Personaje p=MapearDeFormulario(); ctrl.delete(Integer.parseInt(cod.getText()),nom.getText()); JOptionPane.showMessageDialog(null, "PERSONAJE ELIMINADO: " + nom.getText() + " CORRECTAMENTE"); limpiarCampos(); //MapearAFormulario(p); //} } public void MapearAFormulario(Personaje p){ if(p.getNombre()!=null || p.getCodigo()!=0) { cod.setText(String.valueOf(p.getCodigo())); nom.setText(String.valueOf(p.getNombre())); energia.setText(String.valueOf( p.getEnergia())); def.setText(String.valueOf(p.getDefensa())); vida.setText(String.valueOf(p.getVida())); evasion.setText(String.valueOf( p.getEvasion())); ptosTot.setText(String.valueOf(p.getPtos_totales())); } } public Personaje MapearDeFormulario(){ Personaje p = new Personaje(); p.setCodigo(Integer.parseInt("0")); p.setEnergia(Integer.parseInt(energia.getText())); p.setDefensa(Integer.parseInt(def.getText())); p.setVida(Integer.parseInt(vida.getText())); p.setEvasion(Integer.parseInt(evasion.getText())); p.setNombre(nom.getText()); int suma=0; suma=p.getEnergia()+p.getDefensa()+p.getVida()+p.getEvasion(); p.setPtos_totales(suma); return p; } protected void limpiarCampos(){ ptosTot.setText(""); ptosDisp.setText(""); energia.setText(""); def.setText(""); vida.setText(""); evasion.setText(""); nom.setText(""); cod.setText(""); } public boolean datosValidos(int creo){ boolean valido=true; boolean coincideNom=false; boolean coincideCodNom=false; int suma=0; if(!energia.getText().matches("[0-9]*") || energia.getText().matches("")) { JOptionPane.showMessageDialog(null, "LA ENERGIA NO ES UN NUMERO"); valido=false; } if(!def.getText().matches("[0-9]*") || def.getText().matches("") ||Integer.parseInt(def.getText())>20 ) { JOptionPane.showMessageDialog(null, "DEFENSA MAYOR A 20 O NO ES UN NUMERO"); valido=false; // def.setText("0"); } if(!evasion.getText().matches("[0-9]*") || evasion.getText().matches("") || Integer.parseInt(evasion.getText())>80) { JOptionPane.showMessageDialog(null, "EVASION MAYOR A 80 o NO ES UN NUMERO"); valido=false; //evasion.setText("0"); } if(!vida.getText().matches("[0-9]*")|| vida.getText().matches("")) { JOptionPane.showMessageDialog(null, "LA VIDA NO ES UN NUMERO"); valido=false; //vida.setText("0"); } if(nom.getText().matches("") || nom.getText().matches("Ingrese nombre") ) { JOptionPane.showMessageDialog(null, "NO SE HA INGRESADO NOMBRE"); valido=false; nom.setText("Ingresa nombre!!"); } coincideNom= ctrl.coincideNombre(nom.getText()); if(creo==0) { coincideCodNom= ctrl.coincideCodNom(Integer.parseInt(cod.getText()), nom.getText()); if (coincideCodNom==false && coincideNom==true) {JOptionPane.showMessageDialog(null, "No coincide Nombre con el codigo pero si esta en la BD"); valido=false; } } if (coincideNom==true && creo==1) { valido=false; JOptionPane.showMessageDialog(null, "Ya existe nombre en BD"); } if (valido==true) { int resto=0; suma= Integer.parseInt(def.getText()) + Integer.parseInt(evasion.getText()) + Integer.parseInt(vida.getText()) + Integer.parseInt(energia.getText()); if(suma>200) { JOptionPane.showMessageDialog(null, "PUNTOS ASIGNADOS MAYORES A LOS TOTALES"); valido=false; //energia.setText("0"); //def.setText("0"); //vida.setText("0"); //evasion.setText("0"); } resto=200-suma; if (resto>=0) { ptosTot.setText(String.valueOf(suma)); ptosDisp.setText(String.valueOf(resto)); JOptionPane.showMessageDialog(null, "Te sobran: "+resto+" puntos para asignar, podes modificar esos puntos en cualquier momento"); } else JOptionPane.showMessageDialog(null, "Te excediste: "+ -(resto)+" puntos"); } return valido; } } //Aca termina la clase
TP1/src/uiDesktop/ABMCPersonaje.java
package uiDesktop; import java.awt.EventQueue; import negocio.*; import entidades.*; import javax.swing.AbstractButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JEditorPane; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.logging.Level; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; import javax.swing.JRadioButton; import javax.swing.JTextPane; import org.omg.CORBA.portable.ApplicationException; import java.awt.Color; import java.awt.SystemColor; import java.awt.Font; import javax.swing.SwingConstants; public class ABMCPersonaje { private JFrame frame; private JTextField cod; private JTextField nom; private JTextField energia; private JTextField vida; private JTextField evasion; private JTextField def; private JTextField ptosTot; private CtrlABMPersonaje ctrl; private JTextField ptosDisp; public int creo=0; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ABMCPersonaje window = new ABMCPersonaje(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public ABMCPersonaje() { initialize(); ctrl = new CtrlABMPersonaje(); }; /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 508, 333); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); cod = new JTextField(); cod.setBounds(84, 59, 40, 20); frame.getContentPane().add(cod); cod.setColumns(10); //cod.setVisible(false); JLabel lblCodigo = new JLabel("Codigo: "); lblCodigo.setBounds(30, 62, 55, 14); frame.getContentPane().add(lblCodigo); JLabel lblNombre = new JLabel("Nombre: "); lblNombre.setBounds(150, 62, 55, 14); frame.getContentPane().add(lblNombre); nom = new JTextField(); nom.setBounds(200, 59, 145, 20); frame.getContentPane().add(nom); nom.setColumns(10); JLabel lblEnergia = new JLabel("Energia"); lblEnergia.setBounds(42, 107, 46, 14); frame.getContentPane().add(lblEnergia); JLabel lblDefensa = new JLabel("Defensa"); lblDefensa.setBounds(41, 132, 58, 14); frame.getContentPane().add(lblDefensa); JLabel lblVida = new JLabel("Vida"); lblVida.setBounds(42, 157, 46, 14); frame.getContentPane().add(lblVida); JLabel lblEvasion = new JLabel("Evasion"); lblEvasion.setBounds(42, 180, 46, 14); frame.getContentPane().add(lblEvasion); energia = new JTextField(); energia.setBounds(94, 104, 34, 20); frame.getContentPane().add(energia); energia.setColumns(10); vida = new JTextField(); vida.setColumns(10); vida.setBounds(94, 154, 34, 20); frame.getContentPane().add(vida); evasion = new JTextField(); evasion.setColumns(10); evasion.setBounds(94, 177, 34, 20); frame.getContentPane().add(evasion); def = new JTextField(); def.setBounds(93, 129, 35, 20); frame.getContentPane().add(def); def.setColumns(10); ptosTot = new JTextField(); ptosTot.setBounds(94, 208, 34, 20); frame.getContentPane().add(ptosTot); //textField_6.setText("200"); ptosTot.setColumns(10); JLabel lblPuntosTotales = new JLabel("Puntos Totales"); lblPuntosTotales.setBounds(10, 208, 104, 20); frame.getContentPane().add(lblPuntosTotales); JButton btnCrear = new JButton("Crear"); btnCrear.setBounds(355, 128, 89, 23); frame.getContentPane().add(btnCrear); btnCrear.setVisible(false); JButton btnModificar = new JButton("Modificar"); btnModificar.setBounds(355, 103, 89, 23); frame.getContentPane().add(btnModificar); btnModificar.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { modificar(); } }); JButton btnBuscarPorNombre = new JButton("Buscar Por Nombre"); btnBuscarPorNombre.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); btnBuscarPorNombre.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { buscarPorNombre(); } }); btnBuscarPorNombre.setBounds(326, 128, 135, 23); frame.getContentPane().add(btnBuscarPorNombre); JButton btnBorrar = new JButton("Borrar"); btnBorrar.setBounds(355, 190, 89, 23); frame.getContentPane().add(btnBorrar); btnBorrar.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { borrar(); } }); JTextPane condDef = new JTextPane(); condDef.setFont(new Font("Tahoma", Font.BOLD, 11)); condDef.setBackground(SystemColor.control); condDef.setBounds(139, 129, 98, 20); frame.getContentPane().add(condDef); JTextPane condEv = new JTextPane(); condEv.setFont(new Font("Tahoma", Font.BOLD, 11)); condEv.setBackground(SystemColor.control); condEv.setBounds(139, 177, 98, 20); frame.getContentPane().add(condEv); JRadioButton newPers = new JRadioButton("Nuevo Personaje"); newPers.setBounds(351, 58, 123, 23); //rdbtnNuevoPersonaje.setText("Nuevo Personaje"); //newPers.setSelected(true); frame.getContentPane().add(newPers); JButton exit = new JButton("EXIT"); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); exit.setBounds(199, 261, 89, 23); frame.getContentPane().add(exit); JButton btnLimpiarCampos = new JButton("Limpiar Campos"); btnLimpiarCampos.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { limpiarCampos(); } }); btnLimpiarCampos.setBounds(190, 209, 113, 23); frame.getContentPane().add(btnLimpiarCampos); ptosDisp = new JTextField(); ptosDisp.setBounds(94, 245, 40, 20); frame.getContentPane().add(ptosDisp); ptosDisp.setColumns(10); JLabel lblPuntosDisponibles = new JLabel("Puntos Disp"); lblPuntosDisponibles.setHorizontalAlignment(SwingConstants.CENTER); lblPuntosDisponibles.setBounds(10, 239, 75, 28); frame.getContentPane().add(lblPuntosDisponibles); JButton btnBuscarPorCodigo = new JButton("Buscar Por Codigo"); btnBuscarPorCodigo.setBounds(326, 176, 135, 23); frame.getContentPane().add(btnBuscarPorCodigo); btnBuscarPorCodigo.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { buscarPorCodigo(); } }); newPers.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { if (newPers.isSelected()==true) { cod.setVisible(false); lblCodigo.setVisible(false); btnCrear.setVisible(true); btnBuscarPorCodigo.setVisible(false); btnBuscarPorNombre.setVisible(false); btnBorrar.setVisible(false); btnModificar.setVisible(false); ptosDisp.setText("200"); ptosTot.setText("0"); energia.setText("0"); def.setText("0"); vida.setText("0"); evasion.setText("0"); nom.setText("Ingrese nombre"); condEv.setText("Max 80 puntos"); condDef.setText("Max 20 puntos"); } else{ btnCrear.setVisible(false); cod.setVisible(true); lblCodigo.setVisible(true); btnBuscarPorCodigo.setVisible(true); btnBuscarPorNombre.setVisible(true); btnBorrar.setVisible(true); btnModificar.setVisible(true); ptosTot.setText(""); ptosDisp.setText(""); energia.setText(""); def.setText(""); vida.setText(""); evasion.setText(""); nom.setText(""); condEv.setText(""); condDef.setText(""); }; } }); btnCrear.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { creo=1; agregar(); newPers.setSelected(false); condEv.setText(""); condDef.setText(""); limpiarCampos(); creo=0; cod.setVisible(true); lblCodigo.setVisible(true); btnCrear.setVisible(false); btnBuscarPorCodigo.setVisible(true); btnBuscarPorNombre.setVisible(true); btnBorrar.setVisible(true); btnModificar.setVisible(true); } }); }; ///METODOS///////////////////// protected void agregar() { if(datosValidos(creo)){ //JOptionPane.showMessageDialog(null, "TODO OK"); Personaje p=MapearDeFormulario(); ctrl.add(p); //MapearAFormulario(p); } } protected void buscarPorNombre() { //creo=1; if(!nom.getText().matches("")) { Personaje p = ctrl.getPersonaje(nom.getText()); if(p!=null) MapearAFormulario(p); else JOptionPane.showMessageDialog(null, "No se encontro el nombre del personaje"); } else { JOptionPane.showMessageDialog(null, "Ha habido un error amigoh\nVolve a ingresar un nombre"); limpiarCampos(); } } protected void buscarPorCodigo() { if(!cod.getText().matches("")) { Personaje p = ctrl.getPersonaje(Integer.parseInt(cod.getText())); if(p!=null) MapearAFormulario(p); else JOptionPane.showMessageDialog(null, "No se encontro el codigo del personaje"); } else { JOptionPane.showMessageDialog(null, "Ha habido un error amigoh\nVolve a ingresar un codigo"); limpiarCampos(); } } protected void modificar() { if(cod.getText().matches("")) cod.setText("0"); if (datosValidos(creo)) { Personaje po = ctrl.getPersonaje(Integer.parseInt(cod.getText())); if(po!=null) MapearAFormulario(po); /* po tiene el personaje con su nombre antiguo, esto lo hago por si tambien decido cambiarle su nombre ademas de los atributos p va a tener el nuevo nombre (si es que lo cambie) y los atributos nuevos a update le doy el personaje modificado y el nombre del personaje original para que lo busque y modifique ese personaje*/ Personaje p=MapearDeFormulario(); ctrl.update(p, po.getNombre()); limpiarCampos();} /*if(p!=null) JOptionPane.showMessageDialog(null, "Nombre: "+p.getNombre()+" Energia:");*/ } protected void borrar() { //if(datosValidos()){ //Personaje p=MapearDeFormulario(); ctrl.delete(Integer.parseInt(cod.getText()),nom.getText()); JOptionPane.showMessageDialog(null, "PERSONAJE ELIMINADO: " + nom.getText() + " CORRECTAMENTE"); limpiarCampos(); //MapearAFormulario(p); //} } public void MapearAFormulario(Personaje p){ if(p.getNombre()!=null || p.getCodigo()!=0) { cod.setText(String.valueOf(p.getCodigo())); nom.setText(String.valueOf(p.getNombre())); energia.setText(String.valueOf( p.getEnergia())); def.setText(String.valueOf(p.getDefensa())); vida.setText(String.valueOf(p.getVida())); evasion.setText(String.valueOf( p.getEvasion())); ptosTot.setText(String.valueOf(p.getPtos_totales())); } } public Personaje MapearDeFormulario(){ Personaje p = new Personaje(); p.setCodigo(Integer.parseInt("0")); p.setEnergia(Integer.parseInt(energia.getText())); p.setDefensa(Integer.parseInt(def.getText())); p.setVida(Integer.parseInt(vida.getText())); p.setEvasion(Integer.parseInt(evasion.getText())); p.setNombre(nom.getText()); int suma=0; suma=p.getEnergia()+p.getDefensa()+p.getVida()+p.getEvasion(); p.setPtos_totales(suma); return p; } protected void limpiarCampos(){ { ptosTot.setText(""); ptosDisp.setText(""); energia.setText(""); def.setText(""); vida.setText(""); evasion.setText(""); nom.setText(""); cod.setText(""); }; } public boolean datosValidos(int creo){ boolean valido=true; boolean coincideNom=false; boolean coincideCodNom=false; int suma=0; //Font fuente =new Font("Serief",Font.BOLD|Font.ITALIC,14); if(!energia.getText().matches("[0-9]*") || energia.getText().matches("")) { JOptionPane.showMessageDialog(null, "LA ENERGIA NO ES UN NUMERO"); valido=false; // energia.setFont(fuente); } if(!def.getText().matches("[0-9]*") || def.getText().matches("") ||Integer.parseInt(def.getText())>20 ) { JOptionPane.showMessageDialog(null, "DEFENSA MAYOR A 20 O NO ES UN NUMERO"); valido=false; // def.setText("0"); } if(!evasion.getText().matches("[0-9]*") || evasion.getText().matches("") || Integer.parseInt(evasion.getText())>80) { JOptionPane.showMessageDialog(null, "EVASION MAYOR A 80 o NO ES UN NUMERO"); valido=false; //evasion.setText("0"); } if(!vida.getText().matches("[0-9]*")|| vida.getText().matches("")) { JOptionPane.showMessageDialog(null, "LA VIDA NO ES UN NUMERO"); valido=false; //vida.setText("0"); } if(nom.getText().matches("") || nom.getText().matches("Ingrese nombre") ) { JOptionPane.showMessageDialog(null, "NO SE HA INGRESADO NOMBRE"); valido=false; nom.setText("Ingresa nombre!!"); } coincideNom= ctrl.coincideNombre(nom.getText()); if(creo==0) { coincideCodNom= ctrl.coincideCodNom(Integer.parseInt(cod.getText()), nom.getText()); if (coincideCodNom==false && coincideNom==true) {JOptionPane.showMessageDialog(null, "No coincide Nombre con el codigo pero si esta en la BD"); valido=false; } } if (coincideNom==true && creo==1) { valido=false; JOptionPane.showMessageDialog(null, "Ya existe nombre en BD"); } if (valido==true) { int resto=0; suma= Integer.parseInt(def.getText()) + Integer.parseInt(evasion.getText()) + Integer.parseInt(vida.getText()) + Integer.parseInt(energia.getText()); if(suma>200) { JOptionPane.showMessageDialog(null, "PUNTOS ASIGNADOS MAYORES A LOS TOTALES"); valido=false; //energia.setText("0"); //def.setText("0"); //vida.setText("0"); //evasion.setText("0"); } resto=200-suma; if (resto>=0) { ptosTot.setText(String.valueOf(suma)); ptosDisp.setText(String.valueOf(resto)); JOptionPane.showMessageDialog(null, "Te sobran: "+resto+" puntos para asignar, podes modificar esos puntos en cualquier momento"); } else JOptionPane.showMessageDialog(null, "Te excediste: "+ -(resto)+" puntos"); } return valido; } }
cambio en la interfaz, fijense si lo quieren dejar asi o cambiarle algo
TP1/src/uiDesktop/ABMCPersonaje.java
cambio en la interfaz, fijense si lo quieren dejar asi o cambiarle algo
Java
agpl-3.0
2ad7929a0469ac6ea63dc17aca0f4ec7e21ebad2
0
deepstupid/sphinx5
/* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.decoder; import edu.cmu.sphinx.frontend.util.StreamAudioSource; import edu.cmu.sphinx.frontend.util.StreamCepstrumSource; import edu.cmu.sphinx.frontend.DataSource; import edu.cmu.sphinx.util.BatchFile; import edu.cmu.sphinx.util.SphinxProperties; import edu.cmu.sphinx.util.Timer; import edu.cmu.sphinx.util.NISTAlign; import edu.cmu.sphinx.util.Utilities; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.Iterator; /** * Decodes a batch file containing a list of files to decode. * The files can be either audio files or cepstral files, but defaults * to audio files. To decode cepstral files, set the Sphinx property * <code> edu.cmu.sphinx.decoder.BatchDecoder.inputDataType = cepstrum </code> */ public class BatchDecoder { private final static String PROP_PREFIX = "edu.cmu.sphinx.decoder.BatchDecoder."; /** * The SphinxProperty name for how many files to skip for every decode. */ public final static String PROP_SKIP = PROP_PREFIX + "skip"; /** * The default value for the property PROP_SKIP. */ public final static int PROP_SKIP_DEFAULT = 0; /** * The SphinxProperty that specified which batch job is to be run. * */ public final static String PROP_WHICH_BATCH = PROP_PREFIX + "whichBatch"; /** * The default value for the property PROP_WHICH_BATCH. */ public final static int PROP_WHICH_BATCH_DEFAULT = 0; /** * The SphinxProperty for the total number of batch jobs the decoding * run is being divided into. * * The BatchDecoder supports running a subset of a batch. * This allows a test to be distributed among several machines. * */ public final static String PROP_TOTAL_BATCHES = PROP_PREFIX + "totalBatches"; /** * The default value for the property PROP_TOTAL_BATCHES. */ public final static int PROP_TOTAL_BATCHES_DEFAULT = 1; /** * The SphinxProperty name for the input data type. */ public final static String PROP_INPUT_TYPE = PROP_PREFIX+"inputDataType"; /** * The default value for the property PROP_INPUT_TYPE. */ public final static String PROP_INPUT_TYPE_DEFAULT = "audio"; private DataSource dataSource; private Decoder decoder; private String batchFile; private String context; private String inputDataType; private int skip; private int whichBatch; private int totalBatches; /** * Constructs a BatchDecoder. * * @param context the context of this BatchDecoder * @param batchFile the file that contains a list of files to decode */ public BatchDecoder(String context, String batchFile) throws IOException { SphinxProperties props = SphinxProperties.getSphinxProperties(context); init(props, batchFile); } /** * Initialize the SphinxProperties. * * @param props the SphinxProperties */ private void initSphinxProperties(SphinxProperties props) { context = props.getContext(); inputDataType = props.getString(PROP_INPUT_TYPE, PROP_INPUT_TYPE_DEFAULT); skip = props.getInt(PROP_SKIP, PROP_SKIP_DEFAULT); whichBatch = props.getInt(PROP_WHICH_BATCH, PROP_WHICH_BATCH_DEFAULT); totalBatches = props.getInt(PROP_TOTAL_BATCHES, PROP_TOTAL_BATCHES_DEFAULT); } /** * Common intialization code * * @param props the sphinx properties * * @param batchFile the batch file */ private void init(SphinxProperties props, String batchFile) throws IOException { initSphinxProperties(props); this.batchFile = batchFile; if (inputDataType.equals("audio")) { dataSource = new StreamAudioSource ("batchAudioSource", context, null, null); } else if (inputDataType.equals("cepstrum")) { dataSource = new StreamCepstrumSource ("batchCepstrumSource", context); } else { throw new Error("Unsupported data type: " + inputDataType + "\n" + "Only audio and cepstrum are supported\n"); } decoder = new Decoder(context, dataSource); } /** * Decodes the batch of audio files */ public void decode() throws IOException { int curCount = skip; System.out.println("\nBatchDecoder: decoding files in " + batchFile); System.out.println("----------"); for (Iterator i = getLines(batchFile).iterator(); i.hasNext();) { String line = (String) i.next(); String file = BatchFile.getFilename(line); String reference = BatchFile.getReference(line); if (++curCount >= skip) { curCount = 0; decodeFile(file, reference); } } System.out.println("\nBatchDecoder: All files decoded\n"); Timer.dumpAll(context); decoder.showSummary(); } /** * Decodes the given file. * * @param file the file to decode * @param ref the reference string (or null if not available) */ public void decodeFile(String file, String ref) throws IOException { System.out.println("\nDecoding: " + file); InputStream is = new FileInputStream(file); if (inputDataType.equals("audio")) { ((StreamAudioSource) dataSource).setInputStream(is, file); } else if (inputDataType.equals("cepstrum")) { boolean bigEndian = Utilities.isCepstraFileBigEndian(file); ((StreamCepstrumSource) dataSource).setInputStream(is, bigEndian); } decoder.decode(ref); } /** * Returns the set of batch results * * @return a batch result representing the set of runs for this * batch decoder. */ public BatchResults getBatchResults() { NISTAlign align = decoder.getNISTAlign(); return new BatchResults(align.getTotalWords(), align.getTotalSentences(), align.getTotalSubstitutions(), align.getTotalInsertions(), align.getTotalDeletions(), align.getTotalSentencesWithErrors()); } /** * Gets the set of lines from the file * * @param file the name of the file */ private List getLines(String file) throws IOException { List list = BatchFile.getLines(file); if (totalBatches > 1) { int linesPerBatch = list.size() / totalBatches; if (linesPerBatch < 1) { linesPerBatch = 1; } if (whichBatch >= totalBatches) { whichBatch = totalBatches - 1; } int startLine = whichBatch * linesPerBatch; // last batch needs to get all remaining lines if (whichBatch == (totalBatches - 1)) { list = list.subList(startLine, list.size()); } else { list = list.subList(startLine, startLine + linesPerBatch); } } return list; } /** * Main method of this BatchDecoder. * * @param argv argv[0] : SphinxProperties file * argv[1] : a file listing all the audio files to decode */ public static void main(String[] argv) { if (argv.length < 2) { System.out.println ("Usage: BatchDecoder propertiesFile batchFile"); System.exit(1); } String context = "batch"; String propertiesFile = argv[0]; String batchFile = argv[1]; String pwd = System.getProperty("user.dir"); try { SphinxProperties.initContext (context, new URL("file://" + pwd + "/" + propertiesFile)); BatchDecoder decoder = new BatchDecoder(context, batchFile); decoder.decode(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
edu/cmu/sphinx/decoder/BatchDecoder.java
/* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.decoder; import edu.cmu.sphinx.frontend.util.StreamAudioSource; import edu.cmu.sphinx.frontend.util.StreamCepstrumSource; import edu.cmu.sphinx.frontend.DataSource; import edu.cmu.sphinx.util.BatchFile; import edu.cmu.sphinx.util.SphinxProperties; import edu.cmu.sphinx.util.Timer; import edu.cmu.sphinx.util.NISTAlign; import edu.cmu.sphinx.util.Utilities; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.Iterator; /** * Decodes a batch file containing a list of files to decode. * The files can be either audio files or cepstral files, but defaults * to audio files. To decode cepstral files, set the Sphinx property * <code> edu.cmu.sphinx.decoder.BatchDecoder.inputDataType = cepstrum </code> */ public class BatchDecoder { private final static String PROP_PREFIX = "edu.cmu.sphinx.decoder.BatchDecoder."; /** * The SphinxProperty name for how many files to skip for every decode. */ public final static String PROP_SKIP = PROP_PREFIX + "skip"; /** * The default value for the property PROP_SKIP. */ public final static int PROP_SKIP_DEFAULT = 0; /** * The SphinxProperty that specified which batch job is to be run. * */ public final static String PROP_WHICH_BATCH = PROP_PREFIX + "whichBatch"; /** * The default value for the property PROP_WHICH_BATCH. */ public final static int PROP_WHICH_BATCH_DEFAULT = 0; /** * The SphinxProperty for the total number of batch jobs the decoding * run is being divided into. * * The BatchDecoder supports running a subset of a batch. * This allows a test to be distributed among several machines. * */ public final static String PROP_TOTAL_BATCHES = PROP_PREFIX + "totalBatches"; /** * The default value for the property PROP_TOTAL_BATCHES. */ public final static int PROP_TOTAL_BATCHES_DEFAULT = 1; /** * The SphinxProperty name for the input data type. */ public final static String PROP_INPUT_TYPE = PROP_PREFIX+"inputDataType"; /** * The default value for the property PROP_INPUT_TYPE. */ public final static String PROP_INPUT_TYPE_DEFAULT = "audio"; private DataSource dataSource; private Decoder decoder; private String batchFile; private String context; private String inputDataType; private int skip; private int whichBatch; private int totalBatches; /** * Constructs a BatchDecoder. * * @param context the context of this BatchDecoder * @param batchFile the file that contains a list of files to decode */ public BatchDecoder(String context, String batchFile) throws IOException { this(context, batchFile, true); } /** * Constructs a BatchDeocder with the given context, batch file, * and a boolean indicating whether to initialize the decoder. * * @param context the context of this BatchDecoder * @param batchFile the file that contains a list of files to decode * @param initDecoder indicates whether to initialize the decoder */ protected BatchDecoder(String context, String batchFile, boolean initDecoder) throws IOException { SphinxProperties props = SphinxProperties.getSphinxProperties(context); if (initDecoder) { init(props, batchFile); } else { initSphinxProperties(props); this.batchFile = batchFile; } } /** * Initialize the SphinxProperties. * * @param props the SphinxProperties */ private void initSphinxProperties(SphinxProperties props) { context = props.getContext(); inputDataType = props.getString(PROP_INPUT_TYPE, PROP_INPUT_TYPE_DEFAULT); skip = props.getInt(PROP_SKIP, PROP_SKIP_DEFAULT); whichBatch = props.getInt(PROP_WHICH_BATCH, PROP_WHICH_BATCH_DEFAULT); totalBatches = props.getInt(PROP_TOTAL_BATCHES, PROP_TOTAL_BATCHES_DEFAULT); } /** * Common intialization code * * @param props the sphinx properties * * @param batchFile the batch file */ private void init(SphinxProperties props, String batchFile) throws IOException { initSphinxProperties(props); this.batchFile = batchFile; if (inputDataType.equals("audio")) { dataSource = new StreamAudioSource ("batchAudioSource", context, null, null); } else if (inputDataType.equals("cepstrum")) { dataSource = new StreamCepstrumSource ("batchCepstrumSource", context); } else { throw new Error("Unsupported data type: " + inputDataType + "\n" + "Only audio and cepstrum are supported\n"); } decoder = new Decoder(context, dataSource); } /** * Decodes the batch of audio files */ public void decode() throws IOException { int curCount = skip; System.out.println("\nBatchDecoder: decoding files in " + batchFile); System.out.println("----------"); for (Iterator i = getLines(batchFile).iterator(); i.hasNext();) { String line = (String) i.next(); String file = BatchFile.getFilename(line); String reference = BatchFile.getReference(line); if (++curCount >= skip) { curCount = 0; decodeFile(file, reference); } } System.out.println("\nBatchDecoder: All files decoded\n"); Timer.dumpAll(context); getDecoder().showSummary(); } /** * Returns the Decoder. */ protected Decoder getDecoder() { return decoder; } /** * Returns the set of batch results * * @return a batch result representing the set of runs for this * batch decoder. */ public BatchResults getBatchResults() { NISTAlign align = decoder.getNISTAlign(); return new BatchResults( align.getTotalWords(), align.getTotalSentences(), align.getTotalSubstitutions(), align.getTotalInsertions(), align.getTotalDeletions(), align.getTotalSentencesWithErrors()); } /** * Gets the set of lines from the file * * @param file the name of the file */ List getLines(String file) throws IOException { List list = BatchFile.getLines(file); if (totalBatches > 1) { int linesPerBatch = list.size() / totalBatches; if (linesPerBatch < 1) { linesPerBatch = 1; } if (whichBatch >= totalBatches) { whichBatch = totalBatches - 1; } int startLine = whichBatch * linesPerBatch; // last batch needs to get all remaining lines if (whichBatch == (totalBatches - 1)) { list = list.subList(startLine, list.size()); } else { list = list.subList(startLine, startLine + linesPerBatch); } } return list; } /** * Decodes the given file. * * @param file the file to decode * @param ref the reference string (or null if not available) */ public void decodeFile(String file, String ref) throws IOException { System.out.println("\nDecoding: " + file); InputStream is = new FileInputStream(file); if (inputDataType.equals("audio")) { ((StreamAudioSource) dataSource).setInputStream(is, file); } else if (inputDataType.equals("cepstrum")) { boolean bigEndian = Utilities.isCepstraFileBigEndian(file); ((StreamCepstrumSource) dataSource).setInputStream(is, bigEndian); } // usually 25 features in one audio frame // but it doesn't really matter what this number is getDecoder().decode(ref); } /** * Main method of this BatchDecoder. * * @param argv argv[0] : SphinxProperties file * argv[1] : a file listing all the audio files to decode */ public static void main(String[] argv) { if (argv.length < 2) { System.out.println ("Usage: BatchDecoder propertiesFile batchFile"); System.exit(1); } String context = "batch"; String propertiesFile = argv[0]; String batchFile = argv[1]; String pwd = System.getProperty("user.dir"); try { SphinxProperties.initContext (context, new URL("file://" + pwd + "/" + propertiesFile)); BatchDecoder decoder = new BatchDecoder(context, batchFile); decoder.decode(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Further trimmed BatchDecoder. This is probably the simplest it can get... git-svn-id: a8b04003a33e1d3e001b9d20391fa392a9f62d91@1552 94700074-3cef-4d97-a70e-9c8c206c02f5
edu/cmu/sphinx/decoder/BatchDecoder.java
Further trimmed BatchDecoder. This is probably the simplest it can get...
Java
lgpl-2.1
ecb068549793237945b44b8d64fc80c6ef37b983
0
palominolabs/jmagick,palominolabs/jmagick,palominolabs/jmagick
package magicktest; import java.io.*; import java.util.*; import javax.swing.*; import magick.*; /** * Utility class intended for testing purposes. * <p>Title: </p> * * <p>Description: </p> * * <p>Copyright: Copyright (c) 2008</p> * * <p>Company: </p> * * @author Jacob Nordfalk */ public class MagickTesttools { public static String path_input = "test"+File.separator+"magicktest"+File.separator; public static String path_actual_output = "test"+File.separator+"actual_output"+File.separator; public static String path_correct_output = "test"+File.separator+"correct_output"+File.separator; /** * This flag makes all file comparisons pass and avoids that files are deleted in magictest/actual_output/ * Set to true and run tests to generate examples of "correct" output. * Copy then all files from magictest/actual_output/ to magictest/correct_output/ to define * the 'correct' result files which the test should conform to. */ public static boolean generate_correct_output = false; private static boolean generate_correct_output_warned; /** * Compares two image files pixel by pixel (by invoking the IM command 'compare') * @param file1 First image file name * @param file2 Second image file name * @return double difference The max allowed pixel difference (MSE metric) * @throws IOException If the difference is unacceptable big */ public static void compareImage(String file1, String file2, double maxDiff) throws IOException { //maxDiff = 2; // uncomment to make very strict test! if (generate_correct_output) { System.err.println("************************************** WARNING ************************************************"); System.err.println("* With generate_correct_output = true you are generating 'correct' output, instead of testing *"); System.err.println("***********************************************************************************************"); // show popup once if (!generate_correct_output_warned) { int ret = JOptionPane.showConfirmDialog(null, "generate_correct_output is on, so you are a generating 'correct' output, instead of comparing files"); System.out.println("ret="+ret); if (ret != JOptionPane.OK_OPTION) { System.err.println("generate_correct_output cancelled by user"); System.exit(-1); } generate_correct_output_warned = true; } return; } if (!new File(file1).exists()) throw new java.io.FileNotFoundException("Fil 1 not found: " + file1); if (!new File(file2).exists()) throw new java.io.FileNotFoundException("Fil 2 not found: " + file2); /* compare -metric MSE rose.jpg reconstruct.jpg difference.png 29.5615 dB MetricOptions[] = { { "Undefined", (long) UndefinedMetric }, { "MAE", (long) MeanAbsoluteErrorMetric }, { "MSE", (long) MeanSquaredErrorMetric }, { "PAE", (long) PeakAbsoluteErrorMetric }, { "PSNR", (long) PeakSignalToNoiseRatioMetric }, { "RMSE", (long) RootMeanSquaredErrorMetric }, { (char *) NULL, (long) UndefinedMetric } } */ //String cmd = "compare -metric MSE "+file1+" "+file2+" tempImageDifference.jpg"; String[] cmd = new String[] {"compare","-metric","MSE",file1,file2,"tempcompareImage.jpg"}; // Some may need an absolute path for IM 'compare' command. // Here are some examples: // if (System.getProperty("user.dir").startsWith("E:")) cmd = "E:\\user\\caramba\\magick-6.2.6-Q8\\"+cmd; // cmd = "C:\\Program Files\\ImageMagick-6.3.5-Q8\\"+cmd; Process compProces = Runtime.getRuntime().exec(cmd, new String[0]); InputStream std = compProces.getInputStream(); InputStream err = compProces.getErrorStream(); StringBuffer outsb = new StringBuffer(20); StringBuffer errsb = new StringBuffer(20); do { int ch =std.read(); if (ch==-1) break; outsb.append( (char) ch); } while (true); do { int ch =err.read(); if (ch==-1) break; errsb.append( (char) ch); } while (true); compProces.getOutputStream().close(); std.close(); err.close(); String ret = outsb.toString() + errsb.toString(); // parse the first number in output int n = ret.indexOf(" "); try { double difference = Double.parseDouble(n > 0 ? ret.substring(0, n) : ret.toString()); if (difference > maxDiff) { throw new RuntimeException("Images had a difference of " + difference + " which is bigger than max allowed of " + maxDiff + ":\n " + file1 + " " + file2); } } catch (NumberFormatException ex) { System.err.println("Output of command 'compare' could not be parsed."); System.err.println("Perhaps you need to give full path to IMs 'compare' command?"); System.err.println(cmd + " gave stdout: '"+outsb+"'"); System.err.println(cmd + " gave stderr: '"+errsb+"'"); throw new RuntimeException(ret); } // delete temporary file if no significan difference was found new File("tempImageDifference.jpg").delete(); } public static void writeAndCompare(MagickImage image, ImageInfo info, String fileName) throws Exception { new File(path_actual_output).mkdirs(); // Delete old files to make sure they dont interfere new File(path_actual_output+fileName).delete(); image.setFileName(path_actual_output+fileName); image.writeImage(info); // compare the pixel data (allowing for a small difference) compareImage(path_actual_output+fileName, path_correct_output+fileName, 20); if (!generate_correct_output) { // Check that IPCT and ICC data are exactly the same MagickImage correct = new MagickImage(new ImageInfo(path_correct_output+fileName)); if (!compareImageProfiles(image, correct)) { throw new RuntimeException("Image "+fileName+" had a difference in profiles."); } } } public static boolean compareImageProfiles(MagickImage image, MagickImage correct) throws Exception { if (!equals(image.getIptcProfile(), correct.getIptcProfile())) { System.out.println("Images had a IPTC profile difference"); System.out.println("Correct : "+profileInfoToString(correct.getIptcProfile())); System.out.println("Actual : "+profileInfoToString(image.getIptcProfile())); return false; } if (!equals(image.getColorProfile(), correct.getColorProfile())) { System.out.println("Images had a ICC profile difference"); System.out.println("Correct : "+profileInfoToString(correct.getColorProfile())); System.out.println("Actual : "+profileInfoToString(image.getColorProfile())); return false; } return true; } /** * Class ProfileInfo is missing the .equals()-method, so we make it here * @param p1 ProfileInfo * @param p2 ProfileInfo * @return boolean false if different content, true otherwise */ public static boolean equals(ProfileInfo p1, ProfileInfo p2) { if (p1==p2) return true; if (p1==null || p2==null) return false; // one but not both null return (p1.getName()==p2.getName() || (p1.getName()!=null && p1.getName().equals(p2.getName()))) && Arrays.equals(p1.getInfo(), p2.getInfo()); } /** * Display the information about the profile supplied. * * @param profile the profile for which to display */ public static void displayProfile(ProfileInfo profile) { System.out.println(profileInfoToString(profile)); } /** * Returns information about the profile supplied. * * @param profile the profile for which to display */ public static String profileInfoToString(ProfileInfo profile) { if (profile == null) { return "(null)"; } if (profile.getInfo() == null) { return "profile info=null"; } else { return "profile info.length=" + profile.getInfo().length+" hash="+Arrays.hashCode(profile.getInfo()); } } public static void allocateAndFreeSomeMem(int n) { byte[] b = new byte[n]; for (int i=0; i<n; i++) b[i] = (byte) i; System.out.println("alloker "+n+" "+ (b[0] + b[(n-1)/2])); b = null; System.gc(); } }
test/magicktest/MagickTesttools.java
package magicktest; import java.io.*; import java.util.*; import javax.swing.*; import magick.*; /** * Utility class intended for testing purposes. * <p>Title: </p> * * <p>Description: </p> * * <p>Copyright: Copyright (c) 2008</p> * * <p>Company: </p> * * @author Jacob Nordfalk */ public class MagickTesttools { public static String path_input = "test"+File.separator+"magicktest"+File.separator; public static String path_actual_output = "test"+File.separator+"actual_output"+File.separator; public static String path_correct_output = "test"+File.separator+"correct_output"+File.separator; /** * This flag makes all file comparisons pass and avoids that files are deleted in magictest/actual_output/ * Set to true and run tests to generate examples of "correct" output. * Copy then all files from magictest/actual_output/ to magictest/correct_output/ to define * the 'correct' result files which the test should conform to. */ public static boolean generate_correct_output = false; private static boolean generate_correct_output_warned; /** * Compares two image files pixel by pixel (by invoking the IM command 'compare') * @param file1 First image file name * @param file2 Second image file name * @return double difference The max allowed pixel difference (MSE metric) * @throws IOException If the difference is unacceptable big */ public static void compareImage(String file1, String file2, double maxDiff) throws IOException { //maxDiff = 2; // uncomment to make very strict test! if (generate_correct_output) { System.err.println("************************************** WARNING ************************************************"); System.err.println("* With generate_correct_output = true you are generating 'correct' output, instead of testing *"); System.err.println("***********************************************************************************************"); // show popup once if (!generate_correct_output_warned) { int ret = JOptionPane.showConfirmDialog(null, "generate_correct_output is on, so you are a generating 'correct' output, instead of comparing files"); System.out.println("ret="+ret); if (ret != JOptionPane.OK_OPTION) { System.err.println("generate_correct_output cancelled by user"); System.exit(-1); } generate_correct_output_warned = true; } return; } if (!new File(file1).exists()) throw new java.io.FileNotFoundException("Fil 1 not found: " + file1); if (!new File(file2).exists()) throw new java.io.FileNotFoundException("Fil 2 not found: " + file2); /* compare -metric MSE rose.jpg reconstruct.jpg difference.png 29.5615 dB MetricOptions[] = { { "Undefined", (long) UndefinedMetric }, { "MAE", (long) MeanAbsoluteErrorMetric }, { "MSE", (long) MeanSquaredErrorMetric }, { "PAE", (long) PeakAbsoluteErrorMetric }, { "PSNR", (long) PeakSignalToNoiseRatioMetric }, { "RMSE", (long) RootMeanSquaredErrorMetric }, { (char *) NULL, (long) UndefinedMetric } } */ String cmd = "compare -metric MSE "+file1+" "+file2+" tempImageDifference.jpg"; // Some may need an absolute path for IM 'compare' command. // Here are some examples: // if (System.getProperty("user.dir").startsWith("E:")) cmd = "E:\\user\\caramba\\magick-6.2.6-Q8\\"+cmd; // cmd = "C:\\Program Files\\ImageMagick-6.3.5-Q8\\"+cmd; Process compProces = Runtime.getRuntime().exec(cmd, new String[0]); InputStream std = compProces.getInputStream(); InputStream err = compProces.getErrorStream(); StringBuffer outsb = new StringBuffer(20); StringBuffer errsb = new StringBuffer(20); do { int ch =std.read(); if (ch==-1) break; outsb.append( (char) ch); } while (true); do { int ch =err.read(); if (ch==-1) break; errsb.append( (char) ch); } while (true); compProces.getInputStream().close(); std.close(); err.close(); String ret = outsb.toString() + errsb.toString(); // parse the first number in output int n = ret.indexOf(" "); try { double difference = Double.parseDouble(n > 0 ? ret.substring(0, n) : ret.toString()); if (difference > maxDiff) { throw new RuntimeException("Images had a difference of " + difference + " which is bigger than max allowed of " + maxDiff + ":\n " + file1 + " " + file2); } } catch (NumberFormatException ex) { System.err.println("Output of command 'compare' could not be parsed."); System.err.println("Perhaps you need to give full path to IMs 'compare' command?"); System.err.println(cmd + " gave stdout: '"+outsb+"'"); System.err.println(cmd + " gave stderr: '"+errsb+"'"); throw new RuntimeException(ret); } // delete temporary file if no significan difference was found new File("tempImageDifference.jpg").delete(); } public static void writeAndCompare(MagickImage image, ImageInfo info, String fileName) throws Exception { new File(path_actual_output).mkdirs(); // Delete old files to make sure they dont interfere new File(path_actual_output+fileName).delete(); image.setFileName(path_actual_output+fileName); image.writeImage(info); // compare the pixel data (allowing for a small difference) compareImage(path_actual_output+fileName, path_correct_output+fileName, 20); if (!generate_correct_output) { // Check that IPCT and ICC data are exactly the same MagickImage correct = new MagickImage(new ImageInfo(path_correct_output+fileName)); if (!compareImageProfiles(image, correct)) { throw new RuntimeException("Image "+fileName+" had a difference in profiles."); } } } public static boolean compareImageProfiles(MagickImage image, MagickImage correct) throws Exception { if (!equals(image.getIptcProfile(), correct.getIptcProfile())) { System.out.println("Images had a IPTC profile difference"); System.out.println("Correct : "+profileInfoToString(correct.getIptcProfile())); System.out.println("Actual : "+profileInfoToString(image.getIptcProfile())); return false; } if (!equals(image.getColorProfile(), correct.getColorProfile())) { System.out.println("Images had a ICC profile difference"); System.out.println("Correct : "+profileInfoToString(correct.getColorProfile())); System.out.println("Actual : "+profileInfoToString(image.getColorProfile())); return false; } return true; } /** * Class ProfileInfo is missing the .equals()-method, so we make it here * @param p1 ProfileInfo * @param p2 ProfileInfo * @return boolean false if different content, true otherwise */ public static boolean equals(ProfileInfo p1, ProfileInfo p2) { if (p1==p2) return true; if (p1==null || p2==null) return false; // one but not both null return (p1.getName()==p2.getName() || (p1.getName()!=null && p1.getName().equals(p2.getName()))) && Arrays.equals(p1.getInfo(), p2.getInfo()); } /** * Display the information about the profile supplied. * * @param profile the profile for which to display */ public static void displayProfile(ProfileInfo profile) { System.out.println(profileInfoToString(profile)); } /** * Returns information about the profile supplied. * * @param profile the profile for which to display */ public static String profileInfoToString(ProfileInfo profile) { if (profile == null) { return "(null)"; } if (profile.getInfo() == null) { return "profile info=null"; } else { return "profile info.length=" + profile.getInfo().length+" hash="+Arrays.hashCode(profile.getInfo()); } } public static void allocateAndFreeSomeMem(int n) { byte[] b = new byte[n]; for (int i=0; i<n; i++) b[i] = (byte) i; System.out.println("alloker "+n+" "+ (b[0] + b[(n-1)/2])); b = null; System.gc(); } }
bugfix in test tools git-svn-id: f6afc215dea6e63ef165b95e096da332c371cba2@39 00265e9a-a446-0410-a409-fb6d3c48c71e
test/magicktest/MagickTesttools.java
bugfix in test tools
Java
lgpl-2.1
f06f023d175b70cfb6de977674d2d458cf81359a
0
lcahlander/exist,opax/exist,jensopetersen/exist,adamretter/exist,joewiz/exist,patczar/exist,jessealama/exist,patczar/exist,patczar/exist,hungerburg/exist,kohsah/exist,opax/exist,ljo/exist,hungerburg/exist,wolfgangmm/exist,MjAbuz/exist,RemiKoutcherawy/exist,wshager/exist,zwobit/exist,lcahlander/exist,dizzzz/exist,hungerburg/exist,joewiz/exist,dizzzz/exist,ljo/exist,shabanovd/exist,jensopetersen/exist,MjAbuz/exist,MjAbuz/exist,kohsah/exist,RemiKoutcherawy/exist,kohsah/exist,wshager/exist,opax/exist,dizzzz/exist,jensopetersen/exist,ljo/exist,dizzzz/exist,kohsah/exist,shabanovd/exist,ambs/exist,ambs/exist,jensopetersen/exist,ljo/exist,hungerburg/exist,joewiz/exist,joewiz/exist,zwobit/exist,adamretter/exist,eXist-db/exist,windauer/exist,olvidalo/exist,ambs/exist,patczar/exist,patczar/exist,wolfgangmm/exist,MjAbuz/exist,lcahlander/exist,opax/exist,zwobit/exist,ljo/exist,shabanovd/exist,eXist-db/exist,shabanovd/exist,ambs/exist,windauer/exist,eXist-db/exist,olvidalo/exist,wolfgangmm/exist,kohsah/exist,adamretter/exist,joewiz/exist,jensopetersen/exist,lcahlander/exist,windauer/exist,shabanovd/exist,dizzzz/exist,adamretter/exist,RemiKoutcherawy/exist,RemiKoutcherawy/exist,adamretter/exist,wolfgangmm/exist,olvidalo/exist,dizzzz/exist,RemiKoutcherawy/exist,wshager/exist,eXist-db/exist,joewiz/exist,lcahlander/exist,wolfgangmm/exist,kohsah/exist,ambs/exist,zwobit/exist,shabanovd/exist,lcahlander/exist,windauer/exist,olvidalo/exist,zwobit/exist,wshager/exist,windauer/exist,jessealama/exist,zwobit/exist,jensopetersen/exist,jessealama/exist,olvidalo/exist,windauer/exist,jessealama/exist,wshager/exist,MjAbuz/exist,patczar/exist,MjAbuz/exist,RemiKoutcherawy/exist,wshager/exist,eXist-db/exist,hungerburg/exist,opax/exist,ljo/exist,jessealama/exist,wolfgangmm/exist,jessealama/exist,adamretter/exist,ambs/exist,eXist-db/exist
/* * eXist Open Source Native XML Database * Copyright (C) 2001-06 Wolfgang M. Meier * [email protected] * http://exist.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.memtree; import org.exist.dom.DocumentSet; import org.exist.dom.NodeListImpl; import org.exist.dom.NodeSet; import org.exist.dom.QName; import org.exist.dom.QNameable; import org.exist.storage.DBBroker; import org.exist.storage.serializers.Serializer; import org.exist.util.serializer.DOMStreamer; import org.exist.util.serializer.Receiver; import org.exist.util.serializer.SerializerPool; import org.exist.xquery.Cardinality; import org.exist.xquery.Constants; import org.exist.xquery.XPathException; import org.exist.xquery.value.AtomicValue; import org.exist.xquery.value.Item; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.StringValue; import org.exist.xquery.value.Type; import org.exist.xquery.value.ValueSequence; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.UserDataHandler; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; public class NodeImpl implements Node, NodeValue, QNameable, Comparable { public final static short REFERENCE_NODE = 100; public final static short NAMESPACE_NODE = 101; protected int nodeNumber; protected DocumentImpl document; public NodeImpl(DocumentImpl doc, int nodeNumber) { this.document = doc; this.nodeNumber = nodeNumber; } public int getNodeNumber() { return nodeNumber; } /* (non-Javadoc) * @see org.exist.xquery.value.NodeValue#getImplementation() */ public int getImplementationType() { return NodeValue.IN_MEMORY_NODE; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getDocumentSet() */ public DocumentSet getDocumentSet() { return DocumentSet.EMPTY_DOCUMENT_SET; } /* (non-Javadoc) * @see org.exist.xquery.value.NodeValue#getNode() */ public Node getNode() { return this; } /* (non-Javadoc) * @see org.w3c.dom.Node#getNodeName() */ public String getNodeName() { switch (getNodeType()) { case Node.DOCUMENT_NODE : return "#document"; case Node.ELEMENT_NODE : case Node.PROCESSING_INSTRUCTION_NODE : QName qn = (QName) document.namePool.get(document.nodeName[nodeNumber]); return qn.toString(); case Node.ATTRIBUTE_NODE: return document.namePool.get(document.attrName[nodeNumber]).toString(); case NodeImpl.NAMESPACE_NODE: return document.namePool.get(document.namespaceCode[nodeNumber]).toString(); case Node.TEXT_NODE : return "#text"; default : return "#unknown"; } } public QName getQName() { switch (getNodeType()) { case Node.DOCUMENT_NODE : return QName.DOCUMENT_QNAME; case Node.ATTRIBUTE_NODE : case Node.ELEMENT_NODE : case Node.PROCESSING_INSTRUCTION_NODE : QName qn = (QName) document.namePool.get(document.nodeName[nodeNumber]); return qn; case Node.COMMENT_NODE: return QName.COMMENT_QNAME; case Node.TEXT_NODE : return QName.TEXT_QNAME; default : return null; } } public void expand() throws DOMException { document.expand(); } public void deepCopy() throws DOMException { DocumentImpl newDoc = document.expandRefs(this); if (newDoc != document) { // we received a new document this.nodeNumber = 1; this.document = newDoc; } } /* (non-Javadoc) * @see org.w3c.dom.Node#getNodeValue() */ public String getNodeValue() throws DOMException { return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#setNodeValue(java.lang.String) */ public void setNodeValue(String arg0) throws DOMException { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.w3c.dom.Node#getNodeType() */ public short getNodeType() { return document.nodeKind[nodeNumber]; } /* (non-Javadoc) * @see org.w3c.dom.Node#getParentNode() */ public Node getParentNode() { int next = document.next[nodeNumber]; while (next > nodeNumber) { next = document.next[next]; } if (next < 0) return document; return document.getNode(next); } public void addContextNode(int contextId, NodeValue node) { } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if(!(obj instanceof NodeImpl)) return false; return nodeNumber == ((NodeImpl) obj).nodeNumber; } /* (non-Javadoc) * @see org.exist.xquery.value.NodeValue#equals(org.exist.xquery.value.NodeValue) */ public boolean equals(NodeValue other) throws XPathException { if (other.getImplementationType() != NodeValue.IN_MEMORY_NODE) return false; return nodeNumber == ((NodeImpl) other).nodeNumber; } /* (non-Javadoc) * @see org.exist.xquery.value.NodeValue#after(org.exist.xquery.value.NodeValue) */ public boolean after(NodeValue other) throws XPathException { if (other.getImplementationType() != NodeValue.IN_MEMORY_NODE) throw new XPathException("annot compare persistent node with in-memory node"); return nodeNumber < ((NodeImpl) other).nodeNumber; } /* (non-Javadoc) * @see org.exist.xquery.value.NodeValue#before(org.exist.xquery.value.NodeValue) */ public boolean before(NodeValue other) throws XPathException { if (other.getImplementationType() != NodeValue.IN_MEMORY_NODE) throw new XPathException("annot compare persistent node with in-memory node"); return nodeNumber > ((NodeImpl) other).nodeNumber; } public int compareTo(Object other) { if(!(other instanceof NodeImpl)) return Constants.INFERIOR; NodeImpl n = (NodeImpl)other; if(n.document == document) { if (nodeNumber == n.nodeNumber) return Constants.EQUAL; else if (nodeNumber < n.nodeNumber) return Constants.INFERIOR; else return Constants.SUPERIOR; } else return Constants.INFERIOR; } /* (non-Javadoc) * @see org.w3c.dom.Node#getChildNodes() */ public NodeList getChildNodes() { return new NodeListImpl(); } /* (non-Javadoc) * @see org.w3c.dom.Node#getFirstChild() */ public Node getFirstChild() { return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#getLastChild() */ public Node getLastChild() { return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#getPreviousSibling() */ public Node getPreviousSibling() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#getNextSibling() */ public Node getNextSibling() { int nextNr = document.next[nodeNumber]; return nextNr < nodeNumber ? null : document.getNode(nextNr); } /* (non-Javadoc) * @see org.w3c.dom.Node#getAttributes() */ public NamedNodeMap getAttributes() { return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#getOwnerDocument() */ public Document getOwnerDocument() { return document; } public DocumentImpl getDocument() { return document; } /* (non-Javadoc) * @see org.w3c.dom.Node#insertBefore(org.w3c.dom.Node, org.w3c.dom.Node) */ public Node insertBefore(Node arg0, Node arg1) throws DOMException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#replaceChild(org.w3c.dom.Node, org.w3c.dom.Node) */ public Node replaceChild(Node arg0, Node arg1) throws DOMException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#removeChild(org.w3c.dom.Node) */ public Node removeChild(Node arg0) throws DOMException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#appendChild(org.w3c.dom.Node) */ public Node appendChild(Node arg0) throws DOMException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#hasChildNodes() */ public boolean hasChildNodes() { return false; } /* (non-Javadoc) * @see org.w3c.dom.Node#cloneNode(boolean) */ public Node cloneNode(boolean arg0) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#normalize() */ public void normalize() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.w3c.dom.Node#isSupported(java.lang.String, java.lang.String) */ public boolean isSupported(String arg0, String arg1) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see org.w3c.dom.Node#getNamespaceURI() */ public String getNamespaceURI() { return ""; } /* (non-Javadoc) * @see org.w3c.dom.Node#getPrefix() */ public String getPrefix() { return ""; } /* (non-Javadoc) * @see org.w3c.dom.Node#setPrefix(java.lang.String) */ public void setPrefix(String arg0) throws DOMException { } /* (non-Javadoc) * @see org.w3c.dom.Node#getLocalName() */ public String getLocalName() { return ""; } /* (non-Javadoc) * @see org.w3c.dom.Node#hasAttributes() */ public boolean hasAttributes() { return false; } /* * Methods of interface Item */ /* (non-Javadoc) * @see org.exist.xquery.value.Item#getType() */ public int getType() { int type = getNodeType(); switch (type) { case Node.DOCUMENT_NODE : return Type.DOCUMENT; case Node.COMMENT_NODE : return Type.COMMENT; case Node.PROCESSING_INSTRUCTION_NODE : return Type.PROCESSING_INSTRUCTION; case Node.ELEMENT_NODE : return Type.ELEMENT; case Node.ATTRIBUTE_NODE : return Type.ATTRIBUTE; case Node.TEXT_NODE : return Type.TEXT; default : return Type.NODE; } } /* (non-Javadoc) * @see org.exist.xquery.value.Item#getStringValue() */ public String getStringValue() { int level = document.treeLevel[nodeNumber]; StringBuffer buf = null; int next = nodeNumber + 1; while (next < document.size && document.treeLevel[next] > level) { if (document.nodeKind[next] == Node.TEXT_NODE) { if (buf == null) buf = new StringBuffer(); buf.append( document.characters, document.alpha[next], document.alphaLen[next]); } else if (document.nodeKind[next] == REFERENCE_NODE) { if (buf == null) buf = new StringBuffer(); buf.append(document.references[document.alpha[next]].getStringValue()); } ++next; } return buf == null ? "" : buf.toString(); } /* (non-Javadoc) * @see org.exist.xquery.value.Item#toSequence() */ public Sequence toSequence() { return this; } /* (non-Javadoc) * @see org.exist.xquery.value.Item#convertTo(int) */ public AtomicValue convertTo(int requiredType) throws XPathException { return new StringValue(getStringValue()).convertTo(requiredType); } /* (non-Javadoc) * @see org.exist.xquery.value.Item#atomize() */ public AtomicValue atomize() throws XPathException { return new StringValue(getStringValue()); } /* * Methods of interface Sequence */ /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#add(org.exist.xquery.value.Item) */ public void add(Item item) throws XPathException { } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#addAll(org.exist.xquery.value.Sequence) */ public void addAll(Sequence other) throws XPathException { } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getItemType() */ public int getItemType() { return Type.NODE; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#iterate() */ public SequenceIterator iterate() { return new SingleNodeIterator(this); } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#unorderedIterator() */ public SequenceIterator unorderedIterator() { return new SingleNodeIterator(this); } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getLength() */ public int getLength() { return 1; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getCardinality() */ public int getCardinality() { return Cardinality.EXACTLY_ONE; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#itemAt(int) */ public Item itemAt(int pos) { return pos == 0 ? this : null; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#effectiveBooleanValue() */ public boolean effectiveBooleanValue() throws XPathException { return true; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#toNodeSet() */ public NodeSet toNodeSet() throws XPathException { // throw new XPathException("Querying constructed nodes is not yet implemented"); ValueSequence seq = new ValueSequence(); seq.add(this); return seq.toNodeSet(); } private final static class SingleNodeIterator implements SequenceIterator { NodeImpl node; public SingleNodeIterator(NodeImpl node) { this.node = node; } /* (non-Javadoc) * @see org.exist.xquery.value.SequenceIterator#hasNext() */ public boolean hasNext() { return node != null; } /* (non-Javadoc) * @see org.exist.xquery.value.SequenceIterator#nextItem() */ public Item nextItem() { NodeImpl next = node; node = null; return next; } } /* (non-Javadoc) * @see org.exist.xquery.value.Item#toSAX(org.exist.storage.DBBroker, org.xml.sax.ContentHandler) */ public void toSAX(DBBroker broker, ContentHandler handler) throws SAXException { DOMStreamer streamer = null; try { Serializer serializer = broker.getSerializer(); serializer.reset(); serializer.setProperty(Serializer.GENERATE_DOC_EVENTS, "false"); serializer.setSAXHandlers(handler, null); streamer = SerializerPool.getInstance().borrowDOMStreamer(serializer); streamer.setContentHandler(handler); streamer.serialize(this, false); } catch (Exception e) { SerializerPool.getInstance().returnObject(streamer); e.printStackTrace(); throw new SAXException(e); } } public void copyTo(DBBroker broker, DocumentBuilderReceiver receiver) throws SAXException { document.copyTo(this, receiver); } public void streamTo(Serializer serializer, Receiver receiver) throws SAXException { document.streamTo(serializer, this, receiver); } /* (non-Javadoc) * @see org.exist.xquery.value.Item#conversionPreference(java.lang.Class) */ public int conversionPreference(Class javaClass) { if (javaClass.isAssignableFrom(NodeImpl.class)) return 0; if (javaClass.isAssignableFrom(Node.class)) return 1; if (javaClass == String.class || javaClass == CharSequence.class) return 2; if (javaClass == Character.class || javaClass == char.class) return 2; if (javaClass == Double.class || javaClass == double.class) return 10; if (javaClass == Float.class || javaClass == float.class) return 11; if (javaClass == Long.class || javaClass == long.class) return 12; if (javaClass == Integer.class || javaClass == int.class) return 13; if (javaClass == Short.class || javaClass == short.class) return 14; if (javaClass == Byte.class || javaClass == byte.class) return 15; if (javaClass == Boolean.class || javaClass == boolean.class) return 16; if (javaClass == Object.class) return 20; return Integer.MAX_VALUE; } /* (non-Javadoc) * @see org.exist.xquery.value.Item#toJavaObject(java.lang.Class) */ public Object toJavaObject(Class target) throws XPathException { if (target.isAssignableFrom(NodeImpl.class)) return this; else if (target.isAssignableFrom(Node.class)) return this; else if (target == Object.class) return this; else { StringValue v = new StringValue(getStringValue()); return v.toJavaObject(target); } } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#setSelfAsContext(int) */ public void setSelfAsContext(int contextId) { } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#isCached() */ public boolean isCached() { // always return false return false; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#setIsCached(boolean) */ public void setIsCached(boolean cached) { // ignore } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#removeDuplicates() */ public void removeDuplicates() { // do nothing: this is a single node } /** ? @see org.w3c.dom.Node#getBaseURI() */ public String getBaseURI() { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#compareDocumentPosition(org.w3c.dom.Node) */ public short compareDocumentPosition(Node other) throws DOMException { // maybe TODO - new DOM interfaces - Java 5.0 return 0; } /** ? @see org.w3c.dom.Node#getTextContent() */ public String getTextContent() throws DOMException { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#setTextContent(java.lang.String) */ public void setTextContent(String textContent) throws DOMException { // maybe TODO - new DOM interfaces - Java 5.0 } /** ? @see org.w3c.dom.Node#isSameNode(org.w3c.dom.Node) */ public boolean isSameNode(Node other) { // maybe TODO - new DOM interfaces - Java 5.0 return false; } /** ? @see org.w3c.dom.Node#lookupPrefix(java.lang.String) */ public String lookupPrefix(String namespaceURI) { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#isDefaultNamespace(java.lang.String) */ public boolean isDefaultNamespace(String namespaceURI) { // maybe TODO - new DOM interfaces - Java 5.0 return false; } /** ? @see org.w3c.dom.Node#lookupNamespaceURI(java.lang.String) */ public String lookupNamespaceURI(String prefix) { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#isEqualNode(org.w3c.dom.Node) */ public boolean isEqualNode(Node arg) { // maybe TODO - new DOM interfaces - Java 5.0 return false; } /** ? @see org.w3c.dom.Node#getFeature(java.lang.String, java.lang.String) */ public Object getFeature(String feature, String version) { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#setUserData(java.lang.String, java.lang.Object, org.w3c.dom.UserDataHandler) */ public Object setUserData(String key, Object data, UserDataHandler handler) { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#getUserData(java.lang.String) */ public Object getUserData(String key) { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#isPersistentSet() */ public boolean isPersistentSet() { return false; } public void clearContext(int contextId) { // ignored for in-memory nodes } }
src/org/exist/memtree/NodeImpl.java
/* * eXist Open Source Native XML Database * Copyright (C) 2001-06 Wolfgang M. Meier * [email protected] * http://exist.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.memtree; import org.exist.dom.DocumentSet; import org.exist.dom.NodeListImpl; import org.exist.dom.NodeSet; import org.exist.dom.QName; import org.exist.dom.QNameable; import org.exist.storage.DBBroker; import org.exist.storage.serializers.Serializer; import org.exist.util.serializer.DOMStreamer; import org.exist.util.serializer.Receiver; import org.exist.util.serializer.SerializerPool; import org.exist.xquery.Cardinality; import org.exist.xquery.Constants; import org.exist.xquery.XPathException; import org.exist.xquery.value.AtomicValue; import org.exist.xquery.value.Item; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.StringValue; import org.exist.xquery.value.Type; import org.exist.xquery.value.ValueSequence; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.UserDataHandler; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; public class NodeImpl implements Node, NodeValue, QNameable, Comparable { public final static short REFERENCE_NODE = 100; public final static short NAMESPACE_NODE = 101; protected int nodeNumber; protected DocumentImpl document; public NodeImpl(DocumentImpl doc, int nodeNumber) { this.document = doc; this.nodeNumber = nodeNumber; } public int getNodeNumber() { return nodeNumber; } /* (non-Javadoc) * @see org.exist.xquery.value.NodeValue#getImplementation() */ public int getImplementationType() { return NodeValue.IN_MEMORY_NODE; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getDocumentSet() */ public DocumentSet getDocumentSet() { return DocumentSet.EMPTY_DOCUMENT_SET; } /* (non-Javadoc) * @see org.exist.xquery.value.NodeValue#getNode() */ public Node getNode() { return this; } /* (non-Javadoc) * @see org.w3c.dom.Node#getNodeName() */ public String getNodeName() { switch (getNodeType()) { case Node.DOCUMENT_NODE : return "#document"; case Node.ELEMENT_NODE : case Node.PROCESSING_INSTRUCTION_NODE : QName qn = (QName) document.namePool.get(document.nodeName[nodeNumber]); return qn.toString(); case Node.ATTRIBUTE_NODE: return document.namePool.get(document.attrName[nodeNumber]).toString(); case NodeImpl.NAMESPACE_NODE: return document.namePool.get(document.namespaceCode[nodeNumber]).toString(); case Node.TEXT_NODE : return "#text"; default : return "#unknown"; } } public QName getQName() { switch (getNodeType()) { case Node.DOCUMENT_NODE : return QName.DOCUMENT_QNAME; case Node.ATTRIBUTE_NODE : case Node.ELEMENT_NODE : case Node.PROCESSING_INSTRUCTION_NODE : QName qn = (QName) document.namePool.get(document.nodeName[nodeNumber]); return qn; case Node.COMMENT_NODE: return QName.COMMENT_QNAME; case Node.TEXT_NODE : return QName.TEXT_QNAME; default : return null; } } public void expand() throws DOMException { document.expand(); } public void deepCopy() throws DOMException { DocumentImpl newDoc = document.expandRefs(this); this.nodeNumber = 1; this.document = newDoc; } /* (non-Javadoc) * @see org.w3c.dom.Node#getNodeValue() */ public String getNodeValue() throws DOMException { return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#setNodeValue(java.lang.String) */ public void setNodeValue(String arg0) throws DOMException { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.w3c.dom.Node#getNodeType() */ public short getNodeType() { return document.nodeKind[nodeNumber]; } /* (non-Javadoc) * @see org.w3c.dom.Node#getParentNode() */ public Node getParentNode() { int next = document.next[nodeNumber]; while (next > nodeNumber) { next = document.next[next]; } if (next < 0) return document; return document.getNode(next); } public void addContextNode(int contextId, NodeValue node) { } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if(!(obj instanceof NodeImpl)) return false; return nodeNumber == ((NodeImpl) obj).nodeNumber; } /* (non-Javadoc) * @see org.exist.xquery.value.NodeValue#equals(org.exist.xquery.value.NodeValue) */ public boolean equals(NodeValue other) throws XPathException { if (other.getImplementationType() != NodeValue.IN_MEMORY_NODE) return false; return nodeNumber == ((NodeImpl) other).nodeNumber; } /* (non-Javadoc) * @see org.exist.xquery.value.NodeValue#after(org.exist.xquery.value.NodeValue) */ public boolean after(NodeValue other) throws XPathException { if (other.getImplementationType() != NodeValue.IN_MEMORY_NODE) throw new XPathException("annot compare persistent node with in-memory node"); return nodeNumber < ((NodeImpl) other).nodeNumber; } /* (non-Javadoc) * @see org.exist.xquery.value.NodeValue#before(org.exist.xquery.value.NodeValue) */ public boolean before(NodeValue other) throws XPathException { if (other.getImplementationType() != NodeValue.IN_MEMORY_NODE) throw new XPathException("annot compare persistent node with in-memory node"); return nodeNumber > ((NodeImpl) other).nodeNumber; } public int compareTo(Object other) { if(!(other instanceof NodeImpl)) return Constants.INFERIOR; NodeImpl n = (NodeImpl)other; if(n.document == document) { if (nodeNumber == n.nodeNumber) return Constants.EQUAL; else if (nodeNumber < n.nodeNumber) return Constants.INFERIOR; else return Constants.SUPERIOR; } else return Constants.INFERIOR; } /* (non-Javadoc) * @see org.w3c.dom.Node#getChildNodes() */ public NodeList getChildNodes() { return new NodeListImpl(); } /* (non-Javadoc) * @see org.w3c.dom.Node#getFirstChild() */ public Node getFirstChild() { return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#getLastChild() */ public Node getLastChild() { return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#getPreviousSibling() */ public Node getPreviousSibling() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#getNextSibling() */ public Node getNextSibling() { int nextNr = document.next[nodeNumber]; return nextNr < nodeNumber ? null : document.getNode(nextNr); } /* (non-Javadoc) * @see org.w3c.dom.Node#getAttributes() */ public NamedNodeMap getAttributes() { return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#getOwnerDocument() */ public Document getOwnerDocument() { return document; } public DocumentImpl getDocument() { return document; } /* (non-Javadoc) * @see org.w3c.dom.Node#insertBefore(org.w3c.dom.Node, org.w3c.dom.Node) */ public Node insertBefore(Node arg0, Node arg1) throws DOMException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#replaceChild(org.w3c.dom.Node, org.w3c.dom.Node) */ public Node replaceChild(Node arg0, Node arg1) throws DOMException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#removeChild(org.w3c.dom.Node) */ public Node removeChild(Node arg0) throws DOMException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#appendChild(org.w3c.dom.Node) */ public Node appendChild(Node arg0) throws DOMException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#hasChildNodes() */ public boolean hasChildNodes() { return false; } /* (non-Javadoc) * @see org.w3c.dom.Node#cloneNode(boolean) */ public Node cloneNode(boolean arg0) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.w3c.dom.Node#normalize() */ public void normalize() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.w3c.dom.Node#isSupported(java.lang.String, java.lang.String) */ public boolean isSupported(String arg0, String arg1) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see org.w3c.dom.Node#getNamespaceURI() */ public String getNamespaceURI() { return ""; } /* (non-Javadoc) * @see org.w3c.dom.Node#getPrefix() */ public String getPrefix() { return ""; } /* (non-Javadoc) * @see org.w3c.dom.Node#setPrefix(java.lang.String) */ public void setPrefix(String arg0) throws DOMException { } /* (non-Javadoc) * @see org.w3c.dom.Node#getLocalName() */ public String getLocalName() { return ""; } /* (non-Javadoc) * @see org.w3c.dom.Node#hasAttributes() */ public boolean hasAttributes() { return false; } /* * Methods of interface Item */ /* (non-Javadoc) * @see org.exist.xquery.value.Item#getType() */ public int getType() { int type = getNodeType(); switch (type) { case Node.DOCUMENT_NODE : return Type.DOCUMENT; case Node.COMMENT_NODE : return Type.COMMENT; case Node.PROCESSING_INSTRUCTION_NODE : return Type.PROCESSING_INSTRUCTION; case Node.ELEMENT_NODE : return Type.ELEMENT; case Node.ATTRIBUTE_NODE : return Type.ATTRIBUTE; case Node.TEXT_NODE : return Type.TEXT; default : return Type.NODE; } } /* (non-Javadoc) * @see org.exist.xquery.value.Item#getStringValue() */ public String getStringValue() { int level = document.treeLevel[nodeNumber]; StringBuffer buf = null; int next = nodeNumber + 1; while (next < document.size && document.treeLevel[next] > level) { if (document.nodeKind[next] == Node.TEXT_NODE) { if (buf == null) buf = new StringBuffer(); buf.append( document.characters, document.alpha[next], document.alphaLen[next]); } else if (document.nodeKind[next] == REFERENCE_NODE) { if (buf == null) buf = new StringBuffer(); buf.append(document.references[document.alpha[next]].getStringValue()); } ++next; } return buf == null ? "" : buf.toString(); } /* (non-Javadoc) * @see org.exist.xquery.value.Item#toSequence() */ public Sequence toSequence() { return this; } /* (non-Javadoc) * @see org.exist.xquery.value.Item#convertTo(int) */ public AtomicValue convertTo(int requiredType) throws XPathException { return new StringValue(getStringValue()).convertTo(requiredType); } /* (non-Javadoc) * @see org.exist.xquery.value.Item#atomize() */ public AtomicValue atomize() throws XPathException { return new StringValue(getStringValue()); } /* * Methods of interface Sequence */ /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#add(org.exist.xquery.value.Item) */ public void add(Item item) throws XPathException { } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#addAll(org.exist.xquery.value.Sequence) */ public void addAll(Sequence other) throws XPathException { } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getItemType() */ public int getItemType() { return Type.NODE; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#iterate() */ public SequenceIterator iterate() { return new SingleNodeIterator(this); } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#unorderedIterator() */ public SequenceIterator unorderedIterator() { return new SingleNodeIterator(this); } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getLength() */ public int getLength() { return 1; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getCardinality() */ public int getCardinality() { return Cardinality.EXACTLY_ONE; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#itemAt(int) */ public Item itemAt(int pos) { return pos == 0 ? this : null; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#effectiveBooleanValue() */ public boolean effectiveBooleanValue() throws XPathException { return true; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#toNodeSet() */ public NodeSet toNodeSet() throws XPathException { // throw new XPathException("Querying constructed nodes is not yet implemented"); ValueSequence seq = new ValueSequence(); seq.add(this); return seq.toNodeSet(); } private final static class SingleNodeIterator implements SequenceIterator { NodeImpl node; public SingleNodeIterator(NodeImpl node) { this.node = node; } /* (non-Javadoc) * @see org.exist.xquery.value.SequenceIterator#hasNext() */ public boolean hasNext() { return node != null; } /* (non-Javadoc) * @see org.exist.xquery.value.SequenceIterator#nextItem() */ public Item nextItem() { NodeImpl next = node; node = null; return next; } } /* (non-Javadoc) * @see org.exist.xquery.value.Item#toSAX(org.exist.storage.DBBroker, org.xml.sax.ContentHandler) */ public void toSAX(DBBroker broker, ContentHandler handler) throws SAXException { DOMStreamer streamer = null; try { Serializer serializer = broker.getSerializer(); serializer.reset(); serializer.setProperty(Serializer.GENERATE_DOC_EVENTS, "false"); serializer.setSAXHandlers(handler, null); streamer = SerializerPool.getInstance().borrowDOMStreamer(serializer); streamer.setContentHandler(handler); streamer.serialize(this, false); } catch (Exception e) { SerializerPool.getInstance().returnObject(streamer); e.printStackTrace(); throw new SAXException(e); } } public void copyTo(DBBroker broker, DocumentBuilderReceiver receiver) throws SAXException { document.copyTo(this, receiver); } public void streamTo(Serializer serializer, Receiver receiver) throws SAXException { document.streamTo(serializer, this, receiver); } /* (non-Javadoc) * @see org.exist.xquery.value.Item#conversionPreference(java.lang.Class) */ public int conversionPreference(Class javaClass) { if (javaClass.isAssignableFrom(NodeImpl.class)) return 0; if (javaClass.isAssignableFrom(Node.class)) return 1; if (javaClass == String.class || javaClass == CharSequence.class) return 2; if (javaClass == Character.class || javaClass == char.class) return 2; if (javaClass == Double.class || javaClass == double.class) return 10; if (javaClass == Float.class || javaClass == float.class) return 11; if (javaClass == Long.class || javaClass == long.class) return 12; if (javaClass == Integer.class || javaClass == int.class) return 13; if (javaClass == Short.class || javaClass == short.class) return 14; if (javaClass == Byte.class || javaClass == byte.class) return 15; if (javaClass == Boolean.class || javaClass == boolean.class) return 16; if (javaClass == Object.class) return 20; return Integer.MAX_VALUE; } /* (non-Javadoc) * @see org.exist.xquery.value.Item#toJavaObject(java.lang.Class) */ public Object toJavaObject(Class target) throws XPathException { if (target.isAssignableFrom(NodeImpl.class)) return this; else if (target.isAssignableFrom(Node.class)) return this; else if (target == Object.class) return this; else { StringValue v = new StringValue(getStringValue()); return v.toJavaObject(target); } } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#setSelfAsContext(int) */ public void setSelfAsContext(int contextId) { } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#isCached() */ public boolean isCached() { // always return false return false; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#setIsCached(boolean) */ public void setIsCached(boolean cached) { // ignore } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#removeDuplicates() */ public void removeDuplicates() { // do nothing: this is a single node } /** ? @see org.w3c.dom.Node#getBaseURI() */ public String getBaseURI() { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#compareDocumentPosition(org.w3c.dom.Node) */ public short compareDocumentPosition(Node other) throws DOMException { // maybe TODO - new DOM interfaces - Java 5.0 return 0; } /** ? @see org.w3c.dom.Node#getTextContent() */ public String getTextContent() throws DOMException { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#setTextContent(java.lang.String) */ public void setTextContent(String textContent) throws DOMException { // maybe TODO - new DOM interfaces - Java 5.0 } /** ? @see org.w3c.dom.Node#isSameNode(org.w3c.dom.Node) */ public boolean isSameNode(Node other) { // maybe TODO - new DOM interfaces - Java 5.0 return false; } /** ? @see org.w3c.dom.Node#lookupPrefix(java.lang.String) */ public String lookupPrefix(String namespaceURI) { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#isDefaultNamespace(java.lang.String) */ public boolean isDefaultNamespace(String namespaceURI) { // maybe TODO - new DOM interfaces - Java 5.0 return false; } /** ? @see org.w3c.dom.Node#lookupNamespaceURI(java.lang.String) */ public String lookupNamespaceURI(String prefix) { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#isEqualNode(org.w3c.dom.Node) */ public boolean isEqualNode(Node arg) { // maybe TODO - new DOM interfaces - Java 5.0 return false; } /** ? @see org.w3c.dom.Node#getFeature(java.lang.String, java.lang.String) */ public Object getFeature(String feature, String version) { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#setUserData(java.lang.String, java.lang.Object, org.w3c.dom.UserDataHandler) */ public Object setUserData(String key, Object data, UserDataHandler handler) { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /** ? @see org.w3c.dom.Node#getUserData(java.lang.String) */ public Object getUserData(String key) { // maybe TODO - new DOM interfaces - Java 5.0 return null; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#isPersistentSet() */ public boolean isPersistentSet() { return false; } public void clearContext(int contextId) { // ignored for in-memory nodes } }
Fixed: XQuery update extensions did now insert the wrong content. This was introduced by changes made yesterday. svn path=/trunk/eXist-1.0/; revision=2728
src/org/exist/memtree/NodeImpl.java
Fixed: XQuery update extensions did now insert the wrong content. This was introduced by changes made yesterday.
Java
lgpl-2.1
825b76f4d35215b281be92f279bbb79ed8a42b19
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
/* * jETeL/Clover - Java based ETL application framework. * Created on Mar 26, 2003 * Copyright (C) 2003, 2002 David Pavlis, Wes Maciorowski * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package test.org.jetel; /** * @author maciorowski * @version 1.0 * */ import test.org.jetel.data.DataTestSuite; import test.org.jetel.exception.ExceptionTestSuite; import test.org.jetel.metadata.MetadataTestSuite; import test.org.jetel.util.UtilTestSuite; import junit.framework.*; /** * TestSuite that runs all the sample tests * */ public class AllTests { public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(UtilTestSuite.suite()); suite.addTest(MetadataTestSuite.suite()); suite.addTest(ExceptionTestSuite.suite()); suite.addTest(DataTestSuite.suite()); return suite; } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } }
cloveretl.engine/src/test/org/jetel/AllTests.java
/* * jETeL/Clover - Java based ETL application framework. * Created on Mar 26, 2003 * Copyright (C) 2003, 2002 David Pavlis, Wes Maciorowski * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package test.org.jetel; /** * @author maciorowski * @version 1.0 * */ import test.org.jetel.data.DataTestSuite; import test.org.jetel.metadata.MetadataTestSuite; import test.org.jetel.util.UtilTestSuite; import junit.framework.*; /** * TestSuite that runs all the sample tests * */ public class AllTests { public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(UtilTestSuite.suite()); suite.addTest(MetadataTestSuite.suite()); suite.addTest(DataTestSuite.suite()); return suite; } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } }
no message git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@43 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.engine/src/test/org/jetel/AllTests.java
no message
Java
lgpl-2.1
ad345bdeaefaa872127bf8ed2ca88c83cf0b3f0b
0
adamallo/beast-mcmc,maxbiostat/beast-mcmc,beast-dev/beast-mcmc,maxbiostat/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,maxbiostat/beast-mcmc,maxbiostat/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,maxbiostat/beast-mcmc,maxbiostat/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc
/* * BeastMain.java * * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.app.beast; import beagle.BeagleFlag; import beagle.BeagleInfo; import dr.app.plugin.Plugin; import dr.app.plugin.PluginLoader; import dr.app.util.Arguments; import dr.app.util.Utils; import dr.inference.mcmc.MCMC; import dr.inference.mcmcmc.MCMCMC; import dr.inference.mcmcmc.MCMCMCOptions; import dr.math.MathUtils; import dr.util.ErrorLogHandler; import dr.util.MessageLogHandler; import dr.util.Version; import dr.xml.XMLObjectParser; import dr.xml.XMLParser; import jam.util.IconUtils; import javax.swing.*; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.*; import java.util.logging.*; public class BeastMain { private final static Version version = new BeastVersion(); public static final double DEFAULT_DELTA = 1.0; public static final int DEFAULT_SWAP_CHAIN_EVERY = 100; static class BeastConsoleApp extends jam.console.ConsoleApplication { XMLParser parser = null; public BeastConsoleApp(String nameString, String titleString, String aboutString, javax.swing.Icon icon) throws IOException { super(nameString, titleString, aboutString, icon, false); getDefaultFrame().setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); } public void doStop() { Iterator iter = parser.getThreads(); while (iter.hasNext()) { Thread thread = (Thread) iter.next(); thread.stop(); // http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html } } public void setTitle(String title) { getDefaultFrame().setTitle(title); } } public BeastMain(File inputFile, BeastConsoleApp consoleApp, int maxErrorCount, final boolean verbose, boolean parserWarning, boolean strictXML, List<String> additionalParsers, boolean useMC3, double[] chainTemperatures, int swapChainsEvery) { if (inputFile == null) { throw new RuntimeException("Error: no input file specified"); } String fileName = inputFile.getName(); final Logger infoLogger = Logger.getLogger("dr.app.beast"); try { FileReader fileReader = new FileReader(inputFile); XMLParser parser = new BeastParser(new String[]{fileName}, additionalParsers, verbose, parserWarning, strictXML); if (consoleApp != null) { consoleApp.parser = parser; } // Add a handler to handle warnings and errors. This is a ConsoleHandler // so the messages will go to StdOut.. Logger logger = Logger.getLogger("dr"); Handler messageHandler = new MessageLogHandler(); messageHandler.setFilter(new Filter() { public boolean isLoggable(LogRecord record) { return record.getLevel().intValue() < Level.WARNING.intValue(); } }); logger.addHandler(messageHandler); // Add a handler to handle warnings and errors. This is a ConsoleHandler // so the messages will go to StdErr.. Handler errorHandler = new ConsoleHandler(); errorHandler.setFilter(new Filter() { public boolean isLoggable(LogRecord record) { if (verbose) { return record.getLevel().intValue() >= Level.WARNING.intValue(); } else { return record.getLevel().intValue() >= Level.SEVERE.intValue(); } } }); infoLogger.addHandler(errorHandler); logger.setUseParentHandlers(false); infoLogger.info("Parsing XML file: " + fileName); infoLogger.info(" File encoding: " + fileReader.getEncoding()); // This is a special logger that is for logging numerical and statistical errors // during the MCMC run. It will tolerate up to maxErrorCount before throwing a // RuntimeException to shut down the run. Logger errorLogger = Logger.getLogger("error"); messageHandler = new ErrorLogHandler(maxErrorCount); messageHandler.setLevel(Level.WARNING); errorLogger.addHandler(messageHandler); for (String pluginName : PluginLoader.getAvailablePlugins()) { Plugin plugin = PluginLoader.loadPlugin(pluginName); if (plugin != null) { Set<XMLObjectParser> parserSet = plugin.getParsers(); for (XMLObjectParser pluginParser : parserSet) { parser.addXMLObjectParser(pluginParser); } } } if (!useMC3) { // just parse the file running all threads... parser.parse(fileReader, true); } else { int chainCount = chainTemperatures.length; MCMC[] chains = new MCMC[chainCount]; MCMCMCOptions options = new MCMCMCOptions(chainTemperatures, swapChainsEvery); Logger.getLogger("dr.apps.beast").info("Starting cold chain plus hot chains with temperatures: "); for (int i = 1; i < chainTemperatures.length; i++) { Logger.getLogger("dr.apps.beast").info("Hot Chain " + i + ": " + chainTemperatures[i]); } Logger.getLogger("dr.apps.beast").info("Parsing XML file: " + fileName); // parse the file for the initial cold chain returning the MCMC object chains[0] = (MCMC) parser.parse(fileReader, MCMC.class); if (chains[0] == null) { throw new dr.xml.XMLParseException("BEAST XML file is missing an MCMC element"); } fileReader.close(); chainTemperatures[0] = 1.0; for (int i = 1; i < chainCount; i++) { // parse the file once for each hot chain fileReader = new FileReader(inputFile); // turn off all messages for subsequent reads of the file (they will be the same as the // first time). messageHandler.setLevel(Level.OFF); parser = new BeastParser(new String[]{fileName}, additionalParsers, verbose, parserWarning, strictXML); chains[i] = (MCMC) parser.parse(fileReader, MCMC.class); if (chains[i] == null) { throw new dr.xml.XMLParseException("BEAST XML file is missing an MCMC element"); } fileReader.close(); } // restart messages messageHandler.setLevel(Level.ALL); MCMCMC mc3 = new MCMCMC(chains, options); Thread thread = new Thread(mc3); thread.start(); } } catch (java.io.IOException ioe) { infoLogger.severe("File error: " + ioe.getMessage()); throw new RuntimeException("Terminate"); } catch (org.xml.sax.SAXParseException spe) { if (spe.getMessage() != null && spe.getMessage().equals("Content is not allowed in prolog")) { infoLogger.severe("Parsing error - the input file, " + fileName + ", is not a valid XML file."); } else { infoLogger.severe("Error running file: " + fileName); infoLogger.severe("Parsing error - poorly formed XML (possibly not an XML file):\n" + spe.getMessage()); } throw new RuntimeException("Terminate"); } catch (org.w3c.dom.DOMException dome) { infoLogger.severe("Error running file: " + fileName); infoLogger.severe("Parsing error - poorly formed XML:\n" + dome.getMessage()); throw new RuntimeException("Terminate"); } catch (dr.xml.XMLParseException pxe) { pxe.printStackTrace(System.err); if (pxe.getMessage() != null && pxe.getMessage().equals("Unknown root document element, beauti")) { infoLogger.severe("Error running file: " + fileName); infoLogger.severe( "The file you just tried to run in BEAST is actually a BEAUti document.\n" + "Although this uses XML, it is not a format that BEAST understands.\n" + "These files are used by BEAUti to save and load your settings so that\n" + "you can go back and alter them. To generate a BEAST file you must\n" + "select the 'Generate BEAST File' option, either from the File menu or\n" + "the button at the bottom right of the window."); } else { infoLogger.severe("Parsing error - poorly formed BEAST file, " + fileName + ":\n" + pxe.getMessage()); } throw new RuntimeException("Terminate"); } catch (RuntimeException rex) { if (rex.getMessage() != null && rex.getMessage().startsWith("The initial posterior is zero")) { infoLogger.severe("Error running file: " + fileName); infoLogger.severe( "The initial model is invalid because state has a zero probability.\n\n" + "If the log likelihood of the tree is -Inf, his may be because the\n" + "initial, random tree is so large that it has an extremely bad\n" + "likelihood which is being rounded to zero.\n\n" + "Alternatively, it may be that the product of starting mutation rate\n" + "and tree height is extremely small or extremely large. \n\n" + "Finally, it may be that the initial state is incompatible with\n" + "one or more 'hard' constraints (on monophyly or bounds on parameter\n" + "values. This will result in Priors with zero probability.\n\n" + "The individual components of the posterior are as follows:\n" + rex.getMessage() + "\n" + "For more information go to <http://beast.bio.ed.ac.uk/>."); } else { // This call never returns as another RuntimeException exception is raised by // the error log handler??? infoLogger.warning("Error running file: " + fileName); System.err.println("Fatal exception: " + rex.getMessage()); rex.printStackTrace(System.err); System.err.flush(); } throw new RuntimeException("Terminate"); } catch (Exception ex) { infoLogger.warning("Error running file: " + fileName); infoLogger.severe("Fatal exception: " + ex.getMessage()); System.err.println("Fatal exception: " + ex.getMessage()); ex.printStackTrace(System.err); System.err.flush(); throw new RuntimeException("Terminate"); } } public static void centreLine(String line, int pageWidth) { int n = pageWidth - line.length(); int n1 = n / 2; for (int i = 0; i < n1; i++) { System.out.print(" "); } System.out.println(line); } public static void printTitle() { System.out.println(); centreLine("BEAST " + version.getVersionString() + ", " + version.getDateString(), 60); centreLine("Bayesian Evolutionary Analysis Sampling Trees", 60); for (String creditLine : version.getCredits()) { centreLine(creditLine, 60); } System.out.println(); } public static void printUsage(Arguments arguments) { arguments.printUsage("beast", "[<input-file-name>]"); System.out.println(); System.out.println(" Example: beast test.xml"); System.out.println(" Example: beast -window test.xml"); System.out.println(" Example: beast -help"); System.out.println(); } private static long updateSeedByRank(long seed, int rank) { return seed + 1000 * 1000 * rank; } //Main method public static void main(String[] args) throws java.io.IOException { // There is a major issue with languages that use the comma as a decimal separator. // To ensure compatibility between programs in the package, enforce the US locale. Locale.setDefault(Locale.US); Arguments arguments = new Arguments( new Arguments.Option[]{ new Arguments.Option("verbose", "Give verbose XML parsing messages"), new Arguments.Option("warnings", "Show warning messages about BEAST XML file"), new Arguments.Option("strict", "Fail on non-conforming BEAST XML file"), new Arguments.Option("window", "Provide a console window"), new Arguments.Option("options", "Display an options dialog"), new Arguments.Option("working", "Change working directory to input file's directory"), new Arguments.LongOption("seed", "Specify a random number generator seed"), new Arguments.StringOption("prefix", "PREFIX", "Specify a prefix for all output log filenames"), new Arguments.Option("overwrite", "Allow overwriting of log files"), new Arguments.IntegerOption("errors", "Specify maximum number of numerical errors before stopping"), new Arguments.IntegerOption("threads", "The number of computational threads to use (default auto)"), new Arguments.Option("java", "Use Java only, no native implementations"), new Arguments.RealOption("threshold", 0.0, Double.MAX_VALUE, "Full evaluation test threshold (default 1E-6)"), new Arguments.Option("beagle_off", "Don't use the BEAGLE library"), new Arguments.Option("beagle", "Use BEAGLE library if available (default on)"), new Arguments.Option("beagle_info", "BEAGLE: show information on available resources"), new Arguments.StringOption("beagle_order", "order", "BEAGLE: set order of resource use"), new Arguments.IntegerOption("beagle_instances", "BEAGLE: divide site patterns amongst instances"), new Arguments.Option("beagle_CPU", "BEAGLE: use CPU instance"), new Arguments.Option("beagle_GPU", "BEAGLE: use GPU instance if available"), new Arguments.Option("beagle_SSE", "BEAGLE: use SSE extensions if available"), new Arguments.Option("beagle_SSE_off", "BEAGLE: turn off use of SSE extensions"), new Arguments.Option("beagle_cuda", "BEAGLE: use CUDA parallization if available"), new Arguments.Option("beagle_opencl", "BEAGLE: use OpenCL parallization if available"), new Arguments.Option("beagle_single", "BEAGLE: use single precision if available"), new Arguments.Option("beagle_double", "BEAGLE: use double precision if available"), new Arguments.Option("beagle_async", "BEAGLE: use asynchronous kernels if available"), new Arguments.StringOption("beagle_scaling", new String[]{"default", "dynamic", "delayed", "always", "none"}, false, "BEAGLE: specify scaling scheme to use"), new Arguments.LongOption("beagle_rescale", "BEAGLE: frequency of rescaling (dynamic scaling only)"), new Arguments.Option("mpi", "Use MPI rank to label output"), new Arguments.IntegerOption("mc3_chains", 1, Integer.MAX_VALUE, "number of chains"), new Arguments.RealOption("mc3_delta", 0.0, Double.MAX_VALUE, "temperature increment parameter"), new Arguments.RealArrayOption("mc3_temperatures", -1, "a comma-separated list of the hot chain temperatures"), new Arguments.LongOption("mc3_swap", 1, Integer.MAX_VALUE, "frequency at which chains temperatures will be swapped"), new Arguments.StringOption("load_dump", "FILENAME", "Specify a filename to load a dumped state from"), new Arguments.LongOption("dump_state", "Specify a state at which to write a dump file"), new Arguments.LongOption("dump_every", "Specify a frequency to write a dump file"), new Arguments.Option("version", "Print the version and credits and stop"), new Arguments.Option("help", "Print this information and stop"), }); int argumentCount = 0; try { argumentCount = arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { System.out.println(); System.out.println(ae.getMessage()); System.out.println(); printUsage(arguments); System.exit(1); } if (arguments.hasOption("version")) { printTitle(); } if (arguments.hasOption("help")) { printUsage(arguments); } if (arguments.hasOption("version") || arguments.hasOption("help")) { System.exit(0); } List<String> additionalParsers = new ArrayList<String>(); final boolean verbose = arguments.hasOption("verbose"); final boolean parserWarning = arguments.hasOption("warnings"); // if dev, then auto turn on, otherwise default to turn off final boolean strictXML = arguments.hasOption("strict"); final boolean window = arguments.hasOption("window"); final boolean options = arguments.hasOption("options") || (argumentCount == 0); final boolean working = arguments.hasOption("working"); String fileNamePrefix = null; boolean allowOverwrite = arguments.hasOption("overwrite"); boolean useMPI = arguments.hasOption("mpi"); long seed = MathUtils.getSeed(); boolean useJava = false; if (arguments.hasOption("threshold")) { double evaluationThreshold = arguments.getRealOption("threshold"); System.setProperty("mcmc.evaluation.threshold", Double.toString(evaluationThreshold)); } int threadCount = -1; if (arguments.hasOption("java")) { useJava = true; } if (arguments.hasOption("prefix")) { fileNamePrefix = arguments.getStringOption("prefix"); } // ============= MC^3 settings ============= int chainCount = 1; if (arguments.hasOption("mc3_chains")) { chainCount = arguments.getIntegerOption("mc3_chains"); } else if (arguments.hasOption("mc3_temperatures")) { chainCount = 1 + arguments.getRealArrayOption("mc3_temperatures").length; } double delta = DEFAULT_DELTA; if (arguments.hasOption("mc3_delta")) { if (arguments.hasOption("mc3_temperatures")) { System.err.println("Either the -mc3_delta or the -mc3_temperatures option should be used, not both"); System.err.println(); printUsage(arguments); System.exit(1); } delta = arguments.getRealOption("mc3_delta"); } double[] chainTemperatures = new double[chainCount]; chainTemperatures[0] = 1.0; if (arguments.hasOption("mc3_temperatures")) { double[] hotChainTemperatures = arguments.getRealArrayOption("mc3_temperatures"); assert hotChainTemperatures.length == chainCount - 1; System.arraycopy(hotChainTemperatures, 0, chainTemperatures, 1, chainCount - 1); } else { for (int i = 1; i < chainCount; i++) { chainTemperatures[i] = 1.0 / (1.0 + (delta * i)); } } int swapChainsEvery = DEFAULT_SWAP_CHAIN_EVERY; if (arguments.hasOption("mc3_swap")) { swapChainsEvery = arguments.getIntegerOption("mc3_swap"); } boolean useMC3 = chainCount > 1; // ============= BEAGLE settings ============= long beagleFlags = 0; boolean beagleShowInfo = arguments.hasOption("beagle_info"); // if any beagle flag is specified then use beagle... boolean useBeagle = !arguments.hasOption("beagle_off"); if (arguments.hasOption("beagle_CPU")) { beagleFlags |= BeagleFlag.PROCESSOR_CPU.getMask(); } if (arguments.hasOption("beagle_GPU")) { beagleFlags |= BeagleFlag.PROCESSOR_GPU.getMask(); } if (arguments.hasOption("beagle_cuda")) { beagleFlags |= BeagleFlag.FRAMEWORK_CUDA.getMask(); } if (arguments.hasOption("beagle_opencl")) { beagleFlags |= BeagleFlag.FRAMEWORK_OPENCL.getMask(); } if (!arguments.hasOption("beagle_SSE_off")) { beagleFlags |= BeagleFlag.VECTOR_SSE.getMask(); } // if (arguments.hasOption("beagle_double")) { // beagleFlags |= BeagleFlag.PRECISION_DOUBLE.getMask(); // } if (arguments.hasOption("beagle_single")) { beagleFlags |= BeagleFlag.PRECISION_SINGLE.getMask(); } else { beagleFlags |= BeagleFlag.PRECISION_DOUBLE.getMask(); } if (arguments.hasOption("beagle_async")) { beagleFlags |= BeagleFlag.COMPUTATION_ASYNCH.getMask(); } if (arguments.hasOption("beagle_order")) { System.setProperty("beagle.resource.order", arguments.getStringOption("beagle_order")); } if (arguments.hasOption("beagle_instances")) { System.setProperty("beagle.instance.count", Integer.toString(arguments.getIntegerOption("beagle_instances"))); } if (arguments.hasOption("beagle_scaling")) { System.setProperty("beagle.scaling", arguments.getStringOption("beagle_scaling")); } if (arguments.hasOption("beagle_rescale")) { System.setProperty("beagle.rescale", Long.toString(arguments.getLongOption("beagle_rescale"))); } // ============= Other settings ============= if (arguments.hasOption("threads")) { // threadCount defaults to -1 unless the user specifies an option threadCount = arguments.getIntegerOption("threads"); if (threadCount < 0) { printTitle(); System.err.println("The the number of threads should be >= 0"); System.exit(1); } } if (arguments.hasOption("seed")) { seed = arguments.getLongOption("seed"); if (seed <= 0) { printTitle(); System.err.println("The random number seed should be > 0"); System.exit(1); } } if (arguments.hasOption("load_dump")) { String debugStateFile = arguments.getStringOption("load_dump"); System.setProperty(MCMC.LOAD_DUMP_FILE, debugStateFile); } if (arguments.hasOption("dump_state")) { long debugWriteState = arguments.getLongOption("dump_state"); System.setProperty(MCMC.DUMP_STATE, Long.toString(debugWriteState)); } if (arguments.hasOption("dump_every")) { long debugWriteEvery = arguments.getLongOption("dump_every"); System.setProperty(MCMC.DUMP_EVERY, Long.toString(debugWriteEvery)); } if (useMPI) { String[] nullArgs = new String[0]; try { BeastMPI.Init(nullArgs); } catch (Exception e) { throw new RuntimeException("Unable to access MPI."); } int rank = BeastMPI.COMM_WORLD.Rank(); System.setProperty("mpi.rank.postfix", String.valueOf(rank)); } String rankProp = System.getProperty("mpi.rank.postfix"); if (rankProp != null) { int rank = Integer.valueOf(rankProp); seed = updateSeedByRank(seed, rank); } int maxErrorCount = 0; if (arguments.hasOption("errors")) { maxErrorCount = arguments.getIntegerOption("errors"); if (maxErrorCount < 0) { maxErrorCount = 0; } } BeastConsoleApp consoleApp = null; String nameString = "BEAST " + version.getVersionString(); if (window) { System.setProperty("com.apple.macos.useScreenMenuBar", "true"); System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("apple.awt.showGrowBox", "true"); javax.swing.Icon icon = IconUtils.getIcon(BeastMain.class, "images/beast.png"); String titleString = "<html>" + "<div style=\"font: HelveticaNeue, Helvetica, Arial, sans-serif\">" + "<p style=\"font-weight: 100; font-size: 42px\">BEAST</p>" + "<p style=\"font-weight: 200; font-size: 12px\">Bayesian Evolutionary Analysis Sampling Trees</p>" + "<p style=\"font-weight: 300; font-size: 11px\">Version " + version.getVersionString() + ", " + version.getDateString() + "</p>" + "</div></html>"; String aboutString = "<html>" + "<div style=\"font-family:HelveticaNeue-Light, 'Helvetica Neue Light', Helvetica, Arial, 'Lucida Grande',sans-serif; font-weight: 100\">" + "<center>" + version.getHTMLCredits() + "</div></center></div></html>"; consoleApp = new BeastConsoleApp(nameString, titleString, aboutString, icon); consoleApp.initialize(); } printTitle(); File inputFile = null; if (options && !beagleShowInfo) { String titleString = "<html>" + "<div style=\"font: HelveticaNeue, Helvetica, Arial, sans-serif\">" + "<p style=\"font-weight: 100; font-size: 42px\">BEAST</p>" + "<p style=\"font-weight: 200; font-size: 12px\">Bayesian Evolutionary Analysis Sampling Trees</p>" + "<p style=\"font-weight: 300; font-size: 11px\">Version " + version.getVersionString() + ", " + version.getDateString() + "</p>" + "</div></html>"; javax.swing.Icon icon = IconUtils.getIcon(BeastMain.class, "images/beast.png"); BeastDialog dialog = new BeastDialog(new JFrame(), titleString, icon); dialog.setAllowOverwrite(allowOverwrite); dialog.setSeed(seed); dialog.setUseBeagle(useBeagle); if (BeagleFlag.PROCESSOR_GPU.isSet(beagleFlags)) { dialog.setPreferBeagleGPU(); } dialog.setPreferBeagleSSE(BeagleFlag.VECTOR_SSE.isSet(beagleFlags)); if (BeagleFlag.PRECISION_SINGLE.isSet(beagleFlags)) { dialog.setPreferBeagleSingle(); } if (!dialog.showDialog(nameString)) { return; } if (dialog.allowOverwrite()) { allowOverwrite = true; } seed = dialog.getSeed(); threadCount = dialog.getThreadPoolSize(); useBeagle = dialog.useBeagle(); if (useBeagle) { beagleShowInfo = dialog.showBeagleInfo(); if (dialog.preferBeagleCPU()) { beagleFlags |= BeagleFlag.PROCESSOR_CPU.getMask(); } if (dialog.preferBeagleSSE()) { beagleFlags |= BeagleFlag.VECTOR_SSE.getMask(); } else { beagleFlags &= ~BeagleFlag.VECTOR_SSE.getMask(); } if (dialog.preferBeagleGPU()) { beagleFlags |= BeagleFlag.PROCESSOR_GPU.getMask(); } if (dialog.preferBeagleDouble()) { beagleFlags |= BeagleFlag.PRECISION_DOUBLE.getMask(); } if (dialog.preferBeagleSingle()) { beagleFlags |= BeagleFlag.PRECISION_SINGLE.getMask(); } System.setProperty("beagle.scaling", dialog.scalingScheme()); } inputFile = dialog.getInputFile(); if (!beagleShowInfo && inputFile == null) { System.err.println("No input file specified"); return; } } if (useBeagle) { BeagleInfo.printVersionInformation(); if (BeagleInfo.getVersion().startsWith("1.")) { System.err.println("WARNING: You are currenly using BEAGLE v1.x. For best performance and compatibility\n" + "with models in BEAST, please upgrade to BEAGLE v2.x at http://github.com/beagle-dev/beagle-lib/\n"); } } if (beagleShowInfo) { BeagleInfo.printResourceList(); return; } if (inputFile == null) { String[] args2 = arguments.getLeftoverArguments(); if (args2.length > 1) { System.err.println("Unknown option: " + args2[1]); System.err.println(); printUsage(arguments); return; } String inputFileName = null; if (args2.length > 0) { inputFileName = args2[0]; inputFile = new File(inputFileName); } if (inputFileName == null) { // No input file name was given so throw up a dialog box... inputFile = Utils.getLoadFile("BEAST " + version.getVersionString() + " - Select XML input file"); } } if (inputFile != null && inputFile.getParent() != null && working) { System.setProperty("user.dir", inputFile.getParent()); } if (window) { if (inputFile == null) { consoleApp.setTitle("null"); } else { consoleApp.setTitle(inputFile.getName()); } } if (useJava) { System.setProperty("java.only", "true"); } if (fileNamePrefix != null && fileNamePrefix.trim().length() > 0) { System.setProperty("file.name.prefix", fileNamePrefix.trim()); } if (allowOverwrite) { System.setProperty("log.allow.overwrite", "true"); } if (useBeagle) { additionalParsers.add("beagle"); } if (beagleFlags != 0) { System.setProperty("beagle.preferred.flags", Long.toString(beagleFlags)); } if (threadCount >= 0) { System.setProperty("thread.count", String.valueOf(threadCount)); } MathUtils.setSeed(seed); System.out.println(); System.out.println("Random number seed: " + seed); System.out.println(); try { new BeastMain(inputFile, consoleApp, maxErrorCount, verbose, parserWarning, strictXML, additionalParsers, useMC3, chainTemperatures, swapChainsEvery); } catch (RuntimeException rte) { rte.printStackTrace(System.err); if (window) { System.out.println(); System.out.println("BEAST has terminated with an error. Please select QUIT from the menu."); // logger.severe will throw a RTE but we want to keep the console visible } else { System.out.flush(); System.err.flush(); System.exit(1); } } if (useMPI) { BeastMPI.Finalize(); } if (!window) { System.exit(0); } } }
src/dr/app/beast/BeastMain.java
/* * BeastMain.java * * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.app.beast; import beagle.BeagleFlag; import beagle.BeagleInfo; import dr.app.plugin.Plugin; import dr.app.plugin.PluginLoader; import dr.app.util.Arguments; import dr.app.util.Utils; import dr.inference.mcmc.MCMC; import dr.inference.mcmcmc.MCMCMC; import dr.inference.mcmcmc.MCMCMCOptions; import dr.math.MathUtils; import dr.util.ErrorLogHandler; import dr.util.MessageLogHandler; import dr.util.Version; import dr.xml.XMLObjectParser; import dr.xml.XMLParser; import jam.util.IconUtils; import javax.swing.*; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.*; import java.util.logging.*; public class BeastMain { private final static Version version = new BeastVersion(); public static final double DEFAULT_DELTA = 1.0; public static final int DEFAULT_SWAP_CHAIN_EVERY = 100; static class BeastConsoleApp extends jam.console.ConsoleApplication { XMLParser parser = null; public BeastConsoleApp(String nameString, String titleString, String aboutString, javax.swing.Icon icon) throws IOException { super(nameString, titleString, aboutString, icon, false); getDefaultFrame().setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); } public void doStop() { Iterator iter = parser.getThreads(); while (iter.hasNext()) { Thread thread = (Thread) iter.next(); thread.stop(); // http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html } } public void setTitle(String title) { getDefaultFrame().setTitle(title); } } public BeastMain(File inputFile, BeastConsoleApp consoleApp, int maxErrorCount, final boolean verbose, boolean parserWarning, boolean strictXML, List<String> additionalParsers, boolean useMC3, double[] chainTemperatures, int swapChainsEvery) { if (inputFile == null) { throw new RuntimeException("Error: no input file specified"); } String fileName = inputFile.getName(); final Logger infoLogger = Logger.getLogger("dr.app.beast"); try { FileReader fileReader = new FileReader(inputFile); XMLParser parser = new BeastParser(new String[]{fileName}, additionalParsers, verbose, parserWarning, strictXML); if (consoleApp != null) { consoleApp.parser = parser; } // Add a handler to handle warnings and errors. This is a ConsoleHandler // so the messages will go to StdOut.. Logger logger = Logger.getLogger("dr"); Handler messageHandler = new MessageLogHandler(); messageHandler.setFilter(new Filter() { public boolean isLoggable(LogRecord record) { return record.getLevel().intValue() < Level.WARNING.intValue(); } }); logger.addHandler(messageHandler); // Add a handler to handle warnings and errors. This is a ConsoleHandler // so the messages will go to StdErr.. Handler errorHandler = new ConsoleHandler(); errorHandler.setFilter(new Filter() { public boolean isLoggable(LogRecord record) { if (verbose) { return record.getLevel().intValue() >= Level.WARNING.intValue(); } else { return record.getLevel().intValue() >= Level.SEVERE.intValue(); } } }); infoLogger.addHandler(errorHandler); logger.setUseParentHandlers(false); infoLogger.info("Parsing XML file: " + fileName); infoLogger.info(" File encoding: " + fileReader.getEncoding()); // This is a special logger that is for logging numerical and statistical errors // during the MCMC run. It will tolerate up to maxErrorCount before throwing a // RuntimeException to shut down the run. Logger errorLogger = Logger.getLogger("error"); messageHandler = new ErrorLogHandler(maxErrorCount); messageHandler.setLevel(Level.WARNING); errorLogger.addHandler(messageHandler); for (String pluginName : PluginLoader.getAvailablePlugins()) { Plugin plugin = PluginLoader.loadPlugin(pluginName); if (plugin != null) { Set<XMLObjectParser> parserSet = plugin.getParsers(); for (XMLObjectParser pluginParser : parserSet) { parser.addXMLObjectParser(pluginParser); } } } if (!useMC3) { // just parse the file running all threads... parser.parse(fileReader, true); } else { int chainCount = chainTemperatures.length; MCMC[] chains = new MCMC[chainCount]; MCMCMCOptions options = new MCMCMCOptions(chainTemperatures, swapChainsEvery); Logger.getLogger("dr.apps.beast").info("Starting cold chain plus hot chains with temperatures: "); for (int i = 1; i < chainTemperatures.length; i++) { Logger.getLogger("dr.apps.beast").info("Hot Chain " + i + ": " + chainTemperatures[i]); } Logger.getLogger("dr.apps.beast").info("Parsing XML file: " + fileName); // parse the file for the initial cold chain returning the MCMC object chains[0] = (MCMC) parser.parse(fileReader, MCMC.class); if (chains[0] == null) { throw new dr.xml.XMLParseException("BEAST XML file is missing an MCMC element"); } fileReader.close(); chainTemperatures[0] = 1.0; for (int i = 1; i < chainCount; i++) { // parse the file once for each hot chain fileReader = new FileReader(inputFile); // turn off all messages for subsequent reads of the file (they will be the same as the // first time). messageHandler.setLevel(Level.OFF); parser = new BeastParser(new String[]{fileName}, additionalParsers, verbose, parserWarning, strictXML); chains[i] = (MCMC) parser.parse(fileReader, MCMC.class); if (chains[i] == null) { throw new dr.xml.XMLParseException("BEAST XML file is missing an MCMC element"); } fileReader.close(); } // restart messages messageHandler.setLevel(Level.ALL); MCMCMC mc3 = new MCMCMC(chains, options); Thread thread = new Thread(mc3); thread.start(); } } catch (java.io.IOException ioe) { infoLogger.severe("File error: " + ioe.getMessage()); throw new RuntimeException("Terminate"); } catch (org.xml.sax.SAXParseException spe) { if (spe.getMessage() != null && spe.getMessage().equals("Content is not allowed in prolog")) { infoLogger.severe("Parsing error - the input file, " + fileName + ", is not a valid XML file."); } else { infoLogger.severe("Error running file: " + fileName); infoLogger.severe("Parsing error - poorly formed XML (possibly not an XML file):\n" + spe.getMessage()); } throw new RuntimeException("Terminate"); } catch (org.w3c.dom.DOMException dome) { infoLogger.severe("Error running file: " + fileName); infoLogger.severe("Parsing error - poorly formed XML:\n" + dome.getMessage()); throw new RuntimeException("Terminate"); } catch (dr.xml.XMLParseException pxe) { pxe.printStackTrace(System.err); if (pxe.getMessage() != null && pxe.getMessage().equals("Unknown root document element, beauti")) { infoLogger.severe("Error running file: " + fileName); infoLogger.severe( "The file you just tried to run in BEAST is actually a BEAUti document.\n" + "Although this uses XML, it is not a format that BEAST understands.\n" + "These files are used by BEAUti to save and load your settings so that\n" + "you can go back and alter them. To generate a BEAST file you must\n" + "select the 'Generate BEAST File' option, either from the File menu or\n" + "the button at the bottom right of the window."); } else { infoLogger.severe("Parsing error - poorly formed BEAST file, " + fileName + ":\n" + pxe.getMessage()); } throw new RuntimeException("Terminate"); } catch (RuntimeException rex) { if (rex.getMessage() != null && rex.getMessage().startsWith("The initial posterior is zero")) { infoLogger.severe("Error running file: " + fileName); infoLogger.severe( "The initial model is invalid because state has a zero probability.\n\n" + "If the log likelihood of the tree is -Inf, his may be because the\n" + "initial, random tree is so large that it has an extremely bad\n" + "likelihood which is being rounded to zero.\n\n" + "Alternatively, it may be that the product of starting mutation rate\n" + "and tree height is extremely small or extremely large. \n\n" + "Finally, it may be that the initial state is incompatible with\n" + "one or more 'hard' constraints (on monophyly or bounds on parameter\n" + "values. This will result in Priors with zero probability.\n\n" + "The individual components of the posterior are as follows:\n" + rex.getMessage() + "\n" + "For more information go to <http://beast.bio.ed.ac.uk/>."); } else { // This call never returns as another RuntimeException exception is raised by // the error log handler??? infoLogger.warning("Error running file: " + fileName); System.err.println("Fatal exception: " + rex.getMessage()); rex.printStackTrace(System.err); System.err.flush(); } throw new RuntimeException("Terminate"); } catch (Exception ex) { infoLogger.warning("Error running file: " + fileName); infoLogger.severe("Fatal exception: " + ex.getMessage()); System.err.println("Fatal exception: " + ex.getMessage()); ex.printStackTrace(System.err); System.err.flush(); throw new RuntimeException("Terminate"); } } public static void centreLine(String line, int pageWidth) { int n = pageWidth - line.length(); int n1 = n / 2; for (int i = 0; i < n1; i++) { System.out.print(" "); } System.out.println(line); } public static void printTitle() { System.out.println(); centreLine("BEAST " + version.getVersionString() + ", " + version.getDateString(), 60); centreLine("Bayesian Evolutionary Analysis Sampling Trees", 60); for (String creditLine : version.getCredits()) { centreLine(creditLine, 60); } System.out.println(); } public static void printUsage(Arguments arguments) { arguments.printUsage("beast", "[<input-file-name>]"); System.out.println(); System.out.println(" Example: beast test.xml"); System.out.println(" Example: beast -window test.xml"); System.out.println(" Example: beast -help"); System.out.println(); } private static long updateSeedByRank(long seed, int rank) { return seed + 1000 * 1000 * rank; } //Main method public static void main(String[] args) throws java.io.IOException { // There is a major issue with languages that use the comma as a decimal separator. // To ensure compatibility between programs in the package, enforce the US locale. Locale.setDefault(Locale.US); Arguments arguments = new Arguments( new Arguments.Option[]{ new Arguments.Option("verbose", "Give verbose XML parsing messages"), new Arguments.Option("warnings", "Show warning messages about BEAST XML file"), new Arguments.Option("strict", "Fail on non-conforming BEAST XML file"), new Arguments.Option("window", "Provide a console window"), new Arguments.Option("options", "Display an options dialog"), new Arguments.Option("working", "Change working directory to input file's directory"), new Arguments.LongOption("seed", "Specify a random number generator seed"), new Arguments.StringOption("prefix", "PREFIX", "Specify a prefix for all output log filenames"), new Arguments.Option("overwrite", "Allow overwriting of log files"), new Arguments.IntegerOption("errors", "Specify maximum number of numerical errors before stopping"), new Arguments.IntegerOption("threads", "The number of computational threads to use (default auto)"), new Arguments.Option("java", "Use Java only, no native implementations"), new Arguments.RealOption("threshold", 0.0, Double.MAX_VALUE, "Full evaluation test threshold (default 1E-6)"), new Arguments.Option("beagle_off", "Don't use the BEAGLE library"), new Arguments.Option("beagle", "Use BEAGLE library if available (default on)"), new Arguments.Option("beagle_info", "BEAGLE: show information on available resources"), new Arguments.StringOption("beagle_order", "order", "BEAGLE: set order of resource use"), new Arguments.IntegerOption("beagle_instances", "BEAGLE: divide site patterns amongst instances"), new Arguments.Option("beagle_CPU", "BEAGLE: use CPU instance"), new Arguments.Option("beagle_GPU", "BEAGLE: use GPU instance if available"), new Arguments.Option("beagle_SSE", "BEAGLE: use SSE extensions if available"), new Arguments.Option("beagle_SSE_off", "BEAGLE: turn off use of SSE extensions"), new Arguments.Option("beagle_cuda", "BEAGLE: use CUDA parallization if available"), new Arguments.Option("beagle_opencl", "BEAGLE: use OpenCL parallization if available"), new Arguments.Option("beagle_single", "BEAGLE: use single precision if available"), new Arguments.Option("beagle_double", "BEAGLE: use double precision if available"), new Arguments.Option("beagle_async", "BEAGLE: use asynchronous kernels if available"), new Arguments.StringOption("beagle_scaling", new String[]{"default", "dynamic", "delayed", "always", "none"}, false, "BEAGLE: specify scaling scheme to use"), new Arguments.LongOption("beagle_rescale", "BEAGLE: frequency of rescaling (dynamic scaling only)"), new Arguments.Option("mpi", "Use MPI rank to label output"), new Arguments.IntegerOption("mc3_chains", 1, Integer.MAX_VALUE, "number of chains"), new Arguments.RealOption("mc3_delta", 0.0, Double.MAX_VALUE, "temperature increment parameter"), new Arguments.RealArrayOption("mc3_temperatures", -1, "a comma-separated list of the hot chain temperatures"), new Arguments.LongOption("mc3_swap", 1, Integer.MAX_VALUE, "frequency at which chains temperatures will be swapped"), new Arguments.StringOption("load_dump", "FILENAME", "Specify a filename to load a dumped state from"), new Arguments.LongOption("dump_state", "Specify a state at which to write a dump file"), new Arguments.LongOption("dump_every", "Specify a frequency to write a dump file"), new Arguments.Option("version", "Print the version and credits and stop"), new Arguments.Option("help", "Print this information and stop"), }); int argumentCount = 0; try { argumentCount = arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { System.out.println(); System.out.println(ae.getMessage()); System.out.println(); printUsage(arguments); System.exit(1); } if (arguments.hasOption("version")) { printTitle(); } if (arguments.hasOption("help")) { printUsage(arguments); } if (arguments.hasOption("version") || arguments.hasOption("help")) { System.exit(0); } List<String> additionalParsers = new ArrayList<String>(); final boolean verbose = arguments.hasOption("verbose"); final boolean parserWarning = arguments.hasOption("warnings"); // if dev, then auto turn on, otherwise default to turn off final boolean strictXML = arguments.hasOption("strict"); final boolean window = arguments.hasOption("window"); final boolean options = arguments.hasOption("options") || (argumentCount == 0); final boolean working = arguments.hasOption("working"); String fileNamePrefix = null; boolean allowOverwrite = arguments.hasOption("overwrite"); boolean useMPI = arguments.hasOption("mpi"); long seed = MathUtils.getSeed(); boolean useJava = false; if (arguments.hasOption("threshold")) { double evaluationThreshold = arguments.getRealOption("threshold"); System.setProperty("mcmc.evaluation.threshold", Double.toString(evaluationThreshold)); } int threadCount = -1; if (arguments.hasOption("java")) { useJava = true; } if (arguments.hasOption("prefix")) { fileNamePrefix = arguments.getStringOption("prefix"); } // ============= MC^3 settings ============= int chainCount = 1; if (arguments.hasOption("mc3_chains")) { chainCount = arguments.getIntegerOption("mc3_chains"); } else if (arguments.hasOption("mc3_temperatures")) { chainCount = 1 + arguments.getRealArrayOption("mc3_temperatures").length; } double delta = DEFAULT_DELTA; if (arguments.hasOption("mc3_delta")) { if (arguments.hasOption("mc3_temperatures")) { System.err.println("Either the -mc3_delta or the -mc3_temperatures option should be used, not both"); System.err.println(); printUsage(arguments); System.exit(1); } delta = arguments.getRealOption("mc3_delta"); } double[] chainTemperatures = new double[chainCount]; chainTemperatures[0] = 1.0; if (arguments.hasOption("mc3_temperatures")) { double[] hotChainTemperatures = arguments.getRealArrayOption("mc3_temperatures"); assert hotChainTemperatures.length == chainCount - 1; System.arraycopy(hotChainTemperatures, 0, chainTemperatures, 1, chainCount - 1); } else { for (int i = 1; i < chainCount; i++) { chainTemperatures[i] = 1.0 / (1.0 + (delta * i)); } } int swapChainsEvery = DEFAULT_SWAP_CHAIN_EVERY; if (arguments.hasOption("mc3_swap")) { swapChainsEvery = arguments.getIntegerOption("mc3_swap"); } boolean useMC3 = chainCount > 1; // ============= BEAGLE settings ============= long beagleFlags = 0; boolean beagleShowInfo = arguments.hasOption("beagle_info"); // if any beagle flag is specified then use beagle... boolean useBeagle = !arguments.hasOption("beagle_off"); if (arguments.hasOption("beagle_CPU")) { beagleFlags |= BeagleFlag.PROCESSOR_CPU.getMask(); } if (arguments.hasOption("beagle_GPU")) { beagleFlags |= BeagleFlag.PROCESSOR_GPU.getMask(); } if (arguments.hasOption("beagle_cuda")) { beagleFlags |= BeagleFlag.FRAMEWORK_CUDA.getMask(); } if (arguments.hasOption("beagle_opencl")) { beagleFlags |= BeagleFlag.FRAMEWORK_OPENCL.getMask(); } if (!arguments.hasOption("beagle_SSE_off")) { beagleFlags |= BeagleFlag.VECTOR_SSE.getMask(); } // if (arguments.hasOption("beagle_double")) { // beagleFlags |= BeagleFlag.PRECISION_DOUBLE.getMask(); // } if (arguments.hasOption("beagle_single")) { beagleFlags |= BeagleFlag.PRECISION_SINGLE.getMask(); } else { beagleFlags |= BeagleFlag.PRECISION_DOUBLE.getMask(); } if (arguments.hasOption("beagle_async")) { beagleFlags |= BeagleFlag.COMPUTATION_ASYNCH.getMask(); } if (arguments.hasOption("beagle_order")) { System.setProperty("beagle.resource.order", arguments.getStringOption("beagle_order")); } if (arguments.hasOption("beagle_instances")) { System.setProperty("beagle.instance.count", Integer.toString(arguments.getIntegerOption("beagle_instances"))); } if (arguments.hasOption("beagle_scaling")) { System.setProperty("beagle.scaling", arguments.getStringOption("beagle_scaling")); } if (arguments.hasOption("beagle_rescale")) { System.setProperty("beagle.rescale", Integer.toString(arguments.getIntegerOption("beagle_rescale"))); } // ============= Other settings ============= if (arguments.hasOption("threads")) { // threadCount defaults to -1 unless the user specifies an option threadCount = arguments.getIntegerOption("threads"); if (threadCount < 0) { printTitle(); System.err.println("The the number of threads should be >= 0"); System.exit(1); } } if (arguments.hasOption("seed")) { seed = arguments.getLongOption("seed"); if (seed <= 0) { printTitle(); System.err.println("The random number seed should be > 0"); System.exit(1); } } if (arguments.hasOption("load_dump")) { String debugStateFile = arguments.getStringOption("load_dump"); System.setProperty(MCMC.LOAD_DUMP_FILE, debugStateFile); } if (arguments.hasOption("dump_state")) { long debugWriteState = arguments.getLongOption("dump_state"); System.setProperty(MCMC.DUMP_STATE, Long.toString(debugWriteState)); } if (arguments.hasOption("dump_every")) { long debugWriteEvery = arguments.getLongOption("dump_every"); System.setProperty(MCMC.DUMP_EVERY, Long.toString(debugWriteEvery)); } if (useMPI) { String[] nullArgs = new String[0]; try { BeastMPI.Init(nullArgs); } catch (Exception e) { throw new RuntimeException("Unable to access MPI."); } int rank = BeastMPI.COMM_WORLD.Rank(); System.setProperty("mpi.rank.postfix", String.valueOf(rank)); } String rankProp = System.getProperty("mpi.rank.postfix"); if (rankProp != null) { int rank = Integer.valueOf(rankProp); seed = updateSeedByRank(seed, rank); } int maxErrorCount = 0; if (arguments.hasOption("errors")) { maxErrorCount = arguments.getIntegerOption("errors"); if (maxErrorCount < 0) { maxErrorCount = 0; } } BeastConsoleApp consoleApp = null; String nameString = "BEAST " + version.getVersionString(); if (window) { System.setProperty("com.apple.macos.useScreenMenuBar", "true"); System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("apple.awt.showGrowBox", "true"); javax.swing.Icon icon = IconUtils.getIcon(BeastMain.class, "images/beast.png"); String titleString = "<html>" + "<div style=\"font: HelveticaNeue, Helvetica, Arial, sans-serif\">" + "<p style=\"font-weight: 100; font-size: 42px\">BEAST</p>" + "<p style=\"font-weight: 200; font-size: 12px\">Bayesian Evolutionary Analysis Sampling Trees</p>" + "<p style=\"font-weight: 300; font-size: 11px\">Version " + version.getVersionString() + ", " + version.getDateString() + "</p>" + "</div></html>"; String aboutString = "<html>" + "<div style=\"font-family:HelveticaNeue-Light, 'Helvetica Neue Light', Helvetica, Arial, 'Lucida Grande',sans-serif; font-weight: 100\">" + "<center>" + version.getHTMLCredits() + "</div></center></div></html>"; consoleApp = new BeastConsoleApp(nameString, titleString, aboutString, icon); consoleApp.initialize(); } printTitle(); File inputFile = null; if (options && !beagleShowInfo) { String titleString = "<html>" + "<div style=\"font: HelveticaNeue, Helvetica, Arial, sans-serif\">" + "<p style=\"font-weight: 100; font-size: 42px\">BEAST</p>" + "<p style=\"font-weight: 200; font-size: 12px\">Bayesian Evolutionary Analysis Sampling Trees</p>" + "<p style=\"font-weight: 300; font-size: 11px\">Version " + version.getVersionString() + ", " + version.getDateString() + "</p>" + "</div></html>"; javax.swing.Icon icon = IconUtils.getIcon(BeastMain.class, "images/beast.png"); BeastDialog dialog = new BeastDialog(new JFrame(), titleString, icon); dialog.setAllowOverwrite(allowOverwrite); dialog.setSeed(seed); dialog.setUseBeagle(useBeagle); if (BeagleFlag.PROCESSOR_GPU.isSet(beagleFlags)) { dialog.setPreferBeagleGPU(); } dialog.setPreferBeagleSSE(BeagleFlag.VECTOR_SSE.isSet(beagleFlags)); if (BeagleFlag.PRECISION_SINGLE.isSet(beagleFlags)) { dialog.setPreferBeagleSingle(); } if (!dialog.showDialog(nameString)) { return; } if (dialog.allowOverwrite()) { allowOverwrite = true; } seed = dialog.getSeed(); threadCount = dialog.getThreadPoolSize(); useBeagle = dialog.useBeagle(); if (useBeagle) { beagleShowInfo = dialog.showBeagleInfo(); if (dialog.preferBeagleCPU()) { beagleFlags |= BeagleFlag.PROCESSOR_CPU.getMask(); } if (dialog.preferBeagleSSE()) { beagleFlags |= BeagleFlag.VECTOR_SSE.getMask(); } else { beagleFlags &= ~BeagleFlag.VECTOR_SSE.getMask(); } if (dialog.preferBeagleGPU()) { beagleFlags |= BeagleFlag.PROCESSOR_GPU.getMask(); } if (dialog.preferBeagleDouble()) { beagleFlags |= BeagleFlag.PRECISION_DOUBLE.getMask(); } if (dialog.preferBeagleSingle()) { beagleFlags |= BeagleFlag.PRECISION_SINGLE.getMask(); } System.setProperty("beagle.scaling", dialog.scalingScheme()); } inputFile = dialog.getInputFile(); if (!beagleShowInfo && inputFile == null) { System.err.println("No input file specified"); return; } } if (useBeagle) { BeagleInfo.printVersionInformation(); if (BeagleInfo.getVersion().startsWith("1.")) { System.err.println("WARNING: You are currenly using BEAGLE v1.x. For best performance and compatibility\n" + "with models in BEAST, please upgrade to BEAGLE v2.x at http://github.com/beagle-dev/beagle-lib/\n"); } } if (beagleShowInfo) { BeagleInfo.printResourceList(); return; } if (inputFile == null) { String[] args2 = arguments.getLeftoverArguments(); if (args2.length > 1) { System.err.println("Unknown option: " + args2[1]); System.err.println(); printUsage(arguments); return; } String inputFileName = null; if (args2.length > 0) { inputFileName = args2[0]; inputFile = new File(inputFileName); } if (inputFileName == null) { // No input file name was given so throw up a dialog box... inputFile = Utils.getLoadFile("BEAST " + version.getVersionString() + " - Select XML input file"); } } if (inputFile != null && inputFile.getParent() != null && working) { System.setProperty("user.dir", inputFile.getParent()); } if (window) { if (inputFile == null) { consoleApp.setTitle("null"); } else { consoleApp.setTitle(inputFile.getName()); } } if (useJava) { System.setProperty("java.only", "true"); } if (fileNamePrefix != null && fileNamePrefix.trim().length() > 0) { System.setProperty("file.name.prefix", fileNamePrefix.trim()); } if (allowOverwrite) { System.setProperty("log.allow.overwrite", "true"); } if (useBeagle) { additionalParsers.add("beagle"); } if (beagleFlags != 0) { System.setProperty("beagle.preferred.flags", Long.toString(beagleFlags)); } if (threadCount >= 0) { System.setProperty("thread.count", String.valueOf(threadCount)); } MathUtils.setSeed(seed); System.out.println(); System.out.println("Random number seed: " + seed); System.out.println(); try { new BeastMain(inputFile, consoleApp, maxErrorCount, verbose, parserWarning, strictXML, additionalParsers, useMC3, chainTemperatures, swapChainsEvery); } catch (RuntimeException rte) { rte.printStackTrace(System.err); if (window) { System.out.println(); System.out.println("BEAST has terminated with an error. Please select QUIT from the menu."); // logger.severe will throw a RTE but we want to keep the console visible } else { System.out.flush(); System.err.flush(); System.exit(1); } } if (useMPI) { BeastMPI.Finalize(); } if (!window) { System.exit(0); } } }
Long option was being typecast to an Integer option
src/dr/app/beast/BeastMain.java
Long option was being typecast to an Integer option
Java
apache-2.0
9ae5b3e033afa7c8f2992e8228b529db03f40dad
0
gradle/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,robinverduijn/gradle,blindpirate/gradle,gstevey/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,gradle/gradle,gstevey/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,gstevey/gradle,gstevey/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,gstevey/gradle,robinverduijn/gradle,gradle/gradle,lsmaira/gradle,blindpirate/gradle,gstevey/gradle,robinverduijn/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle
/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api; import groovy.lang.Closure; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.plugins.resolver.DependencyResolver; import org.apache.ivy.plugins.resolver.FileSystemResolver; import org.apache.ivy.plugins.resolver.RepositoryResolver; import org.gradle.api.dependencies.*; import org.gradle.api.dependencies.maven.Conf2ScopeMappingContainer; import org.gradle.api.internal.dependencies.ResolverFactory; import java.io.File; import java.util.List; import java.util.Map; import java.util.Set; /** * <p>A <code>DependencyManager</code> represents the set of dependencies and artifacts for a {@link * org.gradle.api.Project}.</p> * * <h3>Using the DependencyManager in a Build File</h3> * * <h4>Dynamic Properties</h4> * * <p>Each configuration added to this {@code DependencyManager} is made available as a property which can be used from * your build script. You use the name of the configuration as the property name to refer to the {@link Configuration} * object.</p> * * <h4>Dynamic Methods</h4> * * <p>The following methods are added for each configuration added to this {@code DependencyManager}. For a * configuration with name {@code config}:</p> * * <ul> * * <li>Method {@code config(Closure configureClosure)}. This is equivalent to calling {@link #configuration(String, * groovy.lang.Closure)}.</li> * * <li>Method {@code config(Object dependency,Closure configureClosure)}. This is equivalent to calling {@link * #dependency(java.util.List, Object, groovy.lang.Closure)}.</li> * * <li>Method {@code config(Object... dependencies)}. This is equivalent to calling * {@link #dependencies(java.util.List, Object[])}.</li> * * </ul> * * @author Hans Dockter */ public interface DependencyManager extends DependencyContainer { public static final String GROUP = "group"; public static final String VERSION = "version"; public static final String DEFAULT_MAVEN_REPO_NAME = "MavenRepo"; public static final String DEFAULT_ARTIFACT_PATTERN = "/[artifact]-[revision](-[classifier]).[ext]"; public static final String MAVEN_REPO_URL = "http://repo1.maven.org/maven2/"; public static final String BUILD_RESOLVER_NAME = "build-resolver"; public static final String DEFAULT_CACHE_DIR_NAME = "cache"; public static final String TMP_CACHE_DIR_NAME = Project.TMP_DIR_NAME + "/tmpIvyCache"; public static final String DEFAULT_CACHE_NAME = "default-gradle-cache"; public static final String DEFAULT_CACHE_ARTIFACT_PATTERN = "[organisation]/[module](/[branch])/[type]s/[artifact]-[revision](-[classifier])(.[ext])"; public static final String DEFAULT_CACHE_IVY_PATTERN = "[organisation]/[module](/[branch])/ivy-[revision].xml"; public static final String BUILD_RESOLVER_PATTERN = "[organisation]/[module]/[revision]/[type]s/[artifact].[ext]"; public static final String MAVEN_REPO_PATTERN = "[organisation]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"; public static final String FLAT_DIR_RESOLVER_PATTERN = "[artifact]-[revision](-[classifier]).[ext]"; public static final String DEFAULT_STATUS = "integration"; public static final String DEFAULT_GROUP = "unspecified"; public static final String DEFAULT_VERSION = "unspecified"; public static final String CLASSIFIER = "classifier"; /** * Returns the configurations that are managed by this dependency manager. * * @return The configurations, mapped from configuration name to the configuration. Returns an empty map when this * dependency manager has no configurations. */ Map<String, Configuration> getConfigurations(); /** * A map where the key is the name of the configuration and the value are Gradles Artifact objects. */ Map<String, List<PublishArtifact>> getArtifacts(); /** * A map for passing directly instances of Ivy Artifact objects. */ Map<String, List<Artifact>> getArtifactDescriptors(); /** * Ivy patterns to tell Ivy where to look for artifacts when publishing the module. */ List<String> getAbsoluteArtifactPatterns(); /** * Directories where Ivy should look for artifacts according to the {@link #getDefaultArtifactPattern()}. */ Set<File> getArtifactParentDirs(); /** * Returns an Ivy pattern describing not a path but only a pattern for the artifact file itself. The default for * this property is {@link #DEFAULT_ARTIFACT_PATTERN}. The path information is taken from {@link * #getArtifactParentDirs()}. * * @see #setDefaultArtifactPattern(String) */ String getDefaultArtifactPattern(); /** * Sets the default artifact pattern. * * @param defaultArtifactPattern The default artifact pattern. * @see #getDefaultArtifactPattern() */ void setDefaultArtifactPattern(String defaultArtifactPattern); /** * Returns the name of the task which produces the artifacts of this project. This is needed by other projects, * which have a dependency on a project. */ String getArtifactProductionTaskName(); /** * Set the artifact production task name for this project. * * @param name The name of the artifact production task name. * @see #getArtifactProductionTaskName() */ void setArtifactProductionTaskName(String name); Map<String, Set<String>> getConfs4Task(); /** * A map where the key is the name of the configuration and the value is the name of a task. This is needed to deal * with project dependencies. In case of a project dependency, we need to establish a dependsOn relationship, * between a task of the project and the task of the dependsOn project, which builds the artifacts. The default is, * that the project task is used, which has the same name as the configuration. If this is not what is wanted, the * mapping can be specified via this map. */ Map<String, Set<String>> getTasks4Conf(); /** * A configuration can be assigned to one or more tasks. One usage of this mapping is that for example the * <pre>compile</pre> task can ask for its classpath by simple passing its name as an argument. Of course the * JavaPlugin had to create the mapping during the initialization phase. <p/> Another important use case are * multi-project builds. Let's say you add a project dependency to the testCompile conf. You don't want the other * project to be build, if you do just a compile. The testCompile task is mapped to the testCompile conf. With this * knowledge we create a dependsOn relation ship between the testCompile task and the task of the other project that * produces the jar. This way a compile does not trigger the build of the other project, but a testCompile does. * * @param conf The name of the configuration * @param task The name of the task * @return this */ DependencyManager linkConfWithTask(String conf, String task); /** * Disassociates a conf from a task. * * @param conf The name of the configuration * @param task The name of the task * @return this * @see #linkConfWithTask(String, String) */ DependencyManager unlinkConfWithTask(String conf, String task); /** * Adds artifacts for the given confs. An artifact is normally a library produced by the project. Usually this * method is not directly used by the build master. The archive tasks of the libs bundle call this method to add the * archive to the artifacts. */ void addArtifacts(String configurationName, PublishArtifact... artifacts); /** * Adds a configuration to this dependency manager. * * @param configuration The name of the configuration. * @return The added configuration * @throws InvalidUserDataException If a configuration with the given name already exists in this dependency * manager. */ Configuration addConfiguration(String configuration) throws InvalidUserDataException; /** * Adds a configuration to this dependency manager, and configures it using the given closure. * * @param configuration The name of the configuration. * @param configureClosure The closure to use to configure the new configuration. * @return The added configuration * @throws InvalidUserDataException If a configuration with the given name already exists in this dependency * manager. */ Configuration addConfiguration(String configuration, Closure configureClosure) throws InvalidUserDataException; /** * <p>Locates a {@link Configuration} by name.</p> * * @param name The name of the configuration. * @return The configuration. Returns null if the configuration cannot be found. */ Configuration findConfiguration(String name); /** * <p>Locates a {@link Configuration} by name.</p> * * <p>You can also call this method from your build script by using the name of the configuration.</p> * * @param name The name of the configuration. * @return The configuration. Never returns null. * @throws UnknownConfigurationException when a configuration with the given name cannot be found. */ Configuration configuration(String name) throws UnknownConfigurationException; /** * <p>Locates a {@link Configuration} by name and configures it.</p> * * <p>You can also call this method from your build script by using the name of the configuration followed by a * closure.</p> * * @param name The name of the configuration. * @param configureClosure The closure to use to configure the configuration. * @return The configuration. Never returns null. * @throws UnknownConfigurationException when a configuration with the given name cannot be found. */ Configuration configuration(String name, Closure configureClosure) throws UnknownConfigurationException; /** * Returns a list of file objects, denoting the path to the classpath elements belonging to this configuration. If a * dependency can't be resolved an exception is thrown. Resolves also project dependencies. * * @return A list of file objects * @throws GradleException If not all dependencies can be resolved * @see #resolve(String, boolean, boolean) */ List<File> resolve(String conf); /** * Returns a list of file objects, denoting the path to the classpath elements belonging to this configuration. * * @param failForMissingDependencies If this method should throw an exception in case a dependency of the * configuration can't be resolved * @param includeProjectDependencies Whether project dependencies should be resolved as well. * @return A list of file objects * @throws GradleException If not all dependencies can be resolved */ List<File> resolve(String conf, boolean failForMissingDependencies, boolean includeProjectDependencies); /** * Returns a list of file objects, denoting the path to the classpath elements belonging to this task. Not all tasks * have an classpagh assigned to them. * * @throws InvalidUserDataException If no classpath is assigned to this tak */ List<File> resolveTask(String taskName); /** * Returns a classpath String in ant notation for the configuration. */ String antpath(String conf); /** * Returns a ResolverContainer with the resolvers responsible for resolving the classpath dependencies. There are * different resolver containers for uploading the libraries and the distributions of a project. The same resolvers * can be part of multiple resolver container. * * @return a ResolverContainer containing the classpathResolvers */ ResolverContainer getClasspathResolvers(); /** * @return The root directory used by the build resolver. */ File getBuildResolverDir(); /** * The build resolver is the resolver responsible for uploading and resolving the build source libraries as well as * project libraries between multi-project builds. * * @return the build resolver */ RepositoryResolver getBuildResolver(); /** * Sets the fail behavior for resolving dependencies. * * @see #isFailForMissingDependencies() */ void setFailForMissingDependencies(boolean failForMissingDependencies); /** * If true an exception is thrown if a dependency can't be resolved. This usually leads to a build failure (unless * there is custom logic which catches the exception). If false, missing dependencies are ignored. The default value * is true. */ boolean isFailForMissingDependencies(); /** * Adds a resolver that look in a list of directories for artifacts. The artifacts are expected to be located in the * root of the specified directories. The resolver ignores any group/organization information specified in the * dependency section of your build script. If you only use this kind of resolver you might specify your * dependencies like <code>":junit:4.4"</code> instead of <code>"junit:junit:4.4"</code> * * @param name The name of the resolver * @param dirs The directories to look for artifacts. * @return the added resolver */ FileSystemResolver addFlatDirResolver(String name, Object... dirs); /** * Adds a resolver which look in the official Maven Repo for dependencies. The URL of the official Repo is {@link * #MAVEN_REPO_URL}. The name is {@link #DEFAULT_MAVEN_REPO_NAME}. The behavior of this resolver is otherwise the * same as the ones added by {@link #addMavenStyleRepo(String, String, String[])}. * * @param jarRepoUrls A list of urls of repositories to look for artifacts only. * @return the added resolver * @see #addMavenStyleRepo(String, String, String[]) */ DependencyResolver addMavenRepo(String... jarRepoUrls); /** * Adds a resolver that uses Maven pom.xml descriptor files for resolving dependencies. By default the resolver * accepts to resolve artifacts without a pom. The resolver always looks first in the root location for the pom and * the artifact. Sometimes the artifact is supposed to live in a different repository as the pom. In such a case you * can specify further locations to look for an artifact. But be aware that the pom is only looked for in the root * location. * * For Ivy related reasons, Maven Snapshot dependencies are only properly resolved if no additional jar locations * are specified. This is unfortunate and we hope to improve this in our next release. * * @param name The name of the resolver * @param root A URL to look for artifacts and pom's * @param jarRepoUrls A list of urls of repositories to look for artifacts only. * @return the added resolver */ DependencyResolver addMavenStyleRepo(String name, String root, String... jarRepoUrls); /** * Publishes dependencies with a set of resolvers. * * @param configurations The configurations which dependencies you want to publish. * @param resolvers The resolvers you want to publish the dependencies with. * @param uploadModuleDescriptor Whether the module descriptor should be published (ivy.xml or pom.xml) */ void publish(List<String> configurations, ResolverContainer resolvers, boolean uploadModuleDescriptor); // todo Should we move this to DependencyManagerInternal? ModuleRevisionId createModuleRevisionId(); /** * Returns a container for adding exclude rules that apply to the transitive dependencies of all dependencies. */ ExcludeRuleContainer getExcludeRules(); /** * Returns an ivy module descriptor containing all dependencies and configuration that have been added to this * dependency manager. * * @param includeProjectDependencies Whether project dependencies should be included in the module descriptor */ ModuleDescriptor createModuleDescriptor(boolean includeProjectDependencies); /** * Returns the default mapping between configurations and Maven scopes. This default mapping is used by default a * {@link org.gradle.api.internal.dependencies.maven.deploy.BaseMavenDeployer} to create and deploy pom. If wished, * a MavenUploadResolver sepcific setting can be defined. */ Conf2ScopeMappingContainer getDefaultMavenScopeMapping(); /** * Returns a factory for creating special resolvers like flat dir or maven resolvers. */ ResolverFactory getResolverFactory(); /** * Returns the converter used for creating the IvySettings object. */ SettingsConverter getSettingsConverter(); /** * Returnes the converter used for creating an Ivy ModuleDescriptor. */ ModuleDescriptorConverter getModuleDescriptorConverter(); }
src/main/groovy/org/gradle/api/DependencyManager.java
/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.plugins.resolver.*; import org.gradle.api.dependencies.*; import org.gradle.api.dependencies.maven.Conf2ScopeMappingContainer; import org.gradle.api.dependencies.maven.GroovyPomFilterContainer; import org.gradle.api.internal.dependencies.ResolverFactory; import java.io.File; import java.util.List; import java.util.Map; import java.util.Set; import groovy.lang.Closure; /** * <p>A <code>DependencyManager</code> represents the set of dependencies and artifacts for a {@link * org.gradle.api.Project}.</p> * * <h3>Using the DependencyManager in a Build File</h3> * * <h4>Dynamic Properties</h4> * * <p>Each configuration added to this {@code DependencyManager} is made available as a property which can be used from * your build script. You use the name of the configuration as the property name to refer to the {@link Configuration} * object.</p> * * <h4>Dynamic Methods</h4> * * <p>The following methods are added for each configuration added to this {@code DependencyManager}. For a * configuration with name {@code config}:</p> * * <ul> * * <li>Method {@code config(Closure configureClosure)}. This is equivalent to calling {@link #configuration(String, * groovy.lang.Closure)}.</li> * * <li>Method {@code config(Object dependency,Closure configureClosure)}. This is equivalent to calling {@link * #dependency(java.util.List, Object, groovy.lang.Closure)}.</li> * * <li>Method {@code config(Object... dependencies)}. This is equivalent to calling * {@link #dependencies(java.util.List, Object[])}.</li> * * </ul> * * @author Hans Dockter */ public interface DependencyManager extends DependencyContainer { public static final String GROUP = "group"; public static final String VERSION = "version"; public static final String DEFAULT_MAVEN_REPO_NAME = "MavenRepo"; public static final String DEFAULT_ARTIFACT_PATTERN = "/[artifact]-[revision](-[classifier]).[ext]"; public static final String MAVEN_REPO_URL = "http://repo1.maven.org/maven2/"; public static final String BUILD_RESOLVER_NAME = "build-resolver"; public static final String DEFAULT_CACHE_DIR_NAME = "cache"; public static final String TMP_CACHE_DIR_NAME = Project.TMP_DIR_NAME + "/tmpIvyCache"; public static final String DEFAULT_CACHE_NAME = "default-gradle-cache"; public static final String DEFAULT_CACHE_ARTIFACT_PATTERN = "[organisation]/[module](/[branch])/[type]s/[artifact]-[revision](-[classifier])(.[ext])"; public static final String DEFAULT_CACHE_IVY_PATTERN = "[organisation]/[module](/[branch])/ivy-[revision].xml"; public static final String BUILD_RESOLVER_PATTERN = "[organisation]/[module]/[revision]/[type]s/[artifact].[ext]"; public static final String MAVEN_REPO_PATTERN = "[organisation]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"; public static final String FLAT_DIR_RESOLVER_PATTERN = "[artifact]-[revision](-[classifier]).[ext]"; public static final String DEFAULT_STATUS = "integration"; public static final String DEFAULT_GROUP = "unspecified"; public static final String DEFAULT_VERSION = "unspecified"; public static final String CLASSIFIER = "classifier"; /** * Returns the configurations that are managed by this dependency manager. * * @return The configurations, mapped from configuration name to the configuration. Returns an empty map when this * dependency manager has no configurations. */ Map<String, Configuration> getConfigurations(); /** * A map where the key is the name of the configuration and the value are Gradles Artifact objects. */ Map<String, List<PublishArtifact>> getArtifacts(); /** * A map for passing directly instances of Ivy Artifact objects. */ Map<String, List<Artifact>> getArtifactDescriptors(); /** * Ivy patterns to tell Ivy where to look for artifacts when publishing the module. */ List<String> getAbsoluteArtifactPatterns(); /** * Directories where Ivy should look for artifacts according to the {@link #getDefaultArtifactPattern()}. */ Set<File> getArtifactParentDirs(); /** * Returns an Ivy pattern describing not a path but only a pattern for the artifact file itself. The default for * this property is {@link #DEFAULT_ARTIFACT_PATTERN}. The path information is taken from {@link * #getArtifactParentDirs()}. * * @see #setDefaultArtifactPattern(String) */ String getDefaultArtifactPattern(); /** * Sets the default artifact pattern. * * @param defaultArtifactPattern The default artifact pattern. * @see #getDefaultArtifactPattern() */ void setDefaultArtifactPattern(String defaultArtifactPattern); /** * Returns the name of the task which produces the artifacts of this project. This is needed by other projects, * which have a dependency on a project. */ String getArtifactProductionTaskName(); /** * Set the artifact production task name for this project. * * @param name The name of the artifact production task name. * @see #getArtifactProductionTaskName() */ void setArtifactProductionTaskName(String name); Map<String, Set<String>> getConfs4Task(); /** * A map where the key is the name of the configuration and the value is the name of a task. This is needed to deal * with project dependencies. In case of a project dependency, we need to establish a dependsOn relationship, * between a task of the project and the task of the dependsOn project, which builds the artifacts. The default is, * that the project task is used, which has the same name as the configuration. If this is not what is wanted, the * mapping can be specified via this map. */ Map<String, Set<String>> getTasks4Conf(); /** * A configuration can be assigned to one or more tasks. One usage of this mapping is that for example the * <pre>compile</pre> task can ask for its classpath by simple passing its name as an argument. Of course the * JavaPlugin had to create the mapping during the initialization phase. <p/> Another important use case are * multi-project builds. Let's say you add a project dependency to the testCompile conf. You don't want the other * project to be build, if you do just a compile. The testCompile task is mapped to the testCompile conf. With this * knowledge we create a dependsOn relation ship between the testCompile task and the task of the other project that * produces the jar. This way a compile does not trigger the build of the other project, but a testCompile does. * * @param conf The name of the configuration * @param task The name of the task * @return this */ DependencyManager linkConfWithTask(String conf, String task); /** * Disassociates a conf from a task. * * @param conf The name of the configuration * @param task The name of the task * @return this * @see #linkConfWithTask(String, String) */ DependencyManager unlinkConfWithTask(String conf, String task); /** * Adds artifacts for the given confs. An artifact is normally a library produced by the project. Usually this * method is not directly used by the build master. The archive tasks of the libs bundle call this method to add the * archive to the artifacts. */ void addArtifacts(String configurationName, PublishArtifact... artifacts); /** * Adds a configuration to this dependency manager. * * @param configuration The name of the configuration. * @return The added configuration * @throws InvalidUserDataException If a configuration with the given name already exists in this dependency * manager. */ Configuration addConfiguration(String configuration) throws InvalidUserDataException; /** * Adds a configuration to this dependency manager, and configures it using the given closure. * * @param configuration The name of the configuration. * @param configureClosure The closure to use to configure the new configuration. * @return The added configuration * @throws InvalidUserDataException If a configuration with the given name already exists in this dependency * manager. */ Configuration addConfiguration(String configuration, Closure configureClosure) throws InvalidUserDataException; /** * <p>Locates a {@link Configuration} by name.</p> * * @param name The name of the configuration. * @return The configuration. Returns null if the configuration cannot be found. */ Configuration findConfiguration(String name); /** * <p>Locates a {@link Configuration} by name.</p> * * <p>You can also call this method from your build script by using the name of the configuration.</p> * * @param name The name of the configuration. * @return The configuration. Never returns null. * @throws UnknownConfigurationException when a configuration with the given name cannot be found. */ Configuration configuration(String name) throws UnknownConfigurationException; /** * <p>Locates a {@link Configuration} by name and configures it.</p> * * <p>You can also call this method from your build script by using the name of the configuration followed by a * closure.</p> * * @param name The name of the configuration. * @param configureClosure The closure to use to configure the configuration. * @return The configuration. Never returns null. * @throws UnknownConfigurationException when a configuration with the given name cannot be found. */ Configuration configuration(String name, Closure configureClosure) throws UnknownConfigurationException; /** * Returns a list of file objects, denoting the path to the classpath elements belonging to this configuration. If a * dependency can't be resolved an exception is thrown. Resolves also project dependencies. * * @return A list of file objects * @throws GradleException If not all dependencies can be resolved * @see #resolve(String, boolean, boolean) */ List<File> resolve(String conf); /** * Returns a list of file objects, denoting the path to the classpath elements belonging to this configuration. * * @param failForMissingDependencies If this method should throw an exception in case a dependency of the * configuration can't be resolved * @param includeProjectDependencies Whether project dependencies should be resolved as well. * @return A list of file objects * @throws GradleException If not all dependencies can be resolved */ List<File> resolve(String conf, boolean failForMissingDependencies, boolean includeProjectDependencies); /** * Returns a list of file objects, denoting the path to the classpath elements belonging to this task. Not all tasks * have an classpagh assigned to them. * * @throws InvalidUserDataException If no classpath is assigned to this tak */ List<File> resolveTask(String taskName); /** * Returns a classpath String in ant notation for the configuration. */ String antpath(String conf); /** * Returns a ResolverContainer with the resolvers responsible for resolving the classpath dependencies. There are * different resolver containers for uploading the libraries and the distributions of a project. The same resolvers * can be part of multiple resolver container. * * @return a ResolverContainer containing the classpathResolvers */ ResolverContainer getClasspathResolvers(); /** * @return The root directory used by the build resolver. */ File getBuildResolverDir(); /** * The build resolver is the resolver responsible for uploading and resolving the build source libraries as well as * project libraries between multi-project builds. * * @return the build resolver */ RepositoryResolver getBuildResolver(); /** * Sets the fail behavior for resolving dependencies. * * @see #isFailForMissingDependencies() */ void setFailForMissingDependencies(boolean failForMissingDependencies); /** * If true an exception is thrown if a dependency can't be resolved. This usually leads to a build failure (unless * there is custom logic which catches the exception). If false, missing dependencies are ignored. The default value * is true. */ boolean isFailForMissingDependencies(); /** * Adds a resolver that look in a list of directories for artifacts. The artifacts are expected to be located in the * root of the specified directories. The resolver ignores any group/organization information specified in the * dependency section of your build script. If you only use this kind of resolver you might specify your * dependencies like <code>":junit:4.4"</code> instead of <code>"junit:junit:4.4"</code> * * @param name The name of the resolver * @param dirs The directories to look for artifacts. * @return the added resolver */ FileSystemResolver addFlatDirResolver(String name, Object... dirs); /** * Adds a resolver which look in the official Maven Repo for dependencies. The URL of the official Repo is {@link * #MAVEN_REPO_URL}. The name is {@link #DEFAULT_MAVEN_REPO_NAME}. The behavior of this resolver is otherwise the * same as the ones added by {@link #addMavenStyleRepo(String, String, String[])}. * * @param jarRepoUrls A list of urls of repositories to look for artifacts only. * @return the added resolver * @see #addMavenStyleRepo(String, String, String[]) */ DependencyResolver addMavenRepo(String... jarRepoUrls); /** * Adds a resolver that uses Maven pom.xml descriptor files for resolving dependencies. By default the resolver * accepts to resolve artifacts without a pom. The resolver always looks first in the root location for the pom and * the artifact. Sometimes the artifact is supposed to live in a different repository as the pom. In such a case you * can specify further locations to look for an artifact. But be aware that the pom is only looked for in the root * location. * * For Ivy related reasons, Maven Snapshot dependencies are only properly resolved if no additional jar locations * are specified. This is unfortunate and we hope to improve this in our next release. * * @param name The name of the resolver * @param root A URL to look for artifacts and pom's * @param jarRepoUrls A list of urls of repositories to look for artifacts only. * @return the added resolver */ DependencyResolver addMavenStyleRepo(String name, String root, String... jarRepoUrls); /** * Publishes dependencies with a set of resolvers. * * @param configurations The configurations which dependencies you want to publish. * @param resolvers The resolvers you want to publish the dependencies with. * @param uploadModuleDescriptor Whether the module descriptor should be published (ivy.xml or pom.xml) */ void publish(List<String> configurations, ResolverContainer resolvers, boolean uploadModuleDescriptor); // todo Should we move this to DependencyManagerInternal? ModuleRevisionId createModuleRevisionId(); /** * Returns a container for adding exclude rules that apply to the transitive dependencies of all dependencies. */ ExcludeRuleContainer getExcludeRules(); /** * Returns an ivy module descriptor containing all dependencies and configuration that have been added to this * dependency manager. * * @param includeProjectDependencies Whether project dependencies should be included in the module descriptor */ ModuleDescriptor createModuleDescriptor(boolean includeProjectDependencies); /** * Returns the default mapping between configurations and Maven scopes. This default mapping is used by default a * {@link org.gradle.api.internal.dependencies.maven.deploy.BaseMavenDeployer} to create and deploy pom. If wished, * a MavenUploadResolver sepcific setting can be defined. */ Conf2ScopeMappingContainer getDefaultMavenScopeMapping(); /** * */ GroovyPomFilterContainer getPoms(); /** * Returns a factory for creating special resolvers like flat dir or maven resolvers. */ ResolverFactory getResolverFactory(); /** * Returns the converter used for creating the IvySettings object. */ SettingsConverter getSettingsConverter(); /** * Returnes the converter used for creating an Ivy ModuleDescriptor. */ ModuleDescriptorConverter getModuleDescriptorConverter(); }
Make pom individually customizable for install and deploy. git-svn-id: 3c1f16eda3ef44bc7d9581ddf719321a2000da74@1074 004c2c75-fc45-0410-b1a2-da8352e2331b
src/main/groovy/org/gradle/api/DependencyManager.java
Make pom individually customizable for install and deploy.
Java
apache-2.0
b97b67dcf0ca2eded809581471b9185e0b1b6638
0
ImpactDevelopment/ClientAPI,ZeroMemes/ClientAPI
package clientapi.util.entity; import net.minecraft.entity.Entity; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; /** * {@code EntityFilter} implementation that can have multiple child entity filters. * * @author Brady * @since 11/7/2017 12:14 PM */ public final class EntityFilter implements EntityCheck { /** * The child {@code EntityFilters} that are run when checking the validity of an {@code Entity} */ private final List<EntityCheck> checks = new ArrayList<>(); public EntityFilter() {} public EntityFilter(EntityCheck... checks) { this(Arrays.asList(checks)); } public EntityFilter(Iterable<EntityCheck> checks) { checks.forEach(this.checks::add); } @Override public final boolean isValid(Entity entity) { boolean containsAllow = this.checks.stream().anyMatch(filter -> filter.getType() == CheckType.ALLOW); return entity != null && this.checks.stream().filter(filter -> filter.getType() == CheckType.RESTRICT).allMatch(filter -> filter.isValid(entity)) && (!containsAllow || this.checks.stream().filter(filter -> filter.getType() == CheckType.ALLOW).anyMatch(filter -> filter.isValid(entity))); } @Override public final CheckType getType() { return CheckType.RESTRICT; } /** * Adds the specified check to this {@code EntityFilter} * if it is not already a child filter. * * @param filter The filter to add */ public final void addFilter(EntityCheck filter) { if (!this.checks.contains(filter)) this.checks.add(filter); } /** * Removes the specified check from this {@code EntityFilter} * if it is already a child filter. * * @param filter The filter to add */ public final void removeFilter(EntityCheck filter) { if (this.checks.contains(filter)) this.checks.remove(filter); } /** * @return A copy of this {@code EntityFilter's} child checks. */ public final List<EntityCheck> getChecks() { return new ArrayList<>(this.checks); } /** * Filters the specified collection of entities with all of this * {@code EntityFilter's} checks, and returns the filtered list. * * @param entities The collection to be filtered * @return A filtered list */ public final List<Entity> filter(Collection<Entity> entities) { return entities.stream().filter(this::isValid).collect(Collectors.toList()); } }
src/main/java/clientapi/util/entity/EntityFilter.java
package clientapi.util.entity; import net.minecraft.entity.Entity; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; /** * {@code EntityFilter} implementation that can have multiple child entity filters. * * @author Brady * @since 11/7/2017 12:14 PM */ public final class EntityFilter implements EntityCheck { /** * The child {@code EntityFilters} that are run when checking the validity of an {@code Entity} */ private final List<EntityCheck> checks = new ArrayList<>(); public EntityFilter() {} public EntityFilter(EntityCheck... checks) { this(Arrays.asList(checks)); } public EntityFilter(Iterable<EntityCheck> checks) { checks.forEach(this.checks::add); } @Override public final boolean isValid(Entity entity) { boolean containsAllow = this.checks.stream().anyMatch(filter -> filter.getType() == CheckType.ALLOW); return entity != null && this.checks.stream().filter(filter -> filter.getType() == CheckType.RESTRICT).allMatch(filter -> filter.isValid(entity)) && (!containsAllow || this.checks.stream().filter(filter -> filter.getType() == CheckType.ALLOW).anyMatch(filter -> filter.isValid(entity))); } @Override public final CheckType getType() { return CheckType.RESTRICT; } /** * Adds the specified check to this {@code EntityFilter} * if it is not already a child filter. * * @param filter The filter to add */ public final void addFilter(EntityCheck filter) { if (!this.checks.contains(filter)) this.checks.add(filter); } /** * Removes the specified check from this {@code EntityFilter} * if it is already a child filter. * * @param filter The filter to add */ public final void removeFilter(EntityCheck filter) { if (this.checks.contains(filter)) this.checks.remove(filter); } /** * @return A copy of this {@code EntityFilter's} child checks. */ public final List<EntityCheck> getChecks() { return new ArrayList<>(this.checks); } /** * Filters the specified collection of entities with all of this * {@code EntityFilter's} checks, and returns the filtered list. * * @param entities The collection to be filtered * @return A filtered list */ public final List<Entity> filter(Collection<Entity> entities) { return entities.stream().filter(this::isValid).collect(Collectors.toList()); } }
Optimize Imports
src/main/java/clientapi/util/entity/EntityFilter.java
Optimize Imports
Java
apache-2.0
ffbefd3a1c13fdcd1d90a8677971193b2506c1d4
0
miracleman1984/vryazanov
package tracker.start; import tracker.models.Item; import tracker.models.Task; import java.util.HashMap; /** * Menu class includes menu and responces for each part of it. * * @author Vitaly Ryazanov [email protected] * @version 1 * @since 18.02.2017 */ public class Menu { /** * Store menu chapters. */ private static final String[] MENU = { "1. Вывести список заявок", "2. Добавить новую заявку", "3. Отредактировать заявку", "4. Удалить заявку", "5. Найти заявку по названию.", "6. Найти заявку по номеру", "7. Выйти из программы." }; /** * Store tracker on that menu operates. */ private Tracker tracker; /** * Store is menu must be exit. */ private boolean isExit = false; /** * Store is menu must be shown after this action. */ private boolean isShow = true; /** * Menu class constructor. * * @param tracker on that menu operates */ public Menu(Tracker tracker) { this.tracker = tracker; } /** * Show menu. */ public void show() { System.out.println("What do your want? Press a number from menu:"); for (String s : this.MENU) { System.out.println(s); } } /** * Create new item by given name and description. * * @param input from for it will be get * @return Item to add */ public Item createItem(Input input) { String name = input.ask("Enter brief summary of item (name of item): "); String description = input.ask("Enter your full story (description of item): "); return new Task(name, description); } /** * Choose item from tracker. * * @param input from for it will be get * @param ask question for user * @return Item chosen item */ public Item chooseItem(Input input, String ask) { Item result = null; HashMap<Integer, String> map = tracker.enumItems(); if (!map.isEmpty()){ result = tracker.findById(map.get(Integer.parseInt(input.ask(ask)))); } return result; } /** * Choose item from tracker. * * @param input from for it will be get * @param output to where will be shown important information */ public void editItem(Input input, Output output) { Item itemForEdit = chooseItem(input, "Enter a number to choose item for edit"); if (itemForEdit!=null) { String id = itemForEdit.getId(); String name = itemForEdit.getName(); String description = itemForEdit.getDescription(); System.out.println("You are edited task with id = " + id); System.out.println("name = " + name); String newName = input.ask("Enter new name or just press Enter to stay current"); if (!"".equals(newName)) { name = newName; } System.out.println("description now = " + description); String newDescription = input.ask("Enter new description or just press Enter to stay current"); if (!"".equals(newDescription)) { description = newDescription; } Item itemForUpdate = new Task(name, description); itemForUpdate.setId(id); tracker.update(itemForUpdate); } else output.toOutput(new String[] {"Nothing to edit"}); } /** * Dialog for delete item from tracker. * * @param input from for it will be get * @param output to where will be shown important information */ public void deleteItem(Input input, Output output) { Item itemForDelete = chooseItem(input, "Enter a number to delete item"); if (itemForDelete!=null) { tracker.delete(chooseItem(input, "Enter a number to delete item")); } else output.toOutput(new String[] {"Nothing to delete"}); } /** * Show given items to output. * * @param items that must be shown * @param output to where will be shown important information */ public void showItems(Item[] items, Output output) { if(items.length != 0 && items[0]!=null) { for (Item item : items) { System.out.println("I'm here" ); output.toOutput(new String[]{"Name: " + item.getName() + " Description: " + item.getDescription()}); } } else output.toOutput(new String[]{"No items to show"}); } /** * Return is menu must be exit. * * @return is menu must be exit */ public boolean isExit() { return isExit; } /** * Return is menu must be shown after this action. * * @return is menu must be shown after this actio */ public boolean isShow() { return isShow; } /** * User choosing - do something. * * @param input from for it will be get * @param output to where will be shown important information */ public void choise(Input input, Output output) { switch (input.ask("Enter your choise:")) { case "1": showItems(tracker.getAll(), output); this.isShow = true; break; case "2": Item item = createItem(input); tracker.add(item); this.isShow = true; break; case "3": editItem(input, output); this.isShow = true; break; case "4": deleteItem(input, output); this.isShow = true; break; case "5": showItems(new Item[]{tracker.findByName(input.ask("Enter a name to find"))}, output); this.isShow = true; break; case "6": showItems(new Item[]{tracker.findById(input.ask("Enter an id to find"))}, output); isShow = true; break; case "7": this.isExit = true; break; default: output.toOutput(new String[]{"You have entered not a key from the menu!"}); this.isShow = false; } } }
chapter_002/Tracker/src/main/java/tracker/start/Menu.java
package tracker.start; import tracker.models.Item; import tracker.models.Task; /** * Menu class includes menu and responces for each part of it. * * @author Vitaly Ryazanov [email protected] * @version 1 * @since 18.02.2017 */ public class Menu { /** * Store menu chapters. */ private static final String[] MENU = { "1. Вывести список заявок", "2. Добавить новую заявку", "3. Отредактировать заявку", "4. Удалить заявку", "5. Найти заявку по названию.", "6. Найти заявку по номеру", "7. Выйти из программы." }; /** * Store tracker on that menu operates. */ private Tracker tracker; /** * Store is menu must be exit. */ private boolean isExit = false; /** * Store is menu must be shown after this action. */ private boolean isShow = true; /** * Menu class constructor. * * @param tracker on that menu operates */ public Menu(Tracker tracker) { this.tracker = tracker; } /** * Show menu. */ public void show() { System.out.println("What do your want? Press a number from menu:"); for (String s : this.MENU) { System.out.println(s); } } /** * Create new item by given name and description. * * @param input from for it will be get * @return Item to add */ public Item createItem(Input input) { String name = input.ask("Enter brief summary of item (name of item): "); String description = input.ask("Enter your full story (description of item): "); return new Task(name, description); } /** * Choose item from tracker. * * @param input from for it will be get * @param ask question for user * @return Item chosen item */ public Item chooseItem(Input input, String ask) { return tracker.findById(tracker.enumItems().get(Integer.parseInt(input.ask(ask)))); } /** * Choose item from tracker. * * @param input from for it will be get * @param output to where will be shown important information */ public void editItem(Input input, Output output) { Item itemForEdit = chooseItem(input, "Enter a number to choose item for edit"); String id = itemForEdit.getId(); String name = itemForEdit.getName(); String description = itemForEdit.getDescription(); System.out.println("You are edited task with id = " + id); System.out.println("name = " + name); String newName = input.ask("Enter new name or just press Enter to stay current"); if (!"".equals(newName)) { name = newName; } System.out.println("description now = " + description); String newDescription = input.ask("Enter new description or just press Enter to stay current"); if (!"".equals(newDescription)) { description = newDescription; } Item itemForUpdate = new Task(name, description); itemForUpdate.setId(id); tracker.update(itemForUpdate); } /** * Dialog for delete item from tracker. * * @param input from for it will be get */ public void deleteItem(Input input) { tracker.delete(chooseItem(input, "Enter a number to delete item")); } /** * Show given items to output. * * @param items that must be shown * @param output to where will be shown important information */ public void showItems(Item[] items, Output output) { for (Item item : items) { output.toOutput(new String[]{"Name: " + item.getName() + " Description: " + item.getDescription()}); } } /** * Return is menu must be exit. * * @return is menu must be exit */ public boolean isExit() { return isExit; } /** * Return is menu must be shown after this action. * * @return is menu must be shown after this actio */ public boolean isShow() { return isShow; } /** * User choosing - do something. * * @param input from for it will be get * @param output to where will be shown important information */ public void choise(Input input, Output output) { switch (input.ask("Enter your choise:")) { case "1": showItems(tracker.getAll(), output); this.isShow = true; break; case "2": Item item = createItem(input); tracker.add(item); this.isShow = true; break; case "3": editItem(input, output); this.isShow = true; break; case "4": deleteItem(input); this.isShow = true; break; case "5": showItems(new Item[]{tracker.findByName(input.ask("Enter a name to find"))}, output); this.isShow = true; break; case "6": showItems(new Item[]{tracker.findById(input.ask("Enter an id to find"))}, output); isShow = true; break; case "7": this.isExit = true; break; default: output.toOutput(new String[]{"You have entered not a key from the menu!"}); this.isShow = false; } } }
5.1 ended
chapter_002/Tracker/src/main/java/tracker/start/Menu.java
5.1 ended
Java
apache-2.0
afb7c7da80698b5002c196448434d81a0fa2b7ba
0
Valkryst/Schillsaver
package controller; import com.valkryst.VMVC.SceneManager; import com.valkryst.VMVC.Settings; import com.valkryst.VMVC.controller.Controller; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.stage.FileChooser; import javafx.stage.Stage; import lombok.Setter; import model.SettingsModel; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import view.SettingsView; import javax.swing.JFileChooser; import java.awt.HeadlessException; import java.io.File; public class SettingsController extends Controller<SettingsModel, SettingsView> implements EventHandler { /** The dialog stage containing the settings view. */ @Setter private Stage dialog; /** * Constructs a new SettingsController. * * @param sceneManager * The scene manager. * * @param settings * The program settings. */ public SettingsController(final SceneManager sceneManager, final Settings settings) { super (sceneManager, settings, new SettingsModel(), new SettingsView(settings)); addEventHandlers(); } /** Sets all of the view's controls to use this class as their event handler. */ private void addEventHandlers() { view.getButton_selectFfmpegExecutablePath().setOnAction(this); view.getButton_selectDefaultEncodingFolder().setOnAction(this); view.getButton_selectDefaultDecodingFolder().setOnAction(this); view.getButton_accept().setOnAction(this); view.getButton_cancel().setOnAction(this); } @Override public void handle(final Event event) { final Object source = event.getSource(); if (source.equals(view.getButton_selectFfmpegExecutablePath())) { view.getTextField_ffmpegExecutablePath().setText(selectFfmpegExecutablePath()); } if (source.equals(view.getButton_selectDefaultEncodingFolder())) { view.getTextField_defaultEncodingFolder().setText(selectFolder()); } if (source.equals(view.getButton_selectDefaultDecodingFolder())) { view.getTextField_defaultDecodingFolder().setText(selectFolder()); } if (source.equals(view.getButton_accept())) { if (updateSettings()) { dialog.close(); } } if (source.equals(view.getButton_cancel())) { dialog.close(); } } /** * Updates the program settings with the values in the view. * * @return * Whether or not the update succeeded. */ private boolean updateSettings() { String ffmpegPath = view.getTextField_ffmpegExecutablePath().getText(); String encodeFolderPath = view.getTextField_defaultEncodingFolder().getText(); String decodeFolderPath = view.getTextField_defaultDecodingFolder().getText(); String codec = view.getTextField_codec().getText(); String frameDimension = view.getComboBox_frameDimensions().getSelectionModel().getSelectedItem(); String frameRate = view.getComboBox_frameRate().getSelectionModel().getSelectedItem(); String blockSize = view.getComboBox_blockSize().getSelectionModel().getSelectedItem(); // Ensure some strings are empty if they're null. if (ffmpegPath == null) { ffmpegPath = ""; } if (encodeFolderPath == null) { encodeFolderPath = ""; } if (decodeFolderPath == null) { decodeFolderPath = ""; } if (codec == null) { codec = ""; } // Validate FFMPEG Path: File temp = new File(ffmpegPath); if (temp.exists() && temp.isFile()) { settings.setSetting("FFMPEG Executable Path", ffmpegPath); } else { final String alertMessage = "The FFMPEG executable path either doesn't exist or isn't a file."; final Alert alert = new Alert(Alert.AlertType.WARNING, alertMessage, ButtonType.OK); alert.showAndWait(); return false; } // Validate Encode Folder Path: temp = new File(encodeFolderPath); if (encodeFolderPath.isEmpty() || (temp.exists() && temp.isDirectory())) { settings.setSetting("Default Encoding Output Directory", encodeFolderPath); } else { final String alertMessage = "The default encode folder path either doesn't exist or isn't a directory."; final Alert alert = new Alert(Alert.AlertType.WARNING, alertMessage, ButtonType.OK); alert.showAndWait(); view.getTextField_defaultEncodingFolder().clear(); return false; } // Validate Decode Folder Path: temp = new File(decodeFolderPath); if (decodeFolderPath.isEmpty() || (temp.exists() && temp.isDirectory())) { settings.setSetting("Default Decoding Output Directory", decodeFolderPath); } else { final String alertMessage = "The default decode folder path either doesn't exist or isn't a directory."; final Alert alert = new Alert(Alert.AlertType.WARNING, alertMessage, ButtonType.OK); alert.showAndWait(); view.getTextField_defaultDecodingFolder().clear(); return false; } // Validate Codec: if (codec.isEmpty()) { final String alertMessage = "No codec was set."; final Alert alert = new Alert(Alert.AlertType.WARNING, alertMessage, ButtonType.OK); alert.showAndWait(); view.getTextField_codec().setText("libx264"); return false; } else { settings.setSetting("Encoding Codec", codec); } // Set other settings: settings.setSetting("Encoding Frame Dimensions", frameDimension); settings.setSetting("Encoding Frame Rate", frameRate); settings.setSetting("Encoding Block Size", blockSize); return true; } /** * Opens a file chooser for the user to select the FFMPEG executable. * * @return * The file path. */ private String selectFfmpegExecutablePath() { final FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("FFMPEG Executable Selection"); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); final File selectedFile = fileChooser.showOpenDialog(sceneManager.getPrimaryStage()); if (selectedFile != null) { if (selectedFile.exists()) { return selectedFile.getPath(); } } return ""; } /** * Open a file chooser for the user to select a directory. * * @return * The file path. */ private String selectFolder() { final JFileChooser fileChooser = new JFileChooser(); fileChooser.setDragEnabled(false); fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("Directory Selection"); fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); fileChooser.setApproveButtonText("Accept"); try { int returnVal = fileChooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fileChooser.getSelectedFile(); if (file.exists() && file.isDirectory()) { return file.getPath() + "/"; } else { return ""; } } } catch(final HeadlessException e) { final Logger logger = LogManager.getLogger(); logger.error(e); final String alertMessage = "There was an issue selecting the folder.\nSee the log file for more information."; final Alert alert = new Alert(Alert.AlertType.ERROR, alertMessage, ButtonType.OK); alert.showAndWait(); } return ""; } }
src/controller/SettingsController.java
package controller; import com.valkryst.VMVC.SceneManager; import com.valkryst.VMVC.Settings; import com.valkryst.VMVC.controller.Controller; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.stage.FileChooser; import javafx.stage.Stage; import lombok.Setter; import model.SettingsModel; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import view.SettingsView; import javax.swing.JFileChooser; import java.awt.HeadlessException; import java.io.File; public class SettingsController extends Controller<SettingsModel, SettingsView> implements EventHandler { /** The dialog stage containing the settings view. */ @Setter private Stage dialog; /** * Constructs a new SettingsController. * * @param sceneManager * The scene manager. * * @param settings * The program settings. */ public SettingsController(final SceneManager sceneManager, final Settings settings) { super (sceneManager, settings, new SettingsModel(), new SettingsView(settings)); addEventHandlers(); } /** Sets all of the view's controls to use this class as their event handler. */ private void addEventHandlers() { view.getButton_selectFfmpegExecutablePath().setOnAction(this); view.getButton_selectDefaultEncodingFolder().setOnAction(this); view.getButton_selectDefaultDecodingFolder().setOnAction(this); view.getButton_accept().setOnAction(this); view.getButton_cancel().setOnAction(this); } @Override public void handle(final Event event) { final Object source = event.getSource(); if (source.equals(view.getButton_selectFfmpegExecutablePath())) { view.getTextField_ffmpegExecutablePath().setText(selectFfmpegExecutablePath()); } if (source.equals(view.getButton_selectDefaultEncodingFolder())) { view.getTextField_defaultEncodingFolder().setText(selectFolder()); } if (source.equals(view.getButton_selectDefaultDecodingFolder())) { view.getTextField_defaultDecodingFolder().setText(selectFolder()); } if (source.equals(view.getButton_accept())) { if (updateSettings()) { dialog.close(); } } if (source.equals(view.getButton_cancel())) { dialog.close(); } } /** * Updates the program settings with the values in the view. * * @return * Whether or not the update succeeded. */ private boolean updateSettings() { final String ffmpegPath = view.getTextField_ffmpegExecutablePath().getText(); final String encodeFolderPath = view.getTextField_defaultEncodingFolder().getText(); final String decodeFolderPath = view.getTextField_defaultDecodingFolder().getText(); final String codec = view.getTextField_codec().getText(); final String frameDimension = view.getComboBox_frameDimensions().getSelectionModel().getSelectedItem(); final String frameRate = view.getComboBox_frameRate().getSelectionModel().getSelectedItem(); final String blockSize = view.getComboBox_blockSize().getSelectionModel().getSelectedItem(); // Validate FFMPEG Path: File temp = new File(ffmpegPath); if (temp.exists() && temp.isFile()) { settings.setSetting("FFMPEG Executable Path", ffmpegPath); } else { final String alertMessage = "The FFMPEG executable path either doesn't exist or isn't a file."; final Alert alert = new Alert(Alert.AlertType.WARNING, alertMessage, ButtonType.OK); alert.showAndWait(); return false; } // Validate Encode Folder Path: temp = new File(encodeFolderPath); if (temp.exists() && temp.isDirectory()) { settings.setSetting("Default Encoding Output Directory", encodeFolderPath); } else { final String alertMessage = "The default encode folder path either doesn't exist or isn't a directory."; final Alert alert = new Alert(Alert.AlertType.WARNING, alertMessage, ButtonType.OK); alert.showAndWait(); view.getTextField_defaultEncodingFolder().clear(); return false; } // Validate Decode Folder Path: temp = new File(decodeFolderPath); if (temp.exists() && temp.isDirectory()) { settings.setSetting("Default Decoding Output Directory", decodeFolderPath); } else { final String alertMessage = "The default decode folder path either doesn't exist or isn't a directory."; final Alert alert = new Alert(Alert.AlertType.WARNING, alertMessage, ButtonType.OK); alert.showAndWait(); view.getTextField_defaultDecodingFolder().clear(); return false; } // Validate Codec: if (codec.isEmpty()) { final String alertMessage = "No codec was set."; final Alert alert = new Alert(Alert.AlertType.WARNING, alertMessage, ButtonType.OK); alert.showAndWait(); view.getTextField_codec().setText("libx264"); return false; } else { settings.setSetting("Encoding Codec", codec); } // Set other settings: settings.setSetting("Encoding Frame Dimensions", frameDimension); settings.setSetting("Encoding Frame Rate", frameRate); settings.setSetting("Encoding Block Size", blockSize); return true; } /** * Opens a file chooser for the user to select the FFMPEG executable. * * @return * The file path. */ private String selectFfmpegExecutablePath() { final FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("FFMPEG Executable Selection"); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); final File selectedFile = fileChooser.showOpenDialog(sceneManager.getPrimaryStage()); if (selectedFile != null) { if (selectedFile.exists()) { return selectedFile.getPath(); } } return ""; } /** * Open a file chooser for the user to select a directory. * * @return * The file path. */ private String selectFolder() { final JFileChooser fileChooser = new JFileChooser(); fileChooser.setDragEnabled(false); fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("Directory Selection"); fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); fileChooser.setApproveButtonText("Accept"); try { int returnVal = fileChooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fileChooser.getSelectedFile(); if (file.exists() && file.isDirectory()) { return file.getPath() + "/"; } else { return ""; } } } catch(final HeadlessException e) { final Logger logger = LogManager.getLogger(); logger.error(e); final String alertMessage = "There was an issue selecting the folder.\nSee the log file for more information."; final Alert alert = new Alert(Alert.AlertType.ERROR, alertMessage, ButtonType.OK); alert.showAndWait(); } return ""; } }
Fixes null pointer error.
src/controller/SettingsController.java
Fixes null pointer error.
Java
apache-2.0
ad422c9ae70b175c246e60407b3dfe9d876db134
0
gin-fizz/pollistics,gin-fizz/pollistics,gin-fizz/pollistics
package com.pollistics.models; import java.util.HashMap; import java.util.Objects; import org.bson.types.ObjectId; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="polls") public class Poll { @Id private ObjectId id; private String name; private HashMap<String,Integer> options; private User user; public Poll(String name, HashMap<String,Integer> options) { this.name = name; this.options = options; } public Poll(String name, HashMap<String,Integer> options, User user) { this.name = name; this.options = options; this.user = user; } public Poll() { } public ObjectId getId() { return id; } public void setId(ObjectId id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public HashMap<String, Integer> getOptions() { return options; } public void setOptions(HashMap<String, Integer> options) { this.options = options; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public int hashCode() { return Objects.hash(id); } @Override public boolean equals(Object obj) { if(this == obj) return true; if((obj == null) || (obj.getClass() != this.getClass())) return false; Poll poll = (Poll) obj; return this.getId().equals(poll.getId()); } }
src/main/java/com/pollistics/models/Poll.java
package com.pollistics.models; import java.util.HashMap; import org.bson.types.ObjectId; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="polls") public class Poll { @Id private ObjectId id; private String name; private HashMap<String,Integer> options; private User user; public Poll(String name, HashMap<String,Integer> options) { this.name = name; this.options = options; } public Poll(String name, HashMap<String,Integer> options, User user) { this.name = name; this.options = options; this.user = user; } public Poll() { } public ObjectId getId() { return id; } public void setId(ObjectId id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public HashMap<String, Integer> getOptions() { return options; } public void setOptions(HashMap<String, Integer> options) { this.options = options; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
Override equals
src/main/java/com/pollistics/models/Poll.java
Override equals