gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * Copyright (C) 2012 Jake Wharton * * 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.helen.andbase.widget.viewpagerindicator; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewConfigurationCompat; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import com.helen.andbase.R; /** * Draws a line for each page. The current page line is colored differently * than the unselected page lines. */ public class UnderlinePageIndicator extends View implements PageIndicator { private static final int INVALID_POINTER = -1; private static final int FADE_FRAME_MS = 30; private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private boolean mFades; private int mFadeDelay; private int mFadeLength; private int mFadeBy; private ViewPager mViewPager; private ViewPager.OnPageChangeListener mListener; private int mScrollState; private int mCurrentPage; private float mPositionOffset; private int mTouchSlop; private float mLastMotionX = -1; private int mActivePointerId = INVALID_POINTER; private boolean mIsDragging; private final Runnable mFadeRunnable = new Runnable() { @Override public void run() { if (!mFades) return; final int alpha = Math.max(mPaint.getAlpha() - mFadeBy, 0); mPaint.setAlpha(alpha); invalidate(); if (alpha > 0) { postDelayed(this, FADE_FRAME_MS); } } }; public UnderlinePageIndicator(Context context) { this(context, null); } public UnderlinePageIndicator(Context context, AttributeSet attrs) { this(context, attrs, R.attr.vpiUnderlinePageIndicatorStyle); } @SuppressWarnings("deprecation") public UnderlinePageIndicator(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if (isInEditMode()) return; final Resources res = getResources(); //Load defaults from resources final boolean defaultFades = res.getBoolean(R.bool.default_underline_indicator_fades); final int defaultFadeDelay = res.getInteger(R.integer.default_underline_indicator_fade_delay); final int defaultFadeLength = res.getInteger(R.integer.default_underline_indicator_fade_length); final int defaultSelectedColor = res.getColor(R.color.default_underline_indicator_selected_color); //Retrieve styles attributes TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.UnderlinePageIndicator, defStyle, 0); setFades(a.getBoolean(R.styleable.UnderlinePageIndicator_fades, defaultFades)); setSelectedColor(a.getColor(R.styleable.UnderlinePageIndicator_selectedColor, defaultSelectedColor)); setFadeDelay(a.getInteger(R.styleable.UnderlinePageIndicator_fadeDelay, defaultFadeDelay)); setFadeLength(a.getInteger(R.styleable.UnderlinePageIndicator_fadeLength, defaultFadeLength)); Drawable background = a.getDrawable(R.styleable.UnderlinePageIndicator_android_background); if (background != null) { setBackgroundDrawable(background); } a.recycle(); final ViewConfiguration configuration = ViewConfiguration.get(context); mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); } public boolean getFades() { return mFades; } public void setFades(boolean fades) { if (fades != mFades) { mFades = fades; if (fades) { post(mFadeRunnable); } else { removeCallbacks(mFadeRunnable); mPaint.setAlpha(0xFF); invalidate(); } } } public int getFadeDelay() { return mFadeDelay; } public void setFadeDelay(int fadeDelay) { mFadeDelay = fadeDelay; } public int getFadeLength() { return mFadeLength; } public void setFadeLength(int fadeLength) { mFadeLength = fadeLength; mFadeBy = 0xFF / (mFadeLength / FADE_FRAME_MS); } public int getSelectedColor() { return mPaint.getColor(); } public void setSelectedColor(int selectedColor) { mPaint.setColor(selectedColor); invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mViewPager == null) { return; } final int count = mViewPager.getAdapter().getCount(); if (count == 0) { return; } if (mCurrentPage >= count) { setCurrentItem(count - 1); return; } final int paddingLeft = getPaddingLeft(); final float pageWidth = (getWidth() - paddingLeft - getPaddingRight()) / (1f * count); final float left = paddingLeft + pageWidth * (mCurrentPage + mPositionOffset); final float right = left + pageWidth; final float top = getPaddingTop(); final float bottom = getHeight() - getPaddingBottom(); canvas.drawRect(left, top, right, bottom, mPaint); } public boolean onTouchEvent(MotionEvent ev) { if (super.onTouchEvent(ev)) { return true; } if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) { return false; } final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; switch (action) { case MotionEvent.ACTION_DOWN: mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mLastMotionX = ev.getX(); break; case MotionEvent.ACTION_MOVE: { final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); final float deltaX = x - mLastMotionX; if (!mIsDragging) { if (Math.abs(deltaX) > mTouchSlop) { mIsDragging = true; } } if (mIsDragging) { mLastMotionX = x; if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) { mViewPager.fakeDragBy(deltaX); } } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: if (!mIsDragging) { final int count = mViewPager.getAdapter().getCount(); final int width = getWidth(); final float halfWidth = width / 2f; final float sixthWidth = width / 6f; if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) { if (action != MotionEvent.ACTION_CANCEL) { mViewPager.setCurrentItem(mCurrentPage - 1); } return true; } else if ((mCurrentPage < count - 1) && (ev.getX() > halfWidth + sixthWidth)) { if (action != MotionEvent.ACTION_CANCEL) { mViewPager.setCurrentItem(mCurrentPage + 1); } return true; } } mIsDragging = false; mActivePointerId = INVALID_POINTER; if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag(); break; case MotionEventCompat.ACTION_POINTER_DOWN: { final int index = MotionEventCompat.getActionIndex(ev); mLastMotionX = MotionEventCompat.getX(ev, index); mActivePointerId = MotionEventCompat.getPointerId(ev, index); break; } case MotionEventCompat.ACTION_POINTER_UP: final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); } mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)); break; } return true; } @Override public void setViewPager(ViewPager viewPager) { if (mViewPager == viewPager) { return; } if (mViewPager != null) { //Clear us from the old pager. mViewPager.setOnPageChangeListener(null); } if (viewPager.getAdapter() == null) { throw new IllegalStateException("ViewPager does not have adapter instance."); } mViewPager = viewPager; mViewPager.setOnPageChangeListener(this); invalidate(); post(new Runnable() { @Override public void run() { if (mFades) { post(mFadeRunnable); } } }); } @Override public void setViewPager(ViewPager view, int initialPosition) { setViewPager(view); setCurrentItem(initialPosition); } @Override public void setCurrentItem(int item) { if (mViewPager == null) { throw new IllegalStateException("ViewPager has not been bound."); } mViewPager.setCurrentItem(item); mCurrentPage = item; invalidate(); } @Override public void notifyDataSetChanged() { invalidate(); } @Override public void onPageScrollStateChanged(int state) { mScrollState = state; if (mListener != null) { mListener.onPageScrollStateChanged(state); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { mCurrentPage = position; mPositionOffset = positionOffset; if (mFades) { if (positionOffsetPixels > 0) { removeCallbacks(mFadeRunnable); mPaint.setAlpha(0xFF); } else if (mScrollState != ViewPager.SCROLL_STATE_DRAGGING) { postDelayed(mFadeRunnable, mFadeDelay); } } invalidate(); if (mListener != null) { mListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } @Override public void onPageSelected(int position) { if (mScrollState == ViewPager.SCROLL_STATE_IDLE) { mCurrentPage = position; mPositionOffset = 0; invalidate(); mFadeRunnable.run(); } if (mListener != null) { mListener.onPageSelected(position); } } @Override public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) { mListener = listener; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState)state; super.onRestoreInstanceState(savedState.getSuperState()); mCurrentPage = savedState.currentPage; requestLayout(); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.currentPage = mCurrentPage; return savedState; } static class SavedState extends BaseSavedState { int currentPage; public SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); currentPage = in.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(currentPage); } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
/*L * Copyright Washington University in St. Louis * Copyright SemanticBits * Copyright Persistent Systems * Copyright Krishagni * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/catissue-simple-query/LICENSE.txt for details. */ package edu.wustl.common.querysuite; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import org.hibernate.HibernateException; import edu.common.dynamicextensions.exception.DynamicExtensionsApplicationException; import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException; import edu.wustl.common.querysuite.exceptions.MultipleRootsException; import edu.wustl.common.querysuite.exceptions.SqlException; import edu.wustl.common.util.dbmanager.DBUtil; /** * This class generates metadata for CP enhancements. * * @author deepti_shelar * */ public class QueryMetadataUtil { private static Connection connection = null; private static Statement stmt = null; private static HashMap<String, List<String>> entityNameAttributeNameMap = new HashMap<String, List<String>>(); private static HashMap<String, String> attributeColumnNameMap = new HashMap<String, String>(); private static HashMap<String, String> attributeDatatypeMap = new HashMap<String, String>(); public static void main(String[] args) throws DynamicExtensionsSystemException, DynamicExtensionsApplicationException, MultipleRootsException, SqlException, HibernateException, SQLException, IOException { populateEntityAttributeMap(); populateAttributeColumnNameMap(); populateAttributeDatatypeMap(); connection = DBUtil.getConnection(); connection.setAutoCommit(true); stmt = connection.createStatement(); Set<String> keySet = entityNameAttributeNameMap.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String entityName = (String) iterator.next(); List<String> attributes = entityNameAttributeNameMap .get(entityName); for (String attr : attributes) { /*System.out.println("Adding attribute " + attr + "--" + entityName); */String sql = "select max(identifier) from dyextn_abstract_metadata"; ResultSet rs = stmt.executeQuery(sql); int nextIdOfAbstractMetadata = 0; if (rs.next()) { int maxId = rs.getInt(1); nextIdOfAbstractMetadata = maxId + 1; } int nextIdAttrTypeInfo = 0; sql = "select max(identifier) from dyextn_attribute_type_info"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIdAttrTypeInfo = maxId + 1; } int nextIdDatabaseproperties = 0; sql = "select max(identifier) from dyextn_database_properties"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIdDatabaseproperties = maxId + 1; } /*System.out.println(" generated ids"); System.out.println("dyextn_abstract_metadata : " + nextIdOfAbstractMetadata); System.out.println("dyextn_attribute_type_info :" + nextIdAttrTypeInfo); System.out.println("dyextn_database_properties :" + nextIdDatabaseproperties);*/ sql = "INSERT INTO dyextn_abstract_metadata values(" + nextIdOfAbstractMetadata + ",NULL,NULL,NULL,'" + attr + "',null)"; executeInsertSQL(sql); int entityId = getEntityIdByName(entityName); sql = "INSERT INTO dyextn_attribute values (" + nextIdOfAbstractMetadata + "," + entityId + ")"; executeInsertSQL(sql); sql = "insert into `dyextn_primitive_attribute` (`IDENTIFIER`,`IS_COLLECTION`,`IS_IDENTIFIED`,`IS_PRIMARY_KEY`,`IS_NULLABLE`)" + " values (" + nextIdOfAbstractMetadata + ",0,NULL,0,1)"; executeInsertSQL(sql); sql = "insert into `dyextn_attribute_type_info` (`IDENTIFIER`,`PRIMITIVE_ATTRIBUTE_ID`) values (" + nextIdAttrTypeInfo + "," + nextIdOfAbstractMetadata + ")"; executeInsertSQL(sql); String dataType = getDataTypeOfAttribute(attr); if (!dataType.equalsIgnoreCase("String")) { sql = "insert into `dyextn_numeric_type_info` (`IDENTIFIER`,`MEASUREMENT_UNITS`,`DECIMAL_PLACES`,`NO_DIGITS`) values (" + nextIdAttrTypeInfo + ",NULL,0,NULL)"; executeInsertSQL(sql); } if (dataType.equalsIgnoreCase("string")) { sql = "insert into `dyextn_string_type_info` (`IDENTIFIER`) values (" + nextIdAttrTypeInfo + ")"; } else if (dataType.equalsIgnoreCase("double")) { sql = "insert into dyextn_double_type_info (`IDENTIFIER`) values (" + nextIdAttrTypeInfo + ")"; } else if (dataType.equalsIgnoreCase("int")) { sql = "insert into dyextn_integer_type_info (`IDENTIFIER`) values (" + nextIdAttrTypeInfo + ")"; } executeInsertSQL(sql); String columnName = getColumnNameOfAttribue(attr); sql = "insert into `dyextn_database_properties` (`IDENTIFIER`,`NAME`) values (" + nextIdDatabaseproperties + ",'" + columnName + "')"; executeInsertSQL(sql); sql = "insert into `dyextn_column_properties` (`IDENTIFIER`,`PRIMITIVE_ATTRIBUTE_ID`) values (" + nextIdDatabaseproperties + "," + nextIdOfAbstractMetadata + ")"; executeInsertSQL(sql); } } addAssociation(false); addAssociation(true); } private static void addAssociation(boolean isSwap) throws SQLException { String sql = "select max(identifier) from dyextn_abstract_metadata"; ResultSet rs = stmt.executeQuery(sql); int nextIdOfAbstractMetadata = 0; if (rs.next()) { int maxId = rs.getInt(1); nextIdOfAbstractMetadata = maxId + 1; } int nextIdOfDERole = 0; sql = "select max(identifier) from dyextn_role"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIdOfDERole = maxId + 1; } int nextIdOfDBProperties = 0; sql = "select max(identifier) from dyextn_database_properties"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIdOfDBProperties = maxId + 1; } int nextIDintraModelAssociation = 0; sql = "select max(ASSOCIATION_ID) from intra_model_association"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIDintraModelAssociation = maxId + 1; } int nextIdPath = 0; sql = "select max(PATH_ID) from path"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIdPath = maxId + 1; } int entityId = 0; String entityName = "edu.wustl.catissuecore.domain.CollectionProtocol"; sql = "select identifier from dyextn_abstract_metadata where name like '" + entityName + "'"; rs = stmt.executeQuery(sql); if (rs.next()) { entityId = rs.getInt(1); } if (entityId == 0) { System.out.println("Entity not found of name "); } /*System.out.println(" generated ids"); System.out.println("Fount entity id is :" + entityId); System.out.println("dyextn_abstract_metadata : " + nextIdOfAbstractMetadata); System.out.println("nextIdOfDERole : " + nextIdOfDERole); System.out.println("nextIdOfDBProperties : " + nextIdOfDBProperties); System.out.println("nextIDintraModelAssociatio : " + nextIDintraModelAssociation);*/ /* System.out.println("nextIdDEAssociation : " + nextIdDEAssociation);*/ sql = "insert into dyextn_abstract_metadata values (" + nextIdOfAbstractMetadata + ",null,null,null,'collectionProtocolSelfAssociation',null)"; executeInsertSQL(sql); sql = "insert into dyextn_attribute values (" + nextIdOfAbstractMetadata + "," + entityId + ")"; executeInsertSQL(sql); sql = "insert into dyextn_role values (" + nextIdOfDERole + ",'ASSOCIATION',2,0,'childCollectionProtocolCollection')"; executeInsertSQL(sql); int roleId = nextIdOfDERole + 1; sql = "insert into dyextn_role values (" + roleId + ",'ASSOCIATION',1,0,'parentCollectionProtocol')"; executeInsertSQL(sql); if (!isSwap) { sql = "insert into dyextn_association values (" + nextIdOfAbstractMetadata + ",'BI_DIRECTIONAL'," + entityId + "," + roleId + "," + nextIdOfDERole + ",1)"; } else { sql = "insert into dyextn_association values (" + nextIdOfAbstractMetadata + ",'BI_DIRECTIONAL'," + entityId + "," + nextIdOfDERole + "," + roleId + ",1)"; } executeInsertSQL(sql); sql = "insert into dyextn_database_properties values (" + nextIdOfDBProperties + ",'collectionProtocolSelfAssociation')"; executeInsertSQL(sql); sql = "insert into dyextn_constraint_properties values(" + nextIdOfDBProperties + ",'PARENT_CP_ID',null," + nextIdOfAbstractMetadata + ")"; executeInsertSQL(sql); sql = "insert into association values(" + nextIDintraModelAssociation + ",2)"; executeInsertSQL(sql); sql = "insert into intra_model_association values(" + nextIDintraModelAssociation + "," + nextIdOfAbstractMetadata + ")"; executeInsertSQL(sql); sql = "insert into path values (" + nextIdPath + "," + entityId + "," + nextIDintraModelAssociation + "," + entityId + ")"; executeInsertSQL(sql); } private static String getColumnNameOfAttribue(String attr) { return attributeColumnNameMap.get(attr); } private static String getDataTypeOfAttribute(String attr) { return attributeDatatypeMap.get(attr); } private static void populateEntityAttributeMap() { List<String> attributes = new ArrayList<String>(); attributes.add("offset"); entityNameAttributeNameMap.put( "edu.wustl.catissuecore.domain.SpecimenCollectionGroup", attributes); attributes = new ArrayList<String>(); attributes.add("offset"); entityNameAttributeNameMap.put( "edu.wustl.catissuecore.domain.CollectionProtocolRegistration", attributes); attributes = new ArrayList<String>(); attributes.add("type"); attributes.add("sequenceNumber"); attributes.add("studyCalendarEventPoint"); entityNameAttributeNameMap.put( "edu.wustl.catissuecore.domain.CollectionProtocol", attributes); } private static void populateAttributeColumnNameMap() { attributeColumnNameMap.put("offset", "DATE_OFFSET"); attributeColumnNameMap.put("type", "CP_TYPE"); attributeColumnNameMap.put("sequenceNumber", "SEQUENCE_NUMBER"); attributeColumnNameMap.put("studyCalendarEventPoint", "STUDY_CALENDAR_EVENT_POINT"); } private static void populateAttributeDatatypeMap() { attributeDatatypeMap.put("offset", "int"); attributeDatatypeMap.put("type", "string"); attributeDatatypeMap.put("sequenceNumber", "int"); attributeDatatypeMap.put("studyCalendarEventPoint", "double"); } private static int executeInsertSQL(String sql) throws SQLException { int b; System.out.println(sql+";"); b = stmt.executeUpdate(sql); return b; } private static int getEntityIdByName(String entityName) throws SQLException { ResultSet rs; int entityId = 0; String sql = "select identifier from dyextn_abstract_metadata where name like '" + entityName + "'"; rs = stmt.executeQuery(sql); if (rs.next()) { entityId = rs.getInt(1); } if (entityId == 0) { System.out.println("Entity not found of name "); } return entityId; } } /* * insert into dyextn_abstract_metadata values * (1224,null,null,null,'collectionProtocolSelfAssociation',null) insert * into dyextn_attribute values (1224,177); insert into dyextn_role * values (897,'ASSOCIATION',2,0,'childCollectionProtocolCollection'); * insert into dyextn_role values * (898,'ASSOCIATION',1,0,'parentCollectionProtocol'); insert into * dyextn_association values (1224,'BI_DIRECTIONAL',177,898,897,1) * insert into dyextn_database_properties values * (1222,'collectionProtocolSelfAssociation'); insert into * dyextn_constraint_properties values(1222,'PARENT_CP_ID',null,1224); * insert into intra_model_association values(664,1224) insert into path * values (985340,177,664,177); * * insert into dyextn_abstract_metadata values * (1225,null,null,null,'collectionProtocolSelfAssociation',null) insert * into dyextn_attribute values (1225,177); insert into dyextn_role * values (899,'ASSOCIATION',2,0,'childCollectionProtocolCollection'); * insert into dyextn_role values * (900,'ASSOCIATION',1,0,'parentCollectionProtocol'); insert into * dyextn_association values (1225,'BI_DIRECTIONAL',177,900,899,1) * insert into dyextn_database_properties values * (1223,'collectionProtocolSelfAssociation'); insert into * dyextn_constraint_properties values(1223,'PARENT_CP_ID',null,1225); * insert into intra_model_association values(665,1225) insert into path * values (985340,177,666,177); */
package org.zu.ardulink.connection.pi; import static org.zu.ardulink.util.Preconditions.checkNotNull; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.zu.ardulink.ConnectionContact; import org.zu.ardulink.connection.Connection; import org.zu.ardulink.protocol.ALProtocol; import org.zu.ardulink.protocol.IProtocol; import org.zu.ardulink.protocol.parser.IProtocolMessageStore; import org.zu.ardulink.protocol.parser.IProtocolParser; import org.zu.ardulink.protocol.parser.MessageParsedInfo; import org.zu.ardulink.protocol.parser.MessageType; import org.zu.ardulink.protocol.parser.ParseException; import org.zu.ardulink.protocol.parser.ProtocolParserHandler; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPin; import com.pi4j.io.gpio.GpioPinAnalogInput; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.GpioPinPwmOutput; import com.pi4j.io.gpio.PinMode; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinAnalogValueChangeEvent; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerAnalog; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import com.pi4j.io.gpio.event.PinEventType; public class RaspberryPIConnection implements Connection { public static final String CONNECTION_NAME = "Raspberry PI"; private ConnectionContact connectionContact; /** * The status of the connection. */ private boolean connected; private GpioController gpioController; /** * The protocol used by the link instance for this connection */ private IProtocolParser protocolParser; private IProtocolMessageStore messageStore; /** * Listeners */ private Map<Integer, GpioPinListenerDigital> digitalListeners = new HashMap<Integer, GpioPinListenerDigital>(); private Map<Integer, GpioPinListenerAnalog> analogListeners = new HashMap<Integer, GpioPinListenerAnalog>(); public RaspberryPIConnection() { this(ALProtocol.NAME); } public RaspberryPIConnection(String protocolName) { super(); protocolParser = ProtocolParserHandler.getProtocolParserImplementation(protocolName); checkNotNull(protocolParser, "Protocol not supported. Resiter the right parser for: " + protocolName); messageStore = protocolParser.getMessageStore(); } @Override public List<String> getPortList() { return Collections.singletonList(CONNECTION_NAME); } public boolean connect() { if(!connected) { gpioController = GpioFactory.getInstance(); if(gpioController != null) { connected = true; if(connectionContact != null) { connectionContact.connected(CONNECTION_NAME, CONNECTION_NAME); } } } return connected; } @Override public boolean connect(Object... params) { checkNotNull(params, "Params must be null"); return connect(); } @Override public boolean disconnect() { if(connected) { gpioController.shutdown(); gpioController = null; connected = false; if(connectionContact != null) { connectionContact.disconnected(CONNECTION_NAME); } } return !connected; } @Override public boolean isConnected() { return connected; } @Override public boolean writeSerial(String message) { boolean success = false; if (isConnected()) { try { success = true; messageStore.addMessageChunck(message); if(messageStore.isMessageComplete()) { MessageParsedInfo messageParsedInfo = protocolParser.parse(messageStore.getNextMessage()); success = processMessage(messageParsedInfo); if(messageParsedInfo.getId() != IProtocol.UNDEFINED_ID) { reply(success, messageParsedInfo); } } } catch (ParseException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); disconnect(); } } else { connectionContact.writeLog(CONNECTION_NAME, "No port is connected."); } return success; } private void reply(final boolean success, final MessageParsedInfo messageParsedInfo) { Thread thread = new Thread(new Runnable() { @Override public void run() { int[] reply = protocolParser.reply(success, messageParsedInfo); connectionContact.parseInput(CONNECTION_NAME, reply.length, reply); } }); thread.start(); } @Override public boolean writeSerial(int numBytes, int[] message) { throw new UnsupportedOperationException("Please use: writeSerial(String message) instead."); } @Override public void setConnectionContact(ConnectionContact contact) { connectionContact = contact; } public void writeLog(String text) { connectionContact.writeLog(CONNECTION_NAME, text); } private boolean processMessage(MessageParsedInfo messageParsedInfo) { boolean retvalue = false; if(MessageType.PPSW == messageParsedInfo.getMessageType()) { retvalue = sendPowerPinSwitch(messageParsedInfo); } else if(MessageType.PPIN == messageParsedInfo.getMessageType()) { retvalue = sendPowerPinIntensity(messageParsedInfo); } else if(MessageType.KPRS == messageParsedInfo.getMessageType()) { throw new UnsupportedOperationException("This connection doesn't support key press messages"); } else if(MessageType.TONE == messageParsedInfo.getMessageType()) { throw new UnsupportedOperationException("This connection doesn't support tone messages"); } else if(MessageType.NOTN == messageParsedInfo.getMessageType()) { throw new UnsupportedOperationException("This connection doesn't support notone messages"); } else if(MessageType.SRLD == messageParsedInfo.getMessageType()) { retvalue = startListenDigitalPin(messageParsedInfo); } else if(MessageType.SPLD == messageParsedInfo.getMessageType()) { retvalue = stopListenDigitalPin(messageParsedInfo); } else if(MessageType.SRLA == messageParsedInfo.getMessageType()) { retvalue = startListenAnalogPin(messageParsedInfo); } else if(MessageType.SPLA == messageParsedInfo.getMessageType()) { retvalue = stopListenAnalogPin(messageParsedInfo); } else if(MessageType.CUST == messageParsedInfo.getMessageType()) { throw new UnsupportedOperationException("This connection doesn't support custom messages"); } else if(MessageType.ARED == messageParsedInfo.getMessageType()) { throw new IllegalStateException("Analog Read Event Message shoudn't come here"); } else if(MessageType.DRED == messageParsedInfo.getMessageType()) { throw new IllegalStateException("Digital Read Event Message shoudn't come here"); } else if(MessageType.RPLY == messageParsedInfo.getMessageType()) { throw new IllegalStateException("Reply Event Message shoudn't come here"); } return retvalue; } private boolean sendPowerPinSwitch(MessageParsedInfo messageParsedInfo) { int pinNum = (Integer)messageParsedInfo.getParsedValues()[0]; int power = (Integer)messageParsedInfo.getParsedValues()[1]; GpioPinDigitalOutput pin = (GpioPinDigitalOutput)getPin(pinNum); pin.setMode(PinMode.DIGITAL_OUTPUT); if(power == IProtocol.LOW) { pin.low(); } else { pin.high(); } return true; } private boolean sendPowerPinIntensity(MessageParsedInfo messageParsedInfo) { int pinNum = (Integer)messageParsedInfo.getParsedValues()[0]; int intensity = (Integer)messageParsedInfo.getParsedValues()[1]; GpioPinPwmOutput pin = (GpioPinPwmOutput )getPin(pinNum); pin.setMode(PinMode.PWM_OUTPUT); pin.setPwm(intensity); return true; } private boolean startListenDigitalPin(MessageParsedInfo messageParsedInfo) { int pinNum = (Integer)messageParsedInfo.getParsedValues()[0]; GpioPinListenerDigital listener = digitalListeners.get(pinNum); if(listener == null) { listener = createDigitalListener(pinNum); GpioPinDigitalInput pin = (GpioPinDigitalInput)getPin(pinNum); pin.setMode(PinMode.DIGITAL_INPUT); pin.setPullResistance(PinPullResistance.PULL_DOWN); digitalListeners.put(pinNum, listener); pin.addListener(listener); } return true; } private boolean stopListenDigitalPin(MessageParsedInfo messageParsedInfo) { int pinNum = (Integer)messageParsedInfo.getParsedValues()[0]; GpioPinListenerDigital listener = digitalListeners.get(pinNum); if(listener != null) { GpioPinDigitalInput pin = (GpioPinDigitalInput)getPin(pinNum); digitalListeners.remove(pin); pin.removeListener(listener); } return true; } private boolean startListenAnalogPin(MessageParsedInfo messageParsedInfo) { int pinNum = (Integer)messageParsedInfo.getParsedValues()[0]; GpioPinListenerAnalog listener = analogListeners.get(pinNum); if(listener == null) { listener = createAnalogListener(pinNum); GpioPinAnalogInput pin = (GpioPinAnalogInput)getPin(pinNum); pin.setMode(PinMode.ANALOG_INPUT); pin.setPullResistance(PinPullResistance.PULL_DOWN); analogListeners.put(pinNum, listener); pin.addListener(listener); } return true; } private boolean stopListenAnalogPin(MessageParsedInfo messageParsedInfo) { int pinNum = (Integer)messageParsedInfo.getParsedValues()[0]; GpioPinListenerAnalog listener = analogListeners.get(pinNum); if(listener != null) { GpioPinAnalogInput pin = (GpioPinAnalogInput)getPin(pinNum); analogListeners.remove(pin); pin.removeListener(listener); } return true; } private GpioPin getPin(int address) { GpioPin retvalue = null; Collection<GpioPin> provisioned = gpioController.getProvisionedPins(); for (GpioPin gpioPin : provisioned) { if(gpioPin.getPin().getAddress() == address) { retvalue = gpioPin; break; } } if(retvalue == null) { retvalue = gpioController.provisionPin(RaspiPin.getPinByName("GPIO " + address), PinMode.DIGITAL_OUTPUT); } return retvalue; } private GpioPinListenerDigital createDigitalListener(int pinNum) { return new DigitalListener(pinNum); } private GpioPinListenerAnalog createAnalogListener(int pinNum) { return new AnalogListener(pinNum); } class DigitalListener implements GpioPinListenerDigital { private int pin; public DigitalListener(int pin) { super(); this.pin = pin; } @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { if(event.getEventType() == PinEventType.DIGITAL_STATE_CHANGE) { int[] message; if(event.getState().isHigh()) { message = protocolParser.digitalRead(pin, IProtocol.HIGH); } else { message = protocolParser.digitalRead(pin, IProtocol.LOW); } connectionContact.parseInput(CONNECTION_NAME, message.length, message); } } } class AnalogListener implements GpioPinListenerAnalog { private int pin; public AnalogListener(int pin) { super(); this.pin = pin; } @Override public void handleGpioPinAnalogValueChangeEvent(GpioPinAnalogValueChangeEvent event) { if(event.getEventType() == PinEventType.ANALOG_VALUE_CHANGE) { int[] message = protocolParser.analogRead(pin, (int)event.getValue()); connectionContact.parseInput(CONNECTION_NAME, message.length, message); } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bftsmart.tom.server; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import bftsmart.statemanagment.ApplicationState; import bftsmart.tom.MessageContext; import bftsmart.tom.server.defaultservices.DefaultApplicationState; import bftsmart.tom.server.defaultservices.StateLog; import bftsmart.tom.util.Logger; /** * * @author Joao Sousa */ public abstract class DefaultRecoverable implements Recoverable, BatchExecutable { public static final int CHECKPOINT_PERIOD = 50; private ReentrantLock logLock = new ReentrantLock(); private ReentrantLock hashLock = new ReentrantLock(); private ReentrantLock stateLock = new ReentrantLock(); private MessageDigest md; private StateLog log; public DefaultRecoverable() { log = new StateLog(CHECKPOINT_PERIOD); try { md = MessageDigest.getInstance("MD5"); // TODO: shouldn't it be SHA? } catch (NoSuchAlgorithmException ex) { java.util.logging.Logger.getLogger(DefaultRecoverable.class.getName()).log(Level.SEVERE, null, ex); } } public byte[][] executeBatch(byte[][] commands, MessageContext[] msgCtxs) { int eid = msgCtxs[0].getConsensusId(); stateLock.lock(); byte[][] replies = executeBatch2(commands, msgCtxs); stateLock.unlock(); if ((eid > 0) && ((eid % CHECKPOINT_PERIOD) == 0)) { Logger.println("(DefaultRecoverable.executeBatch) Performing checkpoint for consensus " + eid); stateLock.lock(); byte[] snapshot = getSnapshot(); stateLock.unlock(); saveState(snapshot, eid, 0, 0/*tomLayer.lm.getLeader(cons.getId(), cons.getDecisionRound().getNumber())*/); } else { Logger.println("(DefaultRecoverable.executeBatch) Storing message batch in the state log for consensus " + eid); saveCommands(commands, eid, 0, 0/*tomLayer.lm.getLeader(cons.getId(), cons.getDecisionRound().getNumber())*/); } return replies; } public final byte[] computeHash(byte[] data) { byte[] ret = null; hashLock.lock(); ret = md.digest(data); hashLock.unlock(); return ret; } private StateLog getLog() { return log; } public void saveState(byte[] snapshot, int lastEid, int decisionRound, int leader) { StateLog thisLog = getLog(); logLock.lock(); Logger.println("(TOMLayer.saveState) Saving state of EID " + lastEid + ", round " + decisionRound + " and leader " + leader); thisLog.newCheckpoint(snapshot, computeHash(snapshot)); thisLog.setLastEid(-1); thisLog.setLastCheckpointEid(lastEid); thisLog.setLastCheckpointRound(decisionRound); thisLog.setLastCheckpointLeader(leader); logLock.unlock(); /*System.out.println("fiz checkpoint"); System.out.println("tamanho do snapshot: " + snapshot.length); System.out.println("tamanho do log: " + thisLog.getMessageBatches().length);*/ Logger.println("(TOMLayer.saveState) Finished saving state of EID " + lastEid + ", round " + decisionRound + " and leader " + leader); } public void saveCommands(byte[][] commands, int lastEid, int decisionRound, int leader) { StateLog thisLog = getLog(); logLock.lock(); Logger.println("(TOMLayer.saveBatch) Saving batch of EID " + lastEid + ", round " + decisionRound + " and leader " + leader); thisLog.addMessageBatch(commands, decisionRound, leader); thisLog.setLastEid(lastEid); logLock.unlock(); /*System.out.println("guardei comandos"); System.out.println("tamanho do log: " + thisLog.getNumBatches());*/ Logger.println("(TOMLayer.saveBatch) Finished saving batch of EID " + lastEid + ", round " + decisionRound + " and leader " + leader); } @Override public ApplicationState getState(int eid, boolean sendState) { logLock.lock(); System.out.println(" EID: " + eid + "sendstate: " + sendState); ApplicationState ret = (eid > -1 ? getLog().getApplicationState(eid, sendState) : new DefaultApplicationState()); logLock.unlock(); return ret; } @Override public int setState(ApplicationState recvState) { int lastEid = -1; if (recvState instanceof DefaultApplicationState) { DefaultApplicationState state = (DefaultApplicationState) recvState; System.out.println("(DefaultRecoverable.setState) last eid in state: " + state.getLastEid()); getLog().update(state); int lastCheckpointEid = state.getLastCheckpointEid(); lastEid = state.getLastEid(); //lastEid = lastCheckpointEid + (state.getMessageBatches() != null ? state.getMessageBatches().length : 0); bftsmart.tom.util.Logger.println("(DefaultRecoverable.setState) I'm going to update myself from EID " + lastCheckpointEid + " to EID " + lastEid); stateLock.lock(); installSnapshot(state.getState()); // INUTIL?????? //tomLayer.lm.addLeaderInfo(lastCheckpointEid, state.getLastCheckpointRound(), // state.getLastCheckpointLeader()); for (int eid = lastCheckpointEid + 1; eid <= lastEid; eid++) { try { bftsmart.tom.util.Logger.println("(DefaultRecoverable.setState) interpreting and verifying batched requests for eid " + eid); System.out.println("(DefaultRecoverable.setState) interpreting and verifying batched requests for eid " + eid); if (state.getMessageBatch(eid) == null) System.out.println("(DefaultRecoverable.setState) " + eid + " NULO!!!"); byte[][] commands = state.getMessageBatch(eid).commands; // take a batch // INUTIL?????? //tomLayer.lm.addLeaderInfo(eid, state.getMessageBatch(eid).round, // state.getMessageBatch(eid).leader); //TROCAR POR EXECUTE E ARRAY DE MENSAGENS!!!!!! //TOMMessage[] requests = new BatchReader(batch, // manager.getStaticConf().getUseSignatures() == 1).deserialiseRequests(manager); executeBatch2(commands, null); // ISTO E UM PROB A RESOLVER!!!!!!!!!!!! //tomLayer.clientsManager.requestsOrdered(requests); // INUTIL?????? //deliverMessages(eid, tomLayer.getLCManager().getLastReg(), false, requests, batch); // IST E UM PROB A RESOLVER!!!! //******* EDUARDO BEGIN **************// /*if (manager.hasUpdates()) { processReconfigMessages(lastCheckpointEid, state.getLastCheckpointRound()); }*/ //******* EDUARDO END **************// } catch (Exception e) { e.printStackTrace(System.err); if (e instanceof ArrayIndexOutOfBoundsException) { System.out.println("Eid do ultimo checkpoint: " + state.getLastCheckpointEid()); System.out.println("Eid do ultimo consenso: " + state.getLastEid()); System.out.println("numero de mensagens supostamente no batch: " + (state.getLastEid() - state.getLastCheckpointEid() + 1)); System.out.println("numero de mensagens realmente no batch: " + state.getMessageBatches().length); } } } stateLock.unlock(); } return lastEid; } public abstract void installSnapshot(byte[] state); public abstract byte[] getSnapshot(); public abstract byte[][] executeBatch2(byte[][] commands, MessageContext[] msgCtxs); }
// Copyright (C) 2011 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.git; import com.google.gerrit.reviewdb.client.Branch; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.client.SubmoduleSubscription; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.GerritPersonIdent; import com.google.gerrit.server.config.CanonicalWebUrl; import com.google.gerrit.server.extensions.events.GitReferenceUpdated; import com.google.gerrit.server.util.SubmoduleSectionParser; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.SchemaFactory; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.assistedinject.Assisted; import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.dircache.DirCacheBuilder; import org.eclipse.jgit.dircache.DirCacheEditor; import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit; import org.eclipse.jgit.dircache.DirCacheEntry; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.lib.BlobBasedConfig; import org.eclipse.jgit.lib.CommitBuilder; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; public class SubmoduleOp { public interface Factory { SubmoduleOp create(Branch.NameKey destBranch, RevCommit mergeTip, RevWalk rw, Repository db, Project destProject, List<Change> submitted, Map<Change.Id, CodeReviewCommit> commits); } private static final Logger log = LoggerFactory.getLogger(SubmoduleOp.class); private static final String GIT_MODULES = ".gitmodules"; private final Branch.NameKey destBranch; private RevCommit mergeTip; private RevWalk rw; private final Provider<String> urlProvider; private ReviewDb schema; private Repository db; private Project destProject; private List<Change> submitted; private final Map<Change.Id, CodeReviewCommit> commits; private final PersonIdent myIdent; private final GitRepositoryManager repoManager; private final GitReferenceUpdated replication; private final SchemaFactory<ReviewDb> schemaFactory; private final Set<Branch.NameKey> updatedSubscribers; @Inject public SubmoduleOp(@Assisted final Branch.NameKey destBranch, @Assisted RevCommit mergeTip, @Assisted RevWalk rw, @CanonicalWebUrl @Nullable final Provider<String> urlProvider, final SchemaFactory<ReviewDb> sf, @Assisted Repository db, @Assisted Project destProject, @Assisted List<Change> submitted, @Assisted final Map<Change.Id, CodeReviewCommit> commits, @GerritPersonIdent final PersonIdent myIdent, GitRepositoryManager repoManager, GitReferenceUpdated replication) { this.destBranch = destBranch; this.mergeTip = mergeTip; this.rw = rw; this.urlProvider = urlProvider; this.schemaFactory = sf; this.db = db; this.destProject = destProject; this.submitted = submitted; this.commits = commits; this.myIdent = myIdent; this.repoManager = repoManager; this.replication = replication; updatedSubscribers = new HashSet<Branch.NameKey>(); } public void update() throws SubmoduleException { try { schema = schemaFactory.open(); updateSubmoduleSubscriptions(); updateSuperProjects(destBranch, mergeTip.getId().toObjectId(), null); } catch (OrmException e) { throw new SubmoduleException("Cannot open database", e); } finally { if (schema != null) { schema.close(); schema = null; } } } private void updateSubmoduleSubscriptions() throws SubmoduleException { if (urlProvider.get() == null) { logAndThrowSubmoduleException("Cannot establish canonical web url used to access gerrit." + " It should be provided in gerrit.config file."); } try { final TreeWalk tw = TreeWalk.forPath(db, GIT_MODULES, mergeTip.getTree()); if (tw != null && (FileMode.REGULAR_FILE.equals(tw.getRawMode(0)) || FileMode.EXECUTABLE_FILE .equals(tw.getRawMode(0)))) { BlobBasedConfig bbc = new BlobBasedConfig(null, db, mergeTip, GIT_MODULES); final String thisServer = new URI(urlProvider.get()).getHost(); final Branch.NameKey target = new Branch.NameKey(new Project.NameKey(destProject.getName()), destBranch.get()); final Set<SubmoduleSubscription> oldSubscriptions = new HashSet<SubmoduleSubscription>(schema.submoduleSubscriptions() .bySuperProject(destBranch).toList()); final List<SubmoduleSubscription> newSubscriptions = new SubmoduleSectionParser(bbc, thisServer, target, repoManager) .parseAllSections(); final Set<SubmoduleSubscription> alreadySubscribeds = new HashSet<SubmoduleSubscription>(); for (SubmoduleSubscription s : newSubscriptions) { if (oldSubscriptions.contains(s)) { alreadySubscribeds.add(s); } } oldSubscriptions.removeAll(newSubscriptions); newSubscriptions.removeAll(alreadySubscribeds); if (!oldSubscriptions.isEmpty()) { schema.submoduleSubscriptions().delete(oldSubscriptions); } schema.submoduleSubscriptions().insert(newSubscriptions); } } catch (OrmException e) { logAndThrowSubmoduleException( "Database problem at update of subscriptions table from " + GIT_MODULES + " file.", e); } catch (ConfigInvalidException e) { logAndThrowSubmoduleException( "Problem at update of subscriptions table: " + GIT_MODULES + " config file is invalid.", e); } catch (IOException e) { logAndThrowSubmoduleException( "Problem at update of subscriptions table from " + GIT_MODULES + ".", e); } catch (URISyntaxException e) { logAndThrowSubmoduleException( "Incorrect gerrit canonical web url provided in gerrit.config file.", e); } } private void updateSuperProjects(final Branch.NameKey updatedBranch, final ObjectId mergedCommit, final String msg) throws SubmoduleException { try { final List<SubmoduleSubscription> subscribers = schema.submoduleSubscriptions().bySubmodule(updatedBranch).toList(); if (!subscribers.isEmpty()) { String msgbuf = msg; if (msgbuf == null) { // Initialize the message buffer msgbuf = ""; // The first updatedBranch on a cascade event of automatic // updates of repos is added to updatedSubscribers set so // if we face a situation having // submodule-a(master)-->super(master)-->submodule-a(master), // it will be detected we have a circular subscription // when updateSuperProjects is called having as updatedBranch // the super(master) value. updatedSubscribers.add(updatedBranch); for (final Change chg : submitted) { final CodeReviewCommit c = commits.get(chg.getId()); if (c != null && (c.statusCode == CommitMergeStatus.CLEAN_MERGE || c.statusCode == CommitMergeStatus.CLEAN_PICK)) { msgbuf += "\n"; msgbuf += c.getFullMessage(); } } } // update subscribers of this module for (final SubmoduleSubscription s : subscribers) { if (!updatedSubscribers.add(s.getSuperProject())) { log.error("Possible circular subscription involving " + s.toString()); } else { Map<Branch.NameKey, ObjectId> modules = new HashMap<Branch.NameKey, ObjectId>(1); modules.put(updatedBranch, mergedCommit); Map<Branch.NameKey, String> paths = new HashMap<Branch.NameKey, String>(1); paths.put(updatedBranch, s.getPath()); try { updateGitlinks(s.getSuperProject(), modules, paths, msgbuf); } catch (SubmoduleException e) { throw e; } } } } } catch (OrmException e) { logAndThrowSubmoduleException("Cannot read subscription records", e); } } private void updateGitlinks(final Branch.NameKey subscriber, final Map<Branch.NameKey, ObjectId> modules, final Map<Branch.NameKey, String> paths, final String msg) throws SubmoduleException { PersonIdent author = null; final StringBuilder msgbuf = new StringBuilder(); msgbuf.append("Updated " + subscriber.getParentKey().get()); Repository pdb = null; try { boolean sameAuthorForAll = true; for (final Map.Entry<Branch.NameKey, ObjectId> me : modules.entrySet()) { RevCommit c = rw.parseCommit(me.getValue()); msgbuf.append("\nProject: "); msgbuf.append(me.getKey().getParentKey().get()); msgbuf.append(" " + me.getValue().getName()); msgbuf.append("\n"); if (modules.size() == 1 && msg != null) { msgbuf.append(msg); } else { msgbuf.append(c.getShortMessage()); } msgbuf.append("\n"); if (author == null) { author = c.getAuthorIdent(); } else if (!author.equals(c.getAuthorIdent())) { sameAuthorForAll = false; } } if (!sameAuthorForAll || author == null) { author = myIdent; } pdb = repoManager.openRepository(subscriber.getParentKey()); if (pdb.getRef(subscriber.get()) == null) { throw new SubmoduleException( "The branch was probably deleted from the subscriber repository"); } final ObjectId currentCommitId = pdb.getRef(subscriber.get()).getObjectId(); DirCache dc = readTree(pdb, pdb.getRef(subscriber.get())); DirCacheEditor ed = dc.editor(); for (final Map.Entry<Branch.NameKey, ObjectId> me : modules.entrySet()) { ed.add(new PathEdit(paths.get(me.getKey())) { public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.GITLINK); ent.setObjectId(me.getValue().copy()); } }); } ed.finish(); ObjectInserter oi = pdb.newObjectInserter(); ObjectId tree = dc.writeTree(oi); final CommitBuilder commit = new CommitBuilder(); commit.setTreeId(tree); commit.setParentIds(new ObjectId[] {currentCommitId}); commit.setAuthor(author); commit.setCommitter(myIdent); commit.setMessage(msgbuf.toString()); oi.insert(commit); ObjectId commitId = oi.idFor(Constants.OBJ_COMMIT, commit.build()); final RefUpdate rfu = pdb.updateRef(subscriber.get()); rfu.setForceUpdate(false); rfu.setNewObjectId(commitId); rfu.setExpectedOldObjectId(currentCommitId); rfu .setRefLogMessage("Submit to " + subscriber.getParentKey().get(), true); switch (rfu.update()) { case NEW: case FAST_FORWARD: replication.fire(subscriber.getParentKey(), rfu.getName()); // TODO since this is performed "in the background" no mail will be // sent to inform users about the updated branch break; default: throw new IOException(rfu.getResult().name()); } // Recursive call: update subscribers of the subscriber updateSuperProjects(subscriber, commitId, msgbuf.toString()); } catch (IOException e) { logAndThrowSubmoduleException("Cannot update gitlinks for " + subscriber.get(), e); } finally { if (pdb != null) { pdb.close(); } } } private static DirCache readTree(final Repository pdb, final Ref branch) throws MissingObjectException, IncorrectObjectTypeException, IOException { final RevWalk rw = new RevWalk(pdb); final DirCache dc = DirCache.newInCore(); final DirCacheBuilder b = dc.builder(); b.addTree(new byte[0], // no prefix path DirCacheEntry.STAGE_0, // standard stage pdb.newObjectReader(), rw.parseTree(branch.getObjectId())); b.finish(); return dc; } private static void logAndThrowSubmoduleException(final String errorMsg, final Exception e) throws SubmoduleException { log.error(errorMsg, e); throw new SubmoduleException(errorMsg, e); } private static void logAndThrowSubmoduleException(final String errorMsg) throws SubmoduleException { log.error(errorMsg); throw new SubmoduleException(errorMsg); } }
/* * Copyright (c) 2014 Jono Vanhie-Van Gerwen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jvanhie.discogsscrobbler; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.preference.PreferenceManager; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ProgressBar; import android.widget.Spinner; import com.github.jvanhie.discogsscrobbler.models.Folder; import com.github.jvanhie.discogsscrobbler.util.Discogs; import java.util.List; /** * An activity representing a list of Releases. This activity * has different presentations for handset and tablet-size devices. On * handsets, the activity presents a list of items, which when touched, * lead to a {@link ReleaseDetailActivity} representing * item details. On tablets, the activity presents the list of items and * item details side-by-side using two vertical panes. * <p> * The activity makes heavy use of fragments. The list of items is a * {@link ReleaseListFragment} and the item details * (if present) is a {@link ReleaseDetailFragment}. * <p> * This activity also implements the required * {@link ReleaseListFragment.Callbacks} interface * to listen for item selections. */ public class ReleaseListActivity extends DrawerActivity implements ReleaseListFragment.Callbacks { /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ private int mPanes = 1; private static final String STATE_PANES = "collection_panes"; private long mSelected; private static final String STATE_RELEASE_SELECTED = "selected_release"; private Discogs mDiscogs; private ReleaseListFragment mReleaseList; //all possible extra fragments in tablet mode private ReleasePagerFragment mReleasePager; private ReleaseDetailFragment mReleaseDetail; private ReleaseTracklistFragment mReleaseTracklist; private ProgressBar mReleaseProgressBar; private ProgressBar mRefreshProgressBar; private boolean mLoaded = false; private boolean mRefresh = false; private boolean mFolders = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PreferenceManager.setDefaultValues(this, R.xml.pref_discogs, false); setContentView(R.layout.activity_release_list); mReleaseProgressBar = (ProgressBar) findViewById(R.id.release_list_progressBar); mRefreshProgressBar = (ProgressBar) findViewById(R.id.release_list_refresh); mReleaseList = ((ReleaseListFragment) getSupportFragmentManager().findFragmentById(R.id.release_list)); if(mReleaseProgressBar != null && mLoaded) mReleaseProgressBar.setVisibility(View.INVISIBLE); if(mRefreshProgressBar != null && mRefresh) mRefreshProgressBar.setVisibility(View.VISIBLE); //check if we're in tablet mode -> two or tripane layout (hide details fields first, for a nice collection view) if (findViewById(R.id.release_pager_container) != null) { mPanes = 2; findViewById(R.id.release_pager_container).setVisibility(View.GONE); } else if (findViewById(R.id.release_tracklist_container) != null) { mPanes = 3; findViewById(R.id.release_detail_container).setVisibility(View.GONE); findViewById(R.id.release_tracklist_container).setVisibility(View.GONE); } // Restore the previously serialized activated release if (savedInstanceState != null && savedInstanceState.containsKey(STATE_RELEASE_SELECTED)) { if (savedInstanceState.getInt(STATE_PANES) != mPanes) { //if the panelayout has changed, forcibly reload the fragments onItemSelected(savedInstanceState.getLong(STATE_RELEASE_SELECTED)); } } if(mDiscogs == null) mDiscogs = Discogs.getInstance(this); //create navigation drawer setDrawer(R.id.list_drawer_layout, R.id.list_drawer, getTitle().toString(), getTitle().toString(), true); } @Override public boolean onCreateOptionsMenu(final Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.discogs_list, menu); //configure search box final MenuItem search = menu.findItem(R.id.list_search); SearchView searchView = (SearchView) search.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { menu.findItem(R.id.list_search).collapseActionView(); return false; } @Override public boolean onQueryTextChange(String s) { mReleaseList.filter(s); return false; } }); searchView.setQueryHint("Filter your releases"); final MenuItem filter = menu.findItem(R.id.list_filter); if(!mFolders) { mDiscogs.getFolders(new Discogs.DiscogsDataWaiter<List<Folder>>() { @Override public void onResult(boolean success, List<Folder> data) { if(success && data != null) { mFolders = true; Spinner s = (Spinner) filter.getActionView(); // find the spinner Context theme = getSupportActionBar().getThemedContext(); if(theme == null) return; //another check for a rare bug ArrayAdapter<Folder> mSpinnerAdapter = new ArrayAdapter<Folder>(theme, android.R.layout.simple_spinner_dropdown_item, data); s.setAdapter(mSpinnerAdapter); // set the adapter s.setSelection(0, false); s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { mDiscogs.setFolderId(((Folder) adapterView.getItemAtPosition(i)).folderid); //reload list with id mReleaseList.loadList(); filter.collapseActionView(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { //filter.collapseActionView(); } }); } } }); } //make sure only one actionview is expanded MenuItemCompat.setOnActionExpandListener(filter,new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem menuItem) { //collapse search search.collapseActionView(); return true; } @Override public boolean onMenuItemActionCollapse(MenuItem menuItem) { return true; } }); MenuItemCompat.setOnActionExpandListener(search,new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem menuItem) { //collapse search filter.collapseActionView(); return true; } @Override public boolean onMenuItemActionCollapse(MenuItem menuItem) { return true; } }); //s.setSelection(mSearchType,false); if (mSelected > 0) { inflater.inflate(R.menu.release_detail_scrobble, menu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if(id == R.id.list_refresh) { //refresh the list mReleaseList.refreshCollection(); } if(id == R.id.detail_scrobble_release) { //if tracklist is available, always scrobble from this view if(mPanes==3 && mReleaseTracklist!=null) { mReleaseTracklist.scrobble(); } else if (mPanes==2 && mReleasePager!=null) { mReleasePager.scrobble(); } } return super.onOptionsItemSelected(item); } /** * Callback method from {@link ReleaseListFragment.Callbacks} * indicating that the item with the given ID was selected. */ @Override public void onItemSelected(long id) { mSelected = id; switch (mPanes) { case 1: //just start new activity with the details Intent detailIntent = new Intent(this, ReleaseDetailActivity.class); detailIntent.putExtra(ReleaseDetailFragment.ARG_ITEM_ID, id); detailIntent.putExtra(ReleasePagerFragment.SHOW_VERSIONS, false); startActivity(detailIntent); break; case 2: //show the pager fragment next to the list invalidateOptionsMenu(); Bundle arguments2 = new Bundle(); arguments2.putLong(ReleaseDetailFragment.ARG_ITEM_ID, id); arguments2.putBoolean(ReleasePagerFragment.SHOW_VERSIONS, false); arguments2.putBoolean(ReleasePagerFragment.HAS_MENU, false); mReleasePager = new ReleasePagerFragment(); mReleasePager.setArguments(arguments2); getSupportFragmentManager().beginTransaction() .replace(R.id.release_pager_container, mReleasePager) .commit(); findViewById(R.id.release_pager_container).setVisibility(View.VISIBLE); break; case 3: //whoa, screen estate! Show detail view _and_ tracklist invalidateOptionsMenu(); Bundle arguments3 = new Bundle(); arguments3.putLong(ReleaseDetailFragment.ARG_ITEM_ID, id); mReleaseDetail = new ReleaseDetailFragment(); mReleaseDetail.setArguments(arguments3); Bundle arguments3_t = new Bundle(); arguments3_t.putLong(ReleaseTracklistFragment.ARG_ITEM_ID, id); mReleaseTracklist = new ReleaseTracklistFragment(); mReleaseTracklist.setArguments(arguments3_t); getSupportFragmentManager().beginTransaction() .replace(R.id.release_detail_container, mReleaseDetail) .replace(R.id.release_tracklist_container, mReleaseTracklist) .commit(); findViewById(R.id.release_detail_container).setVisibility(View.VISIBLE); findViewById(R.id.release_tracklist_container).setVisibility(View.VISIBLE); break; } } @Override public void onAdapterSet() { mLoaded = true; if(mReleaseProgressBar!=null) mReleaseProgressBar.setVisibility(View.INVISIBLE); } public void setRefreshVisible(boolean visible) { mRefresh = visible; if(mRefreshProgressBar!=null) { if(visible) { mRefreshProgressBar.setVisibility(View.VISIBLE); } else { mRefreshProgressBar.setVisibility(View.GONE); } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSelected > 0) { // Serialize and persist the activated item position. outState.putLong(STATE_RELEASE_SELECTED, mSelected); } outState.putInt(STATE_PANES, mPanes); } }
package net.lightbody.bmp.filters; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import net.lightbody.bmp.BrowserMobProxyServer; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersAdapter; import org.littleshoot.proxy.HttpFiltersSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * The filter "driver" that delegates to all chained filters specified by the proxy server. */ public class BrowserMobHttpFilterChain extends HttpFiltersAdapter { private static final Logger log = LoggerFactory.getLogger(BrowserMobHttpFilterChain.class); private final BrowserMobProxyServer proxyServer; private final List<HttpFilters> filters; public BrowserMobHttpFilterChain(BrowserMobProxyServer proxyServer, HttpRequest originalRequest, ChannelHandlerContext ctx) { super(originalRequest, ctx); this.proxyServer = proxyServer; if (proxyServer.getFilterFactories() != null) { filters = new ArrayList<>(proxyServer.getFilterFactories().size()); // instantiate all HttpFilters using the proxy's filter factories for (HttpFiltersSource filterFactory : proxyServer.getFilterFactories()) { HttpFilters filter = filterFactory.filterRequest(originalRequest, ctx); // allow filter factories to avoid adding a filter on a per-request basis by returning a null // HttpFilters instance if (filter != null) { filters.add(filter); } } } else { filters = Collections.emptyList(); } } @Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { if (proxyServer.isStopped()) { log.warn("Aborting request to {} because proxy is stopped", originalRequest.getUri()); HttpResponse abortedResponse = new DefaultFullHttpResponse(originalRequest.getProtocolVersion(), HttpResponseStatus.SERVICE_UNAVAILABLE); HttpHeaders.setContentLength(abortedResponse, 0L); return abortedResponse; } for (HttpFilters filter : filters) { try { HttpResponse filterResponse = filter.clientToProxyRequest(httpObject); if (filterResponse != null) { // if we are short-circuiting the response to an HttpRequest, update ModifiedRequestAwareFilter instances // with this (possibly) modified HttpRequest before returning the short-circuit response if (httpObject instanceof HttpRequest) { updateFiltersWithModifiedResponse((HttpRequest) httpObject); } return filterResponse; } } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } // if this httpObject is the HTTP request, set the modified request object on all ModifiedRequestAwareFilter // instances, so they have access to all modifications the request filters made while filtering if (httpObject instanceof HttpRequest) { updateFiltersWithModifiedResponse((HttpRequest) httpObject); } return null; } @Override public HttpResponse proxyToServerRequest(HttpObject httpObject) { for (HttpFilters filter : filters) { try { HttpResponse filterResponse = filter.proxyToServerRequest(httpObject); if (filterResponse != null) { return filterResponse; } } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } return null; } @Override public void proxyToServerRequestSending() { for (HttpFilters filter : filters) { try { filter.proxyToServerRequestSending(); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } } @Override public HttpObject serverToProxyResponse(HttpObject httpObject) { HttpObject processedHttpObject = httpObject; for (HttpFilters filter : filters) { try { processedHttpObject = filter.serverToProxyResponse(processedHttpObject); if (processedHttpObject == null) { return null; } } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } return processedHttpObject; } @Override public void serverToProxyResponseTimedOut() { for (HttpFilters filter : filters) { try { filter.serverToProxyResponseTimedOut(); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } } @Override public void serverToProxyResponseReceiving() { for (HttpFilters filter : filters) { try { filter.serverToProxyResponseReceiving(); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } } @Override public InetSocketAddress proxyToServerResolutionStarted(String resolvingServerHostAndPort) { InetSocketAddress overrideAddress = null; String newServerHostAndPort = resolvingServerHostAndPort; for (HttpFilters filter : filters) { try { InetSocketAddress filterResult = filter.proxyToServerResolutionStarted(newServerHostAndPort); if (filterResult != null) { overrideAddress = filterResult; newServerHostAndPort = filterResult.getHostString() + ":" + filterResult.getPort(); } } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } return overrideAddress; } @Override public void proxyToServerResolutionFailed(String hostAndPort) { for (HttpFilters filter : filters) { try { filter.proxyToServerResolutionFailed(hostAndPort); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } } @Override public void proxyToServerResolutionSucceeded(String serverHostAndPort, InetSocketAddress resolvedRemoteAddress) { for (HttpFilters filter : filters) { try { filter.proxyToServerResolutionSucceeded(serverHostAndPort, resolvedRemoteAddress); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } super.proxyToServerResolutionSucceeded(serverHostAndPort, resolvedRemoteAddress); } @Override public void proxyToServerConnectionStarted() { for (HttpFilters filter : filters) { try { filter.proxyToServerConnectionStarted(); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } } @Override public void proxyToServerConnectionSSLHandshakeStarted() { for (HttpFilters filter : filters) { try { filter.proxyToServerConnectionSSLHandshakeStarted(); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } } @Override public void proxyToServerConnectionFailed() { for (HttpFilters filter : filters) { try { filter.proxyToServerConnectionFailed(); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } } @Override public void proxyToServerConnectionSucceeded(ChannelHandlerContext serverCtx) { for (HttpFilters filter : filters) { try { filter.proxyToServerConnectionSucceeded(serverCtx); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } } @Override public void proxyToServerRequestSent() { for (HttpFilters filter : filters) { try { filter.proxyToServerRequestSent(); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } } @Override public void serverToProxyResponseReceived() { for (HttpFilters filter : filters) { try { filter.serverToProxyResponseReceived(); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } } @Override public HttpObject proxyToClientResponse(HttpObject httpObject) { HttpObject processedHttpObject = httpObject; for (HttpFilters filter : filters) { try { processedHttpObject = filter.proxyToClientResponse(processedHttpObject); if (processedHttpObject == null) { return null; } } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } return processedHttpObject; } @Override public void proxyToServerConnectionQueued() { for (HttpFilters filter : filters) { try { filter.proxyToServerConnectionQueued(); } catch (RuntimeException e) { log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e); } } } /** * Updates {@link ModifiedRequestAwareFilter} filters with the final, modified request after all request filters have * processed the request. * * @param modifiedRequest the modified HttpRequest after all filters have finished processing it */ private void updateFiltersWithModifiedResponse(HttpRequest modifiedRequest) { for (HttpFilters filter : filters) { if (filter instanceof ModifiedRequestAwareFilter) { ModifiedRequestAwareFilter requestCaptureFilter = (ModifiedRequestAwareFilter) filter; try { requestCaptureFilter.setModifiedHttpRequest(modifiedRequest); } catch (RuntimeException e) { log.warn("ModifiedRequestAwareFilter in filter chain threw exception while setting modified HTTP request.", e); } } } } }
package org.hisp.dhis.common; /* * Copyright (c) 2004-2016, University of Oslo * 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 the HISP project 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. */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.Set; import org.hibernate.SessionFactory; import org.hisp.dhis.DhisSpringTest; import org.hisp.dhis.security.acl.AccessStringHelper; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dataelement.DataElementGroup; import org.hisp.dhis.dataelement.DataElementOperand; import org.hisp.dhis.dataelement.DataElementService; import org.hisp.dhis.hibernate.exception.CreateAccessDeniedException; import org.hisp.dhis.hibernate.exception.DeleteAccessDeniedException; import org.hisp.dhis.indicator.Indicator; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.user.User; import org.hisp.dhis.user.UserGroup; import org.hisp.dhis.user.UserGroupAccess; import org.hisp.dhis.user.UserService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; /** * @author Morten Olav Hansen <mortenoh@gmail.com> */ public class IdentifiableObjectManagerTest extends DhisSpringTest { @Autowired private SessionFactory sessionFactory; @Autowired private DataElementService dataElementService; @Autowired private IdentifiableObjectManager identifiableObjectManager; @Autowired private UserService _userService; @Override protected void setUpTest() throws Exception { this.userService = _userService; } @Test public void testGetObjectWithIdScheme() { DataElement dataElementA = createDataElement( 'A' ); dataElementService.addDataElement( dataElementA ); assertEquals( dataElementA, identifiableObjectManager.get( DataDimensionItem.DATA_DIMENSION_CLASSES, IdScheme.CODE, dataElementA.getCode() ) ); assertEquals( dataElementA, identifiableObjectManager.get( DataDimensionItem.DATA_DIMENSION_CLASSES, IdScheme.UID, dataElementA.getUid() ) ); } @Test public void testGetObject() { DataElement dataElementA = createDataElement( 'A' ); DataElement dataElementB = createDataElement( 'B' ); int dataElementIdA = dataElementService.addDataElement( dataElementA ); int dataElementIdB = dataElementService.addDataElement( dataElementB ); DataElementGroup dataElementGroupA = createDataElementGroup( 'A' ); DataElementGroup dataElementGroupB = createDataElementGroup( 'B' ); int dataElementGroupIdA = dataElementService.addDataElementGroup( dataElementGroupA ); int dataElementGroupIdB = dataElementService.addDataElementGroup( dataElementGroupB ); assertEquals( dataElementA, identifiableObjectManager.getObject( dataElementIdA, DataElement.class.getSimpleName() ) ); assertEquals( dataElementB, identifiableObjectManager.getObject( dataElementIdB, DataElement.class.getSimpleName() ) ); assertEquals( dataElementGroupA, identifiableObjectManager.getObject( dataElementGroupIdA, DataElementGroup.class.getSimpleName() ) ); assertEquals( dataElementGroupB, identifiableObjectManager.getObject( dataElementGroupIdB, DataElementGroup.class.getSimpleName() ) ); } @Test public void testGetWithClasses() { DataElement dataElementA = createDataElement( 'A' ); DataElement dataElementB = createDataElement( 'B' ); dataElementService.addDataElement( dataElementA ); dataElementService.addDataElement( dataElementB ); Set<Class<? extends IdentifiableObject>> classes = ImmutableSet.<Class<? extends IdentifiableObject>>builder(). add( Indicator.class ).add( DataElement.class ).add( DataElementOperand.class ).build(); assertEquals( dataElementA, identifiableObjectManager.get( classes, dataElementA.getUid() ) ); assertEquals( dataElementB, identifiableObjectManager.get( classes, dataElementB.getUid() ) ); } @Test public void publicAccessSetIfNoUser() { DataElement dataElement = createDataElement( 'A' ); identifiableObjectManager.save( dataElement ); assertNotNull( dataElement.getPublicAccess() ); assertFalse( AccessStringHelper.canRead( dataElement.getPublicAccess() ) ); assertFalse( AccessStringHelper.canWrite( dataElement.getPublicAccess() ) ); } @Test public void getCount() { identifiableObjectManager.save( createDataElement( 'A' ) ); identifiableObjectManager.save( createDataElement( 'B' ) ); identifiableObjectManager.save( createDataElement( 'C' ) ); identifiableObjectManager.save( createDataElement( 'D' ) ); assertEquals( 4, identifiableObjectManager.getCount( DataElement.class ) ); } @Test public void getCountLikeName() { identifiableObjectManager.save( createDataElement( 'A' ) ); identifiableObjectManager.save( createDataElement( 'B' ) ); identifiableObjectManager.save( createDataElement( 'C' ) ); identifiableObjectManager.save( createDataElement( 'D' ) ); assertEquals( 1, identifiableObjectManager.getCountLikeName( DataElement.class, "DataElementA" ) ); assertEquals( 1, identifiableObjectManager.getCountLikeName( DataElement.class, "DataElementB" ) ); assertEquals( 1, identifiableObjectManager.getCountLikeName( DataElement.class, "DataElementC" ) ); assertEquals( 1, identifiableObjectManager.getCountLikeName( DataElement.class, "DataElementD" ) ); } @Test public void getCountLikeShortName() { identifiableObjectManager.save( createDataElement( 'A' ) ); identifiableObjectManager.save( createDataElement( 'B' ) ); identifiableObjectManager.save( createDataElement( 'C' ) ); identifiableObjectManager.save( createDataElement( 'D' ) ); assertEquals( 1, identifiableObjectManager.getCountLikeShortName( DataElement.class, "DataElementShortA" ) ); assertEquals( 1, identifiableObjectManager.getCountLikeShortName( DataElement.class, "DataElementShortB" ) ); assertEquals( 1, identifiableObjectManager.getCountLikeShortName( DataElement.class, "DataElementShortC" ) ); assertEquals( 1, identifiableObjectManager.getCountLikeShortName( DataElement.class, "DataElementShortD" ) ); } @Test public void getEqualToName() { DataElement dataElement = createDataElement( 'A' ); identifiableObjectManager.save( dataElement ); assertNotNull( identifiableObjectManager.getByName( DataElement.class, "DataElementA" ) ); assertNull( identifiableObjectManager.getByName( DataElement.class, "DataElementB" ) ); assertEquals( dataElement, identifiableObjectManager.getByName( DataElement.class, "DataElementA" ) ); } @Test public void getAllEqualToName() { OrganisationUnit organisationUnitA1 = createOrganisationUnit( 'A' ); organisationUnitA1.setCode( null ); identifiableObjectManager.save( organisationUnitA1 ); OrganisationUnit organisationUnitA2 = createOrganisationUnit( 'B' ); organisationUnitA2.setName( "OrganisationUnitA" ); organisationUnitA2.setCode( null ); identifiableObjectManager.save( organisationUnitA2 ); assertEquals( 2, identifiableObjectManager.getAllByName( OrganisationUnit.class, "OrganisationUnitA" ).size() ); assertEquals( 0, identifiableObjectManager.getAllByName( OrganisationUnit.class, "organisationunita" ).size() ); } @Test public void getAllEqualToNameIgnoreCase() { OrganisationUnit organisationUnitC1 = createOrganisationUnit( 'C' ); organisationUnitC1.setCode( null ); identifiableObjectManager.save( organisationUnitC1 ); OrganisationUnit organisationUnitC2 = createOrganisationUnit( 'D' ); organisationUnitC2.setName( "OrganisationUnitC" ); organisationUnitC2.setCode( null ); identifiableObjectManager.save( organisationUnitC2 ); assertEquals( 2, identifiableObjectManager.getAllByNameIgnoreCase( OrganisationUnit.class, "OrganisationUnitC" ).size() ); assertEquals( 2, identifiableObjectManager.getAllByNameIgnoreCase( OrganisationUnit.class, "organisationunitc" ).size() ); } @Test public void getLikeName() { identifiableObjectManager.save( createDataElement( 'A' ) ); identifiableObjectManager.save( createDataElement( 'B' ) ); identifiableObjectManager.save( createDataElement( 'C' ) ); identifiableObjectManager.save( createDataElement( 'D' ) ); assertEquals( 4, identifiableObjectManager.getCountLikeName( DataElement.class, "DataElement" ) ); assertEquals( 4, identifiableObjectManager.getCountLikeName( DataElement.class, "dataElement" ) ); assertEquals( 4, identifiableObjectManager.getLikeName( DataElement.class, "DataElement" ).size() ); assertEquals( 4, identifiableObjectManager.getLikeName( DataElement.class, "dataElement" ).size() ); } @Test public void getAllLikeShortName() { identifiableObjectManager.save( createDataElement( 'A' ) ); identifiableObjectManager.save( createDataElement( 'B' ) ); identifiableObjectManager.save( createDataElement( 'C' ) ); identifiableObjectManager.save( createDataElement( 'D' ) ); assertEquals( 4, identifiableObjectManager.getCountLikeShortName( DataElement.class, "DataElementShort" ) ); assertEquals( 4, identifiableObjectManager.getCountLikeShortName( DataElement.class, "dataElementSHORT" ) ); assertEquals( 4, identifiableObjectManager.getLikeShortName( DataElement.class, "DataElementShort" ).size() ); assertEquals( 4, identifiableObjectManager.getLikeShortName( DataElement.class, "dataElementSHORT" ).size() ); } @Test public void getAllOrderedName() { identifiableObjectManager.save( createDataElement( 'D' ) ); identifiableObjectManager.save( createDataElement( 'B' ) ); identifiableObjectManager.save( createDataElement( 'C' ) ); identifiableObjectManager.save( createDataElement( 'A' ) ); List<DataElement> dataElements = new ArrayList<>( identifiableObjectManager.getAllSorted( DataElement.class ) ); assertEquals( 4, dataElements.size() ); assertEquals( "DataElementA", dataElements.get( 0 ).getName() ); assertEquals( "DataElementB", dataElements.get( 1 ).getName() ); assertEquals( "DataElementC", dataElements.get( 2 ).getName() ); assertEquals( "DataElementD", dataElements.get( 3 ).getName() ); } @Test public void getAllOrderedLastUpdated() { DataElement dataElementA = createDataElement( 'A' ); DataElement dataElementB = createDataElement( 'B' ); DataElement dataElementC = createDataElement( 'C' ); DataElement dataElementD = createDataElement( 'D' ); identifiableObjectManager.save( dataElementA ); identifiableObjectManager.save( dataElementB ); identifiableObjectManager.save( dataElementC ); identifiableObjectManager.save( dataElementD ); dataElementA.setLastUpdated( new GregorianCalendar( 2011, 0, 1 ).getTime() ); dataElementB.setLastUpdated( new GregorianCalendar( 2012, 0, 1 ).getTime() ); dataElementC.setLastUpdated( new GregorianCalendar( 2013, 0, 1 ).getTime() ); dataElementD.setLastUpdated( new GregorianCalendar( 2014, 0, 1 ).getTime() ); sessionFactory.getCurrentSession().update( dataElementA ); sessionFactory.getCurrentSession().update( dataElementB ); sessionFactory.getCurrentSession().update( dataElementC ); sessionFactory.getCurrentSession().update( dataElementD ); List<DataElement> dataElements = new ArrayList<>( identifiableObjectManager.getAllSortedByLastUpdated( DataElement.class ) ); assertEquals( 4, dataElements.size() ); assertEquals( "DataElementD", dataElements.get( 0 ).getName() ); assertEquals( "DataElementC", dataElements.get( 1 ).getName() ); assertEquals( "DataElementB", dataElements.get( 2 ).getName() ); assertEquals( "DataElementA", dataElements.get( 3 ).getName() ); } @Test public void userIsCurrentIfNoUserSet() { User user = createUserAndInjectSecurityContext( true ); DataElement dataElement = createDataElement( 'A' ); identifiableObjectManager.save( dataElement ); assertNotNull( dataElement.getUser() ); assertEquals( user, dataElement.getUser() ); } @Test public void userCanCreatePublic() { createUserAndInjectSecurityContext( false, "F_DATAELEMENT_PUBLIC_ADD" ); DataElement dataElement = createDataElement( 'A' ); identifiableObjectManager.save( dataElement ); assertNotNull( dataElement.getPublicAccess() ); assertTrue( AccessStringHelper.canRead( dataElement.getPublicAccess() ) ); assertTrue( AccessStringHelper.canWrite( dataElement.getPublicAccess() ) ); } @Test public void userCanCreatePrivate() { createUserAndInjectSecurityContext( false, "F_DATAELEMENT_PRIVATE_ADD" ); DataElement dataElement = createDataElement( 'A' ); identifiableObjectManager.save( dataElement ); assertNotNull( dataElement.getPublicAccess() ); assertFalse( AccessStringHelper.canRead( dataElement.getPublicAccess() ) ); assertFalse( AccessStringHelper.canWrite( dataElement.getPublicAccess() ) ); } @Test( expected = CreateAccessDeniedException.class ) public void userDeniedCreateObject() { createUserAndInjectSecurityContext( false ); identifiableObjectManager.save( createDataElement( 'A' ) ); } @Test public void publicUserModifiedPublicAccessDEFAULT() { createUserAndInjectSecurityContext( false, "F_DATAELEMENT_PUBLIC_ADD" ); DataElement dataElement = createDataElement( 'A' ); dataElement.setPublicAccess( AccessStringHelper.DEFAULT ); identifiableObjectManager.save( dataElement, false ); assertFalse( AccessStringHelper.canRead( dataElement.getPublicAccess() ) ); assertFalse( AccessStringHelper.canWrite( dataElement.getPublicAccess() ) ); } @Test public void publicUserModifiedPublicAccessRW() { createUserAndInjectSecurityContext( false, "F_DATAELEMENT_PUBLIC_ADD" ); DataElement dataElement = createDataElement( 'A' ); dataElement.setPublicAccess( AccessStringHelper.READ_WRITE ); identifiableObjectManager.save( dataElement, false ); } @Test( expected = CreateAccessDeniedException.class ) public void privateUserModifiedPublicAccessRW() { createUserAndInjectSecurityContext( false, "F_DATAELEMENT_PRIVATE_ADD" ); DataElement dataElement = createDataElement( 'A' ); dataElement.setPublicAccess( AccessStringHelper.READ_WRITE ); identifiableObjectManager.save( dataElement, false ); } @Test public void privateUserModifiedPublicAccessDEFAULT() { createUserAndInjectSecurityContext( false, "F_DATAELEMENT_PRIVATE_ADD" ); DataElement dataElement = createDataElement( 'A' ); dataElement.setPublicAccess( AccessStringHelper.DEFAULT ); identifiableObjectManager.save( dataElement, false ); } // TODO this should actually throw a UpdateAccessDeniedException, but the problem is that we only have access to the updated object @Test( /* expected = UpdateAccessDeniedException.class */ ) public void updateForPrivateUserDeniedAfterChangePublicAccessRW() { createUserAndInjectSecurityContext( false, "F_DATAELEMENT_PRIVATE_ADD" ); DataElement dataElement = createDataElement( 'A' ); dataElement.setPublicAccess( AccessStringHelper.DEFAULT ); identifiableObjectManager.save( dataElement, false ); dataElement.setPublicAccess( AccessStringHelper.READ_WRITE ); identifiableObjectManager.update( dataElement ); } @Test( expected = CreateAccessDeniedException.class ) public void userDeniedForPublicAdd() { createUserAndInjectSecurityContext( false ); DataElement dataElement = createDataElement( 'A' ); dataElement.setPublicAccess( AccessStringHelper.READ_WRITE ); identifiableObjectManager.save( dataElement, false ); } @Test( expected = DeleteAccessDeniedException.class ) public void userDeniedDeleteObject() { createUserAndInjectSecurityContext( false, "F_DATAELEMENT_PUBLIC_ADD", "F_USER_ADD" ); User user = createUser( 'B' ); identifiableObjectManager.save( user ); DataElement dataElement = createDataElement( 'A' ); identifiableObjectManager.save( dataElement ); dataElement.setUser( user ); dataElement.setPublicAccess( AccessStringHelper.DEFAULT ); sessionFactory.getCurrentSession().update( dataElement ); identifiableObjectManager.delete( dataElement ); } @Test public void objectsWithNoUser() { identifiableObjectManager.save( createDataElement( 'A' ) ); identifiableObjectManager.save( createDataElement( 'B' ) ); identifiableObjectManager.save( createDataElement( 'C' ) ); identifiableObjectManager.save( createDataElement( 'D' ) ); assertEquals( 4, identifiableObjectManager.getCount( DataElement.class ) ); assertEquals( 4, identifiableObjectManager.getAll( DataElement.class ).size() ); } @Test public void readPrivateObjects() { createUserAndInjectSecurityContext( false, "F_DATAELEMENT_PUBLIC_ADD", "F_USER_ADD" ); User user = createUser( 'B' ); identifiableObjectManager.save( user ); identifiableObjectManager.save( createDataElement( 'A' ) ); identifiableObjectManager.save( createDataElement( 'B' ) ); identifiableObjectManager.save( createDataElement( 'C' ) ); identifiableObjectManager.save( createDataElement( 'D' ) ); assertEquals( 4, identifiableObjectManager.getAll( DataElement.class ).size() ); List<DataElement> dataElements = new ArrayList<>( identifiableObjectManager.getAll( DataElement.class ) ); for ( DataElement dataElement : dataElements ) { dataElement.setUser( user ); dataElement.setPublicAccess( AccessStringHelper.DEFAULT ); sessionFactory.getCurrentSession().update( dataElement ); } assertEquals( 0, identifiableObjectManager.getCount( DataElement.class ) ); assertEquals( 0, identifiableObjectManager.getAll( DataElement.class ).size() ); } @Test public void readUserGroupSharedObjects() { User loginUser = createUserAndInjectSecurityContext( false, "F_DATAELEMENT_PUBLIC_ADD", "F_USER_ADD", "F_USERGROUP_PUBLIC_ADD" ); User user = createUser( 'B' ); identifiableObjectManager.save( user ); UserGroup userGroup = createUserGroup( 'A', Sets.newHashSet( loginUser ) ); identifiableObjectManager.save( userGroup ); identifiableObjectManager.save( createDataElement( 'A' ) ); identifiableObjectManager.save( createDataElement( 'B' ) ); identifiableObjectManager.save( createDataElement( 'C' ) ); identifiableObjectManager.save( createDataElement( 'D' ) ); assertEquals( 4, identifiableObjectManager.getCount( DataElement.class ) ); assertEquals( 4, identifiableObjectManager.getAll( DataElement.class ).size() ); List<DataElement> dataElements = new ArrayList<>( identifiableObjectManager.getAll( DataElement.class ) ); for ( DataElement dataElement : dataElements ) { dataElement.setUser( user ); dataElement.setPublicAccess( AccessStringHelper.newInstance().build() ); UserGroupAccess userGroupAccess = new UserGroupAccess(); userGroupAccess.setAccess( AccessStringHelper.READ ); userGroupAccess.setUserGroup( userGroup ); sessionFactory.getCurrentSession().save( userGroupAccess ); dataElement.getUserGroupAccesses().add( userGroupAccess ); sessionFactory.getCurrentSession().update( dataElement ); } assertEquals( 4, identifiableObjectManager.getCount( DataElement.class ) ); assertEquals( 4, identifiableObjectManager.getAll( DataElement.class ).size() ); } @Test public void getAllGeCreated() { DataElement dataElementA = createDataElement( 'A' ); DataElement dataElementB = createDataElement( 'B' ); DataElement dataElementC = createDataElement( 'C' ); DataElement dataElementD = createDataElement( 'D' ); identifiableObjectManager.save( dataElementA ); identifiableObjectManager.save( dataElementB ); identifiableObjectManager.save( dataElementC ); identifiableObjectManager.save( dataElementD ); dataElementA.setCreated( new GregorianCalendar( 2014, 0, 1 ).getTime() ); dataElementB.setCreated( new GregorianCalendar( 2013, 0, 1 ).getTime() ); dataElementC.setCreated( new GregorianCalendar( 2012, 0, 1 ).getTime() ); dataElementD.setCreated( new GregorianCalendar( 2011, 0, 1 ).getTime() ); sessionFactory.getCurrentSession().update( dataElementA ); sessionFactory.getCurrentSession().update( dataElementB ); sessionFactory.getCurrentSession().update( dataElementC ); sessionFactory.getCurrentSession().update( dataElementD ); assertEquals( 2, identifiableObjectManager.getCountByCreated( DataElement.class, new GregorianCalendar( 2012, 5, 1 ).getTime() ) ); assertEquals( 2, identifiableObjectManager.getByCreated( DataElement.class, new GregorianCalendar( 2012, 5, 1 ).getTime() ).size() ); } @Test public void getAllGeLastUpdated() { DataElement dataElementA = createDataElement( 'A' ); DataElement dataElementB = createDataElement( 'B' ); DataElement dataElementC = createDataElement( 'C' ); DataElement dataElementD = createDataElement( 'D' ); identifiableObjectManager.save( dataElementA ); identifiableObjectManager.save( dataElementB ); identifiableObjectManager.save( dataElementC ); identifiableObjectManager.save( dataElementD ); dataElementA.setLastUpdated( new GregorianCalendar( 2014, 0, 1 ).getTime() ); dataElementB.setLastUpdated( new GregorianCalendar( 2013, 0, 1 ).getTime() ); dataElementC.setLastUpdated( new GregorianCalendar( 2012, 0, 1 ).getTime() ); dataElementD.setLastUpdated( new GregorianCalendar( 2011, 0, 1 ).getTime() ); sessionFactory.getCurrentSession().update( dataElementA ); sessionFactory.getCurrentSession().update( dataElementB ); sessionFactory.getCurrentSession().update( dataElementC ); sessionFactory.getCurrentSession().update( dataElementD ); assertEquals( 2, identifiableObjectManager.getCountByLastUpdated( DataElement.class, new GregorianCalendar( 2012, 5, 1 ).getTime() ) ); assertEquals( 2, identifiableObjectManager.getByLastUpdated( DataElement.class, new GregorianCalendar( 2012, 5, 1 ).getTime() ).size() ); } @Test public void getByUidTest() { DataElement dataElementA = createDataElement( 'A' ); DataElement dataElementB = createDataElement( 'B' ); DataElement dataElementC = createDataElement( 'C' ); DataElement dataElementD = createDataElement( 'D' ); identifiableObjectManager.save( dataElementA ); identifiableObjectManager.save( dataElementB ); identifiableObjectManager.save( dataElementC ); identifiableObjectManager.save( dataElementD ); List<DataElement> ab = identifiableObjectManager.getByUid( DataElement.class, Arrays.asList( dataElementA.getUid(), dataElementB.getUid() ) ); List<DataElement> cd = identifiableObjectManager.getByUid( DataElement.class, Arrays.asList( dataElementC.getUid(), dataElementD.getUid() ) ); assertTrue( ab.contains( dataElementA ) ); assertTrue( ab.contains( dataElementB ) ); assertFalse( ab.contains( dataElementC ) ); assertFalse( ab.contains( dataElementD ) ); assertFalse( cd.contains( dataElementA ) ); assertFalse( cd.contains( dataElementB ) ); assertTrue( cd.contains( dataElementC ) ); assertTrue( cd.contains( dataElementD ) ); } @Test public void getByUidOrderedTest() { DataElement dataElementA = createDataElement( 'A' ); DataElement dataElementB = createDataElement( 'B' ); DataElement dataElementC = createDataElement( 'C' ); DataElement dataElementD = createDataElement( 'D' ); identifiableObjectManager.save( dataElementA ); identifiableObjectManager.save( dataElementB ); identifiableObjectManager.save( dataElementC ); identifiableObjectManager.save( dataElementD ); List<String> uids = Arrays.asList( dataElementA.getUid(), dataElementC.getUid(), dataElementB.getUid(), dataElementD.getUid() ); List<DataElement> expected = new ArrayList<>( Arrays.asList( dataElementA, dataElementC, dataElementB, dataElementD ) ); List<DataElement> actual = new ArrayList<>( identifiableObjectManager.getByUidOrdered( DataElement.class, uids ) ); assertEquals( expected, actual ); } @Test public void getByCodeTest() { DataElement dataElementA = createDataElement( 'A' ); DataElement dataElementB = createDataElement( 'B' ); DataElement dataElementC = createDataElement( 'C' ); DataElement dataElementD = createDataElement( 'D' ); dataElementA.setCode("DE_A"); dataElementB.setCode("DE_B"); dataElementC.setCode("DE_C"); dataElementD.setCode("DE_D"); identifiableObjectManager.save( dataElementA ); identifiableObjectManager.save( dataElementB ); identifiableObjectManager.save( dataElementC ); identifiableObjectManager.save( dataElementD ); List<DataElement> ab = identifiableObjectManager.getByCode( DataElement.class, Arrays.asList( dataElementA.getCode(), dataElementB.getCode() ) ); List<DataElement> cd = identifiableObjectManager.getByCode( DataElement.class, Arrays.asList( dataElementC.getCode(), dataElementD.getCode() ) ); assertTrue( ab.contains( dataElementA ) ); assertTrue( ab.contains( dataElementB ) ); assertFalse( ab.contains( dataElementC ) ); assertFalse( ab.contains( dataElementD ) ); assertFalse( cd.contains( dataElementA ) ); assertFalse( cd.contains( dataElementB ) ); assertTrue( cd.contains( dataElementC ) ); assertTrue( cd.contains( dataElementD ) ); } @Test public void testGetObjects() { OrganisationUnit unit1 = createOrganisationUnit( 'A' ); OrganisationUnit unit2 = createOrganisationUnit( 'B' ); OrganisationUnit unit3 = createOrganisationUnit( 'C' ); identifiableObjectManager.save( unit1 ); identifiableObjectManager.save( unit2 ); identifiableObjectManager.save( unit3 ); Set<String> codes = Sets.newHashSet( unit2.getCode(), unit3.getCode() ); List<OrganisationUnit> units = identifiableObjectManager.getObjects( OrganisationUnit.class, IdentifiableProperty.CODE, codes ); assertEquals( 2, units.size() ); assertTrue( units.contains( unit2 ) ); assertTrue( units.contains( unit3 ) ); } @Test public void testGetIdMapIdScheme() { DataElement dataElementA = createDataElement( 'A' ); DataElement dataElementB = createDataElement( 'B' ); dataElementService.addDataElement( dataElementA ); dataElementService.addDataElement( dataElementB ); Map<String, DataElement> map = identifiableObjectManager.getIdMap( DataElement.class, IdScheme.CODE ); assertEquals( dataElementA, map.get( "DataElementCodeA" ) ); assertEquals( dataElementB, map.get( "DataElementCodeB" ) ); assertNull( map.get( "DataElementCodeX" ) ); } }
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.util; import com.intellij.codeInsight.generation.*; import com.intellij.ide.IdeBundle; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.VerticalFlowLayout; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.SystemInfo; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.ui.ColoredTreeCellRenderer; import com.intellij.ui.NonFocusableCheckBox; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.Icons; import com.intellij.util.SmartList; import com.intellij.util.containers.Convertor; import com.intellij.util.containers.FactoryMap; import com.intellij.util.containers.HashMap; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.*; import java.util.List; public class MemberChooser<T extends ClassMember> extends DialogWrapper implements TypeSafeDataProvider { protected Tree myTree; private DefaultTreeModel myTreeModel; private JCheckBox myCopyJavadocCheckbox; private JCheckBox myInsertOverrideAnnotationCheckbox; private final ArrayList<MemberNode> mySelectedNodes = new ArrayList<MemberNode>(); private boolean mySorted = false; private boolean myShowClasses = true; private boolean myAllowEmptySelection = false; private boolean myAllowMultiSelection; private final Project myProject; private final boolean myIsInsertOverrideVisible; private final JComponent myHeaderPanel; private T[] myElements; private final HashMap<MemberNode,ParentNode> myNodeToParentMap = new HashMap<MemberNode, ParentNode>(); private final HashMap<ClassMember, MemberNode> myElementToNodeMap = new HashMap<ClassMember, MemberNode>(); private final ArrayList<ContainerNode> myContainerNodes = new ArrayList<ContainerNode>(); private LinkedHashSet<T> mySelectedElements; @NonNls private static final String PROP_SORTED = "MemberChooser.sorted"; @NonNls private static final String PROP_SHOWCLASSES = "MemberChooser.showClasses"; @NonNls private static final String PROP_COPYJAVADOC = "MemberChooser.copyJavadoc"; public MemberChooser(T[] elements, boolean allowEmptySelection, boolean allowMultiSelection, @NotNull Project project) { this(elements, allowEmptySelection, allowMultiSelection, project, false); } public MemberChooser(T[] elements, boolean allowEmptySelection, boolean allowMultiSelection, @NotNull Project project, boolean isInsertOverrideVisible) { this(elements, allowEmptySelection, allowMultiSelection, project, isInsertOverrideVisible, null); } public MemberChooser(T[] elements, boolean allowEmptySelection, boolean allowMultiSelection, @NotNull Project project, boolean isInsertOverrideVisible, JComponent headerPanel ) { super(project, true); myAllowEmptySelection = allowEmptySelection; myAllowMultiSelection = allowMultiSelection; myProject = project; myIsInsertOverrideVisible = isInsertOverrideVisible; myHeaderPanel = headerPanel; myTree = new Tree(new DefaultTreeModel(new DefaultMutableTreeNode())); resetElements(elements); init(); } public void resetElements(T[] elements) { myElements = elements; mySelectedNodes.clear(); myNodeToParentMap.clear(); myElementToNodeMap.clear(); myContainerNodes.clear(); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { myTreeModel = buildModel(); } }); myTree.setModel(myTreeModel); myTree.setRootVisible(false); doSort(); TreeUtil.expandAll(myTree); myCopyJavadocCheckbox = new NonFocusableCheckBox(IdeBundle.message("checkbox.copy.javadoc")); if (myIsInsertOverrideVisible) { myInsertOverrideAnnotationCheckbox = new NonFocusableCheckBox(IdeBundle.message("checkbox.insert.at.override")); } myTree.doLayout(); } /** * should be invoked in read action */ private DefaultTreeModel buildModel() { final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(); final Ref<Integer> count = new Ref<Integer>(0); final FactoryMap<MemberChooserObject,ParentNode> map = new FactoryMap<MemberChooserObject,ParentNode>() { protected ParentNode create(final MemberChooserObject key) { ParentNode node = null; if (key instanceof PsiElementMemberChooserObject) { final ContainerNode containerNode = new ContainerNode(rootNode, key, count); node = containerNode; myContainerNodes.add(containerNode); } if (node == null) { node = new ParentNode(rootNode, key, count); } return node; } }; for (T object : myElements) { final ParentNode parentNode = map.get(object.getParentNodeDelegate()); final MemberNode elementNode = new MemberNode(parentNode, object, count); myNodeToParentMap.put(elementNode, parentNode); myElementToNodeMap.put(object, elementNode); } return new DefaultTreeModel(rootNode); } public void selectElements(ClassMember[] elements) { ArrayList<TreePath> selectionPaths = new ArrayList<TreePath>(); for (ClassMember element : elements) { MemberNode treeNode = myElementToNodeMap.get(element); if (treeNode != null) { selectionPaths.add(new TreePath(treeNode.getPath())); } } myTree.setSelectionPaths(selectionPaths.toArray(new TreePath[selectionPaths.size()])); } protected Action[] createActions() { if (myAllowEmptySelection) { return new Action[]{getOKAction(), new SelectNoneAction(), getCancelAction()}; } else { return new Action[]{getOKAction(), getCancelAction()}; } } protected void doHelpAction() { } protected List<JComponent> customizeOptionsPanel() { final SmartList<JComponent> list = new SmartList<JComponent>(); if (myIsInsertOverrideVisible) { CodeStyleSettings styleSettings = CodeStyleSettingsManager.getInstance(myProject).getCurrentSettings(); myInsertOverrideAnnotationCheckbox.setSelected(styleSettings.INSERT_OVERRIDE_ANNOTATION); list.add(myInsertOverrideAnnotationCheckbox); } myCopyJavadocCheckbox.setSelected(PropertiesComponent.getInstance().isTrueValue(PROP_COPYJAVADOC)); list.add(myCopyJavadocCheckbox); return list; } protected JComponent createSouthPanel() { JPanel panel = new JPanel(new GridBagLayout()); JPanel optionsPanel = new JPanel(new VerticalFlowLayout()); for (final JComponent component : customizeOptionsPanel()) { optionsPanel.add(component); } panel.add( optionsPanel, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0) ); if (myElements == null || myElements.length == 0) { setOKActionEnabled(false); } panel.add( super.createSouthPanel(), new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0) ); return panel; } @Override protected JComponent createNorthPanel() { return myHeaderPanel; } protected JComponent createCenterPanel() { JPanel panel = new JPanel(new BorderLayout()); // Toolbar DefaultActionGroup group = new DefaultActionGroup(); fillToolbarActions(group); group.addSeparator(); ExpandAllAction expandAllAction = new ExpandAllAction(); expandAllAction.registerCustomShortcutSet( new CustomShortcutSet( KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, SystemInfo.isMac ? InputEvent.META_MASK : InputEvent.CTRL_MASK)), myTree); group.add(expandAllAction); CollapseAllAction collapseAllAction = new CollapseAllAction(); collapseAllAction.registerCustomShortcutSet( new CustomShortcutSet( KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, SystemInfo.isMac ? InputEvent.META_MASK : InputEvent.CTRL_MASK)), myTree); group.add(collapseAllAction); panel.add(ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true).getComponent(), BorderLayout.NORTH); // Tree myTree.setCellRenderer(new ColoredTreeCellRenderer() { public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof ElementNode) { ((ElementNode) value).getDelegate().renderTreeNode(this, tree); } } } ); UIUtil.setLineStyleAngled(myTree); myTree.setRootVisible(false); myTree.setShowsRootHandles(true); myTree.addKeyListener(new TreeKeyListener()); myTree.addTreeSelectionListener(new MyTreeSelectionListener()); if (!myAllowMultiSelection) { myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); } if (getRootNode().getChildCount() > 0) { myTree.expandRow(0); myTree.setSelectionRow(1); } TreeUtil.expandAll(myTree); final TreeSpeedSearch treeSpeedSearch = new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() { @Nullable public String convert(TreePath path) { final ElementNode lastPathComponent = (ElementNode)path.getLastPathComponent(); if (lastPathComponent == null) return null; final MemberChooserObject delegate = lastPathComponent.getDelegate(); return delegate.getText(); } }); treeSpeedSearch.addChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { myTree.repaint(); // to update match highlighting } }); myTree.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { if (myTree.getPathForLocation(e.getX(), e.getY()) != null) { doOKAction(); } } } } ); TreeUtil.installActions(myTree); JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree); scrollPane.setPreferredSize(new Dimension(350, 450)); panel.add(scrollPane, BorderLayout.CENTER); return panel; } protected void fillToolbarActions(DefaultActionGroup group) { SortEmAction sortAction = new SortEmAction(); sortAction.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.ALT_MASK)), myTree); setSorted(PropertiesComponent.getInstance().isTrueValue(PROP_SORTED)); group.add(sortAction); ShowContainersAction showContainersAction = getShowContainersAction(); showContainersAction.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.ALT_MASK)), myTree); setShowClasses(PropertiesComponent.getInstance().isTrueValue(PROP_SHOWCLASSES)); group.add(showContainersAction); } protected String getDimensionServiceKey() { return "#com.intellij.ide.util.MemberChooser"; } public JComponent getPreferredFocusedComponent() { return myTree; } @Nullable private LinkedHashSet<T> getSelectedElementsList() { return getExitCode() == OK_EXIT_CODE ? mySelectedElements : null; } @Nullable public List<T> getSelectedElements() { final LinkedHashSet<T> list = getSelectedElementsList(); return list == null ? null : new ArrayList<T>(list); } @Nullable public T[] getSelectedElements(T[] a) { LinkedHashSet<T> list = getSelectedElementsList(); if (list == null) return null; return list.toArray(a); } protected final boolean areElementsSelected() { return mySelectedElements != null && !mySelectedElements.isEmpty(); } public void setCopyJavadocVisible(boolean state) { myCopyJavadocCheckbox.setVisible(state); } public boolean isCopyJavadoc() { return myCopyJavadocCheckbox.isSelected(); } public boolean isInsertOverrideAnnotation () { return myIsInsertOverrideVisible && myInsertOverrideAnnotationCheckbox.isSelected(); } private boolean isSorted() { return mySorted; } private void setSorted(boolean sorted) { if (mySorted == sorted) return; mySorted = sorted; doSort(); } private void doSort() { Pair<ElementNode,List<ElementNode>> pair = storeSelection(); Enumeration<ParentNode> children = getRootNodeChildren(); while (children.hasMoreElements()) { ParentNode classNode = children.nextElement(); sortNode(classNode, mySorted); myTreeModel.nodeStructureChanged(classNode); } restoreSelection(pair); } private static void sortNode(ParentNode node, boolean sorted) { ArrayList<MemberNode> arrayList = new ArrayList<MemberNode>(); Enumeration<MemberNode> children = node.children(); while (children.hasMoreElements()) { arrayList.add(children.nextElement()); } Collections.sort(arrayList, sorted ? new AlphaComparator() : new OrderComparator()); replaceChildren(node, arrayList); } private static void replaceChildren(final DefaultMutableTreeNode node, final Collection<? extends ElementNode> arrayList) { node.removeAllChildren(); for (ElementNode child : arrayList) { node.add(child); } } private void setShowClasses(boolean showClasses) { myShowClasses = showClasses; Pair<ElementNode,List<ElementNode>> selection = storeSelection(); DefaultMutableTreeNode root = getRootNode(); if (!myShowClasses || myContainerNodes.isEmpty()) { List<ParentNode> otherObjects = new ArrayList<ParentNode>(); Enumeration<ParentNode> children = getRootNodeChildren(); ParentNode newRoot = new ParentNode(null, new MemberChooserObjectBase(getAllContainersNodeName()), new Ref<Integer>(0)); while (children.hasMoreElements()) { final ParentNode nextElement = children.nextElement(); if (nextElement instanceof ContainerNode) { final ContainerNode containerNode = (ContainerNode)nextElement; Enumeration<MemberNode> memberNodes = containerNode.children(); List<MemberNode> memberNodesList = new ArrayList<MemberNode>(); while (memberNodes.hasMoreElements()) { memberNodesList.add(memberNodes.nextElement()); } for (MemberNode memberNode : memberNodesList) { newRoot.add(memberNode); } } else { otherObjects.add(nextElement); } } replaceChildren(root, otherObjects); sortNode(newRoot, mySorted); if (newRoot.children().hasMoreElements()) root.add(newRoot); } else { Enumeration<ParentNode> children = getRootNodeChildren(); if (children.hasMoreElements()) { ParentNode allClassesNode = children.nextElement(); Enumeration<MemberNode> memberNodes = allClassesNode.children(); ArrayList<MemberNode> arrayList = new ArrayList<MemberNode>(); while (memberNodes.hasMoreElements()) { arrayList.add(memberNodes.nextElement()); } for (MemberNode memberNode : arrayList) { myNodeToParentMap.get(memberNode).add(memberNode); } } replaceChildren(root, myContainerNodes); } myTreeModel.nodeStructureChanged(root); TreeUtil.expandAll(myTree); restoreSelection(selection); } protected String getAllContainersNodeName() { return IdeBundle.message("node.memberchooser.all.classes"); } private Enumeration<ParentNode> getRootNodeChildren() { return getRootNode().children(); } private DefaultMutableTreeNode getRootNode() { return (DefaultMutableTreeNode)myTreeModel.getRoot(); } private Pair<ElementNode,List<ElementNode>> storeSelection() { List<ElementNode> selectedNodes = new ArrayList<ElementNode>(); TreePath[] paths = myTree.getSelectionPaths(); if (paths != null) { for (TreePath path : paths) { selectedNodes.add((ElementNode)path.getLastPathComponent()); } } TreePath leadSelectionPath = myTree.getLeadSelectionPath(); return Pair.create(leadSelectionPath != null ? (ElementNode)leadSelectionPath.getLastPathComponent() : null, selectedNodes); } private void restoreSelection(Pair<ElementNode,List<ElementNode>> pair) { List<ElementNode> selectedNodes = pair.second; DefaultMutableTreeNode root = getRootNode(); ArrayList<TreePath> toSelect = new ArrayList<TreePath>(); for (ElementNode node : selectedNodes) { if (root.isNodeDescendant(node)) { toSelect.add(new TreePath(node.getPath())); } } if (!toSelect.isEmpty()) { myTree.setSelectionPaths(toSelect.toArray(new TreePath[toSelect.size()])); } ElementNode leadNode = pair.first; if (leadNode != null) { myTree.setLeadSelectionPath(new TreePath(leadNode.getPath())); } } public void dispose() { PropertiesComponent instance = PropertiesComponent.getInstance(); instance.setValue(PROP_SORTED, Boolean.toString(isSorted())); instance.setValue(PROP_SHOWCLASSES, Boolean.toString(myShowClasses)); instance.setValue(PROP_COPYJAVADOC, Boolean.toString(myCopyJavadocCheckbox.isSelected())); getContentPane().removeAll(); mySelectedNodes.clear(); myElements = null; super.dispose(); } public void calcData(final DataKey key, final DataSink sink) { if (key.equals(LangDataKeys.PSI_ELEMENT)) { if (mySelectedElements != null && !mySelectedElements.isEmpty()) { T selectedElement = mySelectedElements.iterator().next(); if (selectedElement instanceof ClassMemberWithElement) { sink.put(LangDataKeys.PSI_ELEMENT, ((ClassMemberWithElement) selectedElement).getElement()); } } } } private class MyTreeSelectionListener implements TreeSelectionListener { public void valueChanged(TreeSelectionEvent e) { TreePath[] paths = e.getPaths(); if (paths == null) return; for (int i = 0; i < paths.length; i++) { Object node = paths[i].getLastPathComponent(); if (node instanceof MemberNode) { final MemberNode memberNode = (MemberNode)node; if (e.isAddedPath(i)) { if (!mySelectedNodes.contains(memberNode)) { mySelectedNodes.add(memberNode); } } else { mySelectedNodes.remove(memberNode); } } } mySelectedElements = new LinkedHashSet<T>(); for (MemberNode selectedNode : mySelectedNodes) { mySelectedElements.add((T)selectedNode.getDelegate()); } } } private abstract static class ElementNode extends DefaultMutableTreeNode { private final int myOrder; private final MemberChooserObject myDelegate; public ElementNode(@Nullable DefaultMutableTreeNode parent, MemberChooserObject delegate, Ref<Integer> order) { myOrder = order.get(); order.set(myOrder + 1); myDelegate = delegate; if (parent != null) { parent.add(this); } } public MemberChooserObject getDelegate() { return myDelegate; } public int getOrder() { return myOrder; } } private static class MemberNode extends ElementNode { public MemberNode(ParentNode parent, ClassMember delegate, Ref<Integer> order) { super(parent, delegate, order); } } private static class ParentNode extends ElementNode { public ParentNode(@Nullable DefaultMutableTreeNode parent, MemberChooserObject delegate, Ref<Integer> order) { super(parent, delegate, order); } } private static class ContainerNode extends ParentNode { public ContainerNode(DefaultMutableTreeNode parent, MemberChooserObject delegate, Ref<Integer> order) { super(parent, delegate, order); } } private class SelectNoneAction extends AbstractAction { public SelectNoneAction() { super(IdeBundle.message("action.select.none")); } public void actionPerformed(ActionEvent e) { myTree.clearSelection(); doOKAction(); } } private class TreeKeyListener extends KeyAdapter { public void keyPressed(KeyEvent e) { TreePath path = myTree.getLeadSelectionPath(); if (path == null) return; final Object lastComponent = path.getLastPathComponent(); if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (lastComponent instanceof ParentNode) return; doOKAction(); e.consume(); } else if (e.getKeyCode() == KeyEvent.VK_INSERT) { if (lastComponent instanceof ElementNode) { final ElementNode node = (ElementNode)lastComponent; if (!mySelectedNodes.contains(node)) { if (node.getNextNode() != null) { myTree.setSelectionPath(new TreePath(node.getNextNode().getPath())); } } else { if (node.getNextNode() != null) { myTree.removeSelectionPath(new TreePath(node.getPath())); myTree.setSelectionPath(new TreePath(node.getNextNode().getPath())); myTree.repaint(); } } e.consume(); } } } } private class SortEmAction extends ToggleAction { public SortEmAction() { super(IdeBundle.message("action.sort.alphabetically"), IdeBundle.message("action.sort.alphabetically"), IconLoader.getIcon("/objectBrowser/sorted.png")); } public boolean isSelected(AnActionEvent event) { return isSorted(); } public void setSelected(AnActionEvent event, boolean flag) { setSorted(flag); } } protected ShowContainersAction getShowContainersAction() { return new ShowContainersAction(IdeBundle.message("action.show.classes"), Icons.CLASS_ICON); } protected class ShowContainersAction extends ToggleAction { public ShowContainersAction(final String text, final Icon icon) { super(text, text, icon); } public boolean isSelected(AnActionEvent event) { return myShowClasses; } public void setSelected(AnActionEvent event, boolean flag) { setShowClasses(flag); } public void update(AnActionEvent e) { super.update(e); Presentation presentation = e.getPresentation(); presentation.setEnabled(myContainerNodes.size() > 1); } } private class ExpandAllAction extends AnAction { public ExpandAllAction() { super(IdeBundle.message("action.expand.all"), IdeBundle.message("action.expand.all"), IconLoader.getIcon("/actions/expandall.png")); } public void actionPerformed(AnActionEvent e) { TreeUtil.expandAll(myTree); } } private class CollapseAllAction extends AnAction { public CollapseAllAction() { super(IdeBundle.message("action.collapse.all"), IdeBundle.message("action.collapse.all"), IconLoader.getIcon("/actions/collapseall.png")); } public void actionPerformed(AnActionEvent e) { TreeUtil.collapseAll(myTree, 1); } } private static class AlphaComparator implements Comparator<ElementNode> { public int compare(ElementNode n1, ElementNode n2) { return n1.getDelegate().getText().compareToIgnoreCase(n2.getDelegate().getText()); } } private static class OrderComparator implements Comparator<ElementNode> { public int compare(ElementNode n1, ElementNode n2) { if (n1.getDelegate() instanceof ClassMemberWithElement && n2.getDelegate() instanceof ClassMemberWithElement) { return ((ClassMemberWithElement)n1.getDelegate()).getElement().getTextOffset() - ((ClassMemberWithElement)n2.getDelegate()).getElement().getTextOffset(); } return n1.getOrder() - n2.getOrder(); } } }
package com.alibaba.dubbo.rpc.protocol.swift; /** * File Created at 2011-12-05 * $Id$ * * Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. * * This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Alibaba.com. */ import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import org.apache.thrift.TApplicationException; import org.apache.thrift.TBase; import org.apache.thrift.TException; import org.apache.thrift.TFieldIdEnum; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TMessage; import org.apache.thrift.protocol.TMessageType; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TIOStreamTransport; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.utils.ClassHelper; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBufferInputStream; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.RpcInvocation; import com.alibaba.dubbo.rpc.RpcResult; /** * Thrift framed protocol codec. * * <pre> * |<- message header ->|<- message body ->| * +----------------+----------------------+------------------+---------------------------+------------------+ * | magic (2 bytes)|message size (4 bytes)|head size(2 bytes)| version (1 byte) | header | message body | * +----------------+----------------------+------------------+---------------------------+------------------+ * |<- message size ->| * </pre> * * <p> * <b>header fields in version 1</b> * <ol> * <li>string - service name</li> * <li>long - dubbo request id</li> * </ol> * </p> * * @author <a href="mailto:gang.lvg@alibaba-inc.com">gang.lvg</a> */ public class ThriftCodec implements Codec2 { private static final AtomicInteger THRIFT_SEQ_ID = new AtomicInteger(0); private static final ConcurrentMap<String, Class<?>> cachedClass = new ConcurrentHashMap<String, Class<?>>(); static final ConcurrentMap<Integer, RequestData> cachedRequest = new ConcurrentHashMap<Integer, RequestData>(); public static final int MESSAGE_LENGTH_INDEX = 2; public static final int MESSAGE_HEADER_LENGTH_INDEX = 6; public static final int MESSAGE_SHORTEST_LENGTH = 10; public static final String NAME = "thrift"; public static final String PARAMETER_CLASS_NAME_GENERATOR = "class.name.generator"; public static final byte VERSION = (byte) 1; public static final short MAGIC = (short) 0xdabc; @Override public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException { if (message instanceof Request) { encodeRequest(channel, buffer, (Request) message); } else if (message instanceof Response) { encodeResponse(channel, buffer, (Response) message); } else { throw new UnsupportedOperationException(new StringBuilder(32).append("Thrift codec only support encode ") .append(Request.class.getName()).append(" and ").append(Response.class.getName()).toString()); } } @Override public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { int available = buffer.readableBytes(); if (available < MESSAGE_SHORTEST_LENGTH) { return DecodeResult.NEED_MORE_INPUT; } else { TIOStreamTransport transport = new TIOStreamTransport(new ChannelBufferInputStream(buffer)); TBinaryProtocol protocol = new TBinaryProtocol(transport); String serviceName = channel.getUrl().getParameter(Constants.INTERFACE_KEY); return decode(serviceName, protocol); } } private Object decode(String serviceName, TProtocol protocol) throws IOException { TMessage message; try { message = protocol.readMessageBegin(); } catch (TException e) { throw new IOException(e.getMessage(), e); } if (message.type == TMessageType.CALL) { RpcInvocation result = new RpcInvocation(); result.setAttachment(Constants.INTERFACE_KEY, serviceName); result.setMethodName(message.name); String argsClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) .getExtension(ThriftClassNameGenerator.NAME).generateArgsClassName(serviceName, message.name); if (StringUtils.isEmpty(argsClassName)) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, "The specified interface name incorrect."); } Class clazz = cachedClass.get(argsClassName); if (clazz == null) { try { clazz = ClassHelper.forNameWithThreadContextClassLoader(argsClassName); cachedClass.putIfAbsent(argsClassName, clazz); } catch (ClassNotFoundException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } TBase args; try { args = (TBase) clazz.newInstance(); } catch (InstantiationException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } try { args.read(protocol); protocol.readMessageEnd(); } catch (TException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } List<Object> parameters = new ArrayList<Object>(); List<Class<?>> parameterTypes = new ArrayList<Class<?>>(); int index = 1; while (true) { TFieldIdEnum fieldIdEnum = args.fieldForId(index++); if (fieldIdEnum == null) { break; } String fieldName = fieldIdEnum.getFieldName(); String getMethodName = ThriftUtils.generateGetMethodName(fieldName); Method getMethod; try { getMethod = clazz.getMethod(getMethodName); } catch (NoSuchMethodException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } parameterTypes.add(getMethod.getReturnType()); try { parameters.add(getMethod.invoke(args)); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (InvocationTargetException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } result.setArguments(parameters.toArray()); result.setParameterTypes(parameterTypes.toArray(new Class[parameterTypes.size()])); Request request = new Request(message.seqid); request.setData(result); cachedRequest.putIfAbsent(message.seqid, RequestData.create(message.seqid, serviceName, message.name)); return request; } else if (message.type == TMessageType.EXCEPTION) { TApplicationException exception; try { exception = TApplicationException.read(protocol); protocol.readMessageEnd(); } catch (TException e) { throw new IOException(e.getMessage(), e); } RpcResult result = new RpcResult(); result.setException(new RpcException(exception.getMessage())); Response response = new Response(); response.setResult(result); response.setId(message.seqid); return response; } else if (message.type == TMessageType.REPLY) { String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) .getExtension(ThriftClassNameGenerator.NAME).generateResultClassName(serviceName, message.name); if (StringUtils.isEmpty(resultClassName)) { throw new IllegalArgumentException(new StringBuilder(32) .append("Could not infer service result class name from service name ").append(serviceName) .append(", the service name you specified may not generated by thrift idl compiler").toString()); } Class<?> clazz = cachedClass.get(resultClassName); if (clazz == null) { try { clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName); cachedClass.putIfAbsent(resultClassName, clazz); } catch (ClassNotFoundException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } TBase<?, ? extends TFieldIdEnum> result; try { result = (TBase<?, ?>) clazz.newInstance(); } catch (InstantiationException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } try { result.read(protocol); protocol.readMessageEnd(); } catch (TException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } Object realResult = null; int index = 0; while (true) { TFieldIdEnum fieldIdEnum = result.fieldForId(index++); if (fieldIdEnum == null) { break; } Field field; try { field = clazz.getDeclaredField(fieldIdEnum.getFieldName()); field.setAccessible(true); } catch (NoSuchFieldException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } try { realResult = field.get(result); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } if (realResult != null) { break; } } Response response = new Response(); response.setId(message.seqid); RpcResult rpcResult = new RpcResult(); if (realResult instanceof Throwable) { rpcResult.setException((Throwable) realResult); } else { rpcResult.setValue(realResult); } response.setResult(rpcResult); return response; } else { // Impossible throw new IOException(); } } private void encodeRequest(Channel channel, ChannelBuffer buffer, Request request) throws IOException { RpcInvocation inv = (RpcInvocation) request.getData(); int seqId = new Long(request.getId()).intValue(); String serviceName = inv.getAttachment(Constants.INTERFACE_KEY); if (StringUtils.isEmpty(serviceName)) { throw new IllegalArgumentException(new StringBuilder(32) .append("Could not find service name in attachment with key ").append(Constants.INTERFACE_KEY) .toString()); } TMessage message = new TMessage(inv.getMethodName(), TMessageType.CALL, seqId); ExtensionLoader<ClassNameGenerator> loader = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class); String name = channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME); ClassNameGenerator generator = loader.getExtension(name); String methodName = inv.getMethodName(); String methodArgs = generator.generateArgsClassName(serviceName, methodName); if (StringUtils.isEmpty(methodArgs)) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, new StringBuilder(32).append( "Could not encode request, the specified interface may be incorrect.").toString()); } Class<?> clazz = cachedClass.get(methodArgs); if (clazz == null) { try { clazz = ClassHelper.forNameWithThreadContextClassLoader(methodArgs); cachedClass.putIfAbsent(methodArgs, clazz); } catch (ClassNotFoundException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } TBase args; try { args = (TBase) clazz.newInstance(); } catch (InstantiationException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } for (int i = 0; i < inv.getArguments().length; i++) { Object obj = inv.getArguments()[i]; if (obj == null) { continue; } TFieldIdEnum field = args.fieldForId(i + 1); String setMethodName = ThriftUtils.generateSetMethodName(field.getFieldName()); Method method; try { method = clazz.getMethod(setMethodName, inv.getParameterTypes()[i]); } catch (NoSuchMethodException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } try { method.invoke(args, obj); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (InvocationTargetException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024); TIOStreamTransport transport = new TIOStreamTransport(bos); TBinaryProtocol protocol = new TBinaryProtocol(transport); try { protocol.writeMessageBegin(message); args.write(protocol); protocol.writeMessageEnd(); protocol.getTransport().flush(); } catch (TException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } buffer.writeBytes(bos.toByteArray()); } private void encodeResponse(Channel channel, ChannelBuffer buffer, Response response) throws IOException { RpcResult result = (RpcResult) response.getResult(); RequestData rd = cachedRequest.get((int) response.getId()); String service = channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME); ClassNameGenerator generator = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class).getExtension( service); String resultClassName = generator.generateResultClassName(rd.serviceName, rd.methodName); if (StringUtils.isEmpty(resultClassName)) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, new StringBuilder(32).append( "Could not encode response, the specified interface may be incorrect.").toString()); } Class clazz = cachedClass.get(resultClassName); if (clazz == null) { try { clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName); cachedClass.putIfAbsent(resultClassName, clazz); } catch (ClassNotFoundException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } TBase resultObj; try { resultObj = (TBase) clazz.newInstance(); } catch (InstantiationException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } TApplicationException applicationException = null; TMessage message; if (result.hasException()) { Throwable throwable = result.getException(); int index = 1; boolean found = false; while (true) { TFieldIdEnum fieldIdEnum = resultObj.fieldForId(index++); if (fieldIdEnum == null) { break; } String fieldName = fieldIdEnum.getFieldName(); String getMethodName = ThriftUtils.generateGetMethodName(fieldName); String setMethodName = ThriftUtils.generateSetMethodName(fieldName); Method getMethod; Method setMethod; try { getMethod = clazz.getMethod(getMethodName); if (getMethod.getReturnType().equals(throwable.getClass())) { found = true; setMethod = clazz.getMethod(setMethodName, throwable.getClass()); setMethod.invoke(resultObj, throwable); } } catch (NoSuchMethodException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (InvocationTargetException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } if (!found) { applicationException = new TApplicationException(throwable.getMessage()); } } else { Object realResult = result.getResult(); // result field id is 0 String fieldName = resultObj.fieldForId(0).getFieldName(); String setMethodName = ThriftUtils.generateSetMethodName(fieldName); String getMethodName = ThriftUtils.generateGetMethodName(fieldName); Method getMethod; Method setMethod; try { getMethod = clazz.getMethod(getMethodName); setMethod = clazz.getMethod(setMethodName, getMethod.getReturnType()); setMethod.invoke(resultObj, realResult); } catch (NoSuchMethodException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (InvocationTargetException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } if (applicationException != null) { message = new TMessage(rd.methodName, TMessageType.EXCEPTION, rd.id); } else { message = new TMessage(rd.methodName, TMessageType.REPLY, rd.id); } RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024); TIOStreamTransport transport = new TIOStreamTransport(bos); TBinaryProtocol protocol = new TBinaryProtocol(transport); try { protocol.writeMessageBegin(message); switch (message.type) { case TMessageType.EXCEPTION: applicationException.write(protocol); break; case TMessageType.REPLY: resultObj.write(protocol); break; } protocol.writeMessageEnd(); protocol.getTransport().flush(); } catch (TException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } buffer.writeBytes(bos.toByteArray()); } // just for test static int getSeqId() { return THRIFT_SEQ_ID.get(); } static class RequestData { int id; String serviceName; String methodName; static RequestData create(int id, String sn, String mn) { RequestData result = new RequestData(); result.id = id; result.serviceName = sn; result.methodName = mn; return result; } } }
/* * Copyright 2014 - 2016 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.real_logic.sbe; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.util.Arrays; import static java.lang.Double.doubleToLongBits; import static java.nio.charset.Charset.forName; /** * Class used to encapsulate values for primitives. Used for nullValue, minValue, maxValue, and constants */ public class PrimitiveValue { public enum Representation { LONG, DOUBLE, BYTE_ARRAY } public static final long MIN_VALUE_CHAR = 0x20; public static final long MAX_VALUE_CHAR = 0x7E; public static final long NULL_VALUE_CHAR = 0; public static final long MIN_VALUE_INT8 = -127; public static final long MAX_VALUE_INT8 = 127; public static final long NULL_VALUE_INT8 = -128; public static final long MIN_VALUE_UINT8 = 0; public static final long MAX_VALUE_UINT8 = 254; public static final long NULL_VALUE_UINT8 = 255; public static final long MIN_VALUE_INT16 = -32767; public static final long MAX_VALUE_INT16 = 32767; public static final long NULL_VALUE_INT16 = -32768; public static final long MIN_VALUE_UINT16 = 0; public static final long MAX_VALUE_UINT16 = 65534; public static final long NULL_VALUE_UINT16 = 65535; public static final long MIN_VALUE_INT32 = -2147483647; public static final long MAX_VALUE_INT32 = 2147483647; public static final long NULL_VALUE_INT32 = -2147483648; public static final long MIN_VALUE_UINT32 = 0; public static final long MAX_VALUE_UINT32 = 4294967293L; // 0xFFFFFFFD public static final long NULL_VALUE_UINT32 = 4294967294L; // 0xFFFFFFFE public static final long MIN_VALUE_INT64 = Long.MIN_VALUE + 1; // (-2 ^ 63) + 1 public static final long MAX_VALUE_INT64 = Long.MAX_VALUE; // (2 ^ 63) - 1 (SBE spec says (-2 ^ 63) - 1) public static final long NULL_VALUE_INT64 = Long.MIN_VALUE; // (-2 ^ 63) public static final long MIN_VALUE_UINT64 = 0; public static final BigInteger BI_MAX_VALUE_UINT64 = new BigInteger("18446744073709551614"); public static final long MAX_VALUE_UINT64 = BI_MAX_VALUE_UINT64.longValue(); // (2 ^ 64)- 2 public static final BigInteger BI_NULL_VALUE_UINT64 = new BigInteger("18446744073709551615"); public static final long NULL_VALUE_UINT64 = BI_NULL_VALUE_UINT64.longValue(); // (2 ^ 64)- 1 public static final float MIN_VALUE_FLOAT = Float.MIN_VALUE; public static final float MAX_VALUE_FLOAT = Float.MAX_VALUE; public static final float NULL_VALUE_FLOAT = Float.NaN; public static final double MIN_VALUE_DOUBLE = Double.MIN_VALUE; public static final double MAX_VALUE_DOUBLE = Double.MAX_VALUE; public static final double NULL_VALUE_DOUBLE = Double.NaN; private final Representation representation; private final long longValue; private final double doubleValue; private final byte[] byteArrayValue; private final String characterEncoding; private final int size; private final byte[] byteArrayValueForLong = new byte[1]; /** * Construct and fill in value as a long. * * @param value in long format * @param size of the type in bytes */ public PrimitiveValue(final long value, final int size) { representation = Representation.LONG; longValue = value; doubleValue = 0.0; byteArrayValue = null; characterEncoding = null; this.size = size; } /** * Construct and fill in value as a double. * * @param value in double format * @param size of the type in bytes */ public PrimitiveValue(final double value, final int size) { representation = Representation.DOUBLE; longValue = 0; doubleValue = value; byteArrayValue = null; characterEncoding = null; this.size = size; } /** * Construct and fill in value as a byte array. * * @param value as a byte array * @param characterEncoding of the characters * @param size of string in characters */ public PrimitiveValue(final byte[] value, final String characterEncoding, final int size) { representation = Representation.BYTE_ARRAY; longValue = 0; doubleValue = 0.0; byteArrayValue = value; this.characterEncoding = characterEncoding; this.size = size; } /** * Parse constant value string and set representation based on type * * @param value expressed as a String * @param primitiveType that this is supposed to be * @return a new {@link PrimitiveValue} for the value. * @throws IllegalArgumentException if parsing malformed type */ public static PrimitiveValue parse(final String value, final PrimitiveType primitiveType) { switch (primitiveType) { case CHAR: if (value.length() > 1) { throw new IllegalArgumentException("Constant char value malformed: " + value); } return new PrimitiveValue((long)value.getBytes(forName("US-ASCII"))[0], 1); case INT8: return new PrimitiveValue(Byte.parseByte(value), 1); case INT16: return new PrimitiveValue(Short.parseShort(value), 2); case INT32: return new PrimitiveValue(Integer.parseInt(value), 4); case INT64: return new PrimitiveValue(Long.parseLong(value), 8); case UINT8: return new PrimitiveValue(Short.parseShort(value), 1); case UINT16: return new PrimitiveValue(Integer.parseInt(value), 2); case UINT32: return new PrimitiveValue(Long.parseLong(value), 4); case UINT64: final BigInteger biValue = new BigInteger(value); if (biValue.compareTo(BI_NULL_VALUE_UINT64) > 0) { throw new IllegalArgumentException("Value greater than UINT64 allows: value=" + value); } return new PrimitiveValue(biValue.longValue(), 8); case FLOAT: return new PrimitiveValue(Float.parseFloat(value), 4); case DOUBLE: return new PrimitiveValue(Double.parseDouble(value), 8); default: throw new IllegalArgumentException("Unknown PrimitiveType: " + primitiveType); } } /** * Parse constant value string and set representation based on type, length, and characterEncoding * * @param value expressed as a String * @param length of the type * @param characterEncoding of the String * @return a new {@link PrimitiveValue} for the value. * @throws IllegalArgumentException if parsing malformed type */ public static PrimitiveValue parse( final String value, final int length, final String characterEncoding) { // TODO: handle incorrect length, characterEncoding, etc. return new PrimitiveValue(value.getBytes(forName(characterEncoding)), characterEncoding, length); } /** * Return long value for this PrimitiveValue * * @return value expressed as a long * @throws IllegalStateException if not a long value representation */ public long longValue() { if (representation != Representation.LONG) { throw new IllegalStateException("PrimitiveValue is not a long representation"); } return longValue; } /** * Return double value for this PrimitiveValue. * * @return value expressed as a double * @throws IllegalStateException if not a double value representation */ public double doubleValue() { if (representation != Representation.DOUBLE) { throw new IllegalStateException("PrimitiveValue is not a double representation"); } return doubleValue; } /** * Return byte array value for this PrimitiveValue. * * @return value expressed as a byte array * @throws IllegalStateException if not a byte array value representation */ public byte[] byteArrayValue() { if (representation != Representation.BYTE_ARRAY) { throw new IllegalStateException("PrimitiveValue is not a byte[] representation"); } return byteArrayValue; } /** * Return byte array value for this PrimitiveValue given a particular type * * @param type of this value * @return value expressed as a byte array * @throws IllegalStateException if not a byte array value representation */ public byte[] byteArrayValue(final PrimitiveType type) { if (representation == Representation.BYTE_ARRAY) { return byteArrayValue; } else if (representation == Representation.LONG && size == 1 && type == PrimitiveType.CHAR) { byteArrayValueForLong[0] = (byte)longValue; return byteArrayValueForLong; } throw new IllegalStateException("PrimitiveValue is not a byte[] representation"); } /** * Return encodedLength for this PrimitiveValue for serialization purposes. * * @return encodedLength for serialization */ public int size() { return size; } /** * The character encoding of the byte array representation. * * @return the character encoding of te byte array representation. */ public String characterEncoding() { return characterEncoding; } /** * Return String representation of this object * * @return String representing object value */ public String toString() { switch (representation) { case LONG: return Long.toString(longValue); case DOUBLE: return Double.toString(doubleValue); case BYTE_ARRAY: try { return characterEncoding == null ? new String(byteArrayValue) : new String(byteArrayValue, characterEncoding); } catch (final UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } default: throw new IllegalStateException("Unsupported Representation: " + representation); } } /** * Determine if two values are equivalent. * * @param value to compare this value with * @return equivalence of values */ public boolean equals(final Object value) { if (null != value && value instanceof PrimitiveValue) { final PrimitiveValue rhs = (PrimitiveValue)value; if (representation == rhs.representation) { switch (representation) { case LONG: return longValue == rhs.longValue; case DOUBLE: return doubleToLongBits(doubleValue) == doubleToLongBits(rhs.doubleValue); case BYTE_ARRAY: return Arrays.equals(byteArrayValue, rhs.byteArrayValue); } } } return false; } /** * Return hashCode for value. This is the underlying representations hashCode for the value * * @return int value of the hashCode */ public int hashCode() { final long bits; switch (representation) { case LONG: bits = longValue; break; case DOUBLE: bits = doubleToLongBits(doubleValue); break; case BYTE_ARRAY: return Arrays.hashCode(byteArrayValue); default: throw new IllegalStateException("Unrecognised representation: " + representation); } return (int)(bits ^ (bits >>> 32)); } }
import java.io.*; import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class AddressBook extends Application { // Specify the size of five string fields in the record final static int NAME_SIZE = 32; final static int STREET_SIZE = 32; final static int CITY_SIZE = 20; final static int STATE_SIZE = 2; final static int ZIP_SIZE = 5; final static int RECORD_SIZE = (NAME_SIZE + STREET_SIZE + CITY_SIZE + STATE_SIZE + ZIP_SIZE); // Access address.dat using RandomAccessFile private RandomAccessFile raf; // Text fields private TextField tfName = new TextField(); private TextField tfStreet = new TextField(); private TextField tfCity = new TextField(); private TextField tfState = new TextField(); private TextField tfZip = new TextField(); // Buttons private Button btAdd = new Button("Add"); private Button btFirst = new Button("First"); private Button btNext = new Button("Next"); private Button btPrevious = new Button("Previous"); private Button btLast = new Button("Last"); public AddressBook() { // Open or create a random access file try { raf = new RandomAccessFile("address.dat", "rw"); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } } @Override public void start(Stage primaryStage) { tfState.setPrefColumnCount(2); tfZip.setPrefColumnCount(4); tfCity.setPrefColumnCount(12); // Pane p1 for holding labels Name, Street, and City GridPane p1 = new GridPane(); p1.setAlignment(Pos.CENTER); p1.setHgap(5); p1.setVgap(5); p1.add(new Label("Name"), 0, 0); p1.add(new Label("Street"), 0, 1); p1.add(new Label("City"), 0, 2); p1.add(tfName, 1, 0); p1.add(tfStreet, 1, 1); HBox p2 = new HBox(5); p2.getChildren().addAll(tfCity, new Label("State"), tfState, new Label("Zip"), tfZip); p1.add(p2, 1, 2); // Add buttons to a pane HBox p3 = new HBox(5); p3.getChildren().addAll(btAdd, btFirst, btNext, btPrevious, btLast); p3.setAlignment(Pos.CENTER); // Add p1 and p3 to a border pane BorderPane borderPane = new BorderPane(); borderPane.setCenter(p1); borderPane.setBottom(p3); // Create a scene and place it in the stage Scene scene = new Scene(borderPane, 400, 120); primaryStage.setTitle("Address Book"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage // Display the first record if exists try { if (raf.length() > 0) { readAddress(0); } } catch (IOException ex) { ex.printStackTrace(); } /** * The Add button writes a new record at the end of the file */ btAdd.setOnAction(e -> { try { // Write a record at the END of the file writeAddress(raf.length()); } catch (Exception ex) { } }); /** * The First button reads the record at the beginning of the file */ btFirst.setOnAction(e -> { try { if (raf.length() > 0) { readAddress(0); } } catch (IOException ex) { } }); /** * The Next button reads the record at the current file pointer. */ btNext.setOnAction(e -> { try { long currentPosition = raf.getFilePointer(); if (currentPosition < raf.length()) { readAddress(currentPosition); } } catch (IOException ex) { } }); /** * The Previous button moves BACK two records from the current file * pointer. (Remember that the current file pointer points to the * location AFTER the record which is displayed.) */ btPrevious.setOnAction(e -> { try { long currentPosition = raf.getFilePointer(); if (currentPosition - 2 * RECORD_SIZE > 0) // (each char is 2 bytes) { readAddress(currentPosition - 2 * 2 * RECORD_SIZE); } else { readAddress(0); } } catch (IOException ex) { } }); /** * The Last button reads the last record in the file, so it must point * the file pointer to the BEGINNING of that record. */ btLast.setOnAction(e -> { try { long lastPosition = raf.length(); if (lastPosition > 0) { readAddress(lastPosition - 2 * RECORD_SIZE); } } catch (IOException ex) { } }); } // (end start method) /** * Write a record at the specified location in the file */ public void writeAddress(long position) { try { raf.seek(position); FixedLengthStringIO.writeFixedLengthString( tfName.getText(), NAME_SIZE, raf); FixedLengthStringIO.writeFixedLengthString( tfStreet.getText(), STREET_SIZE, raf); FixedLengthStringIO.writeFixedLengthString( tfCity.getText(), CITY_SIZE, raf); FixedLengthStringIO.writeFixedLengthString( tfState.getText(), STATE_SIZE, raf); FixedLengthStringIO.writeFixedLengthString( tfZip.getText(), ZIP_SIZE, raf); } catch (IOException ex) { ex.printStackTrace(); } } /** * Read a record at the specified position */ public void readAddress(long position) throws IOException { raf.seek(position); String name = FixedLengthStringIO.readFixedLengthString( NAME_SIZE, raf); String street = FixedLengthStringIO.readFixedLengthString( STREET_SIZE, raf); String city = FixedLengthStringIO.readFixedLengthString( CITY_SIZE, raf); String state = FixedLengthStringIO.readFixedLengthString( STATE_SIZE, raf); String zip = FixedLengthStringIO.readFixedLengthString( ZIP_SIZE, raf); tfName.setText(name); tfStreet.setText(street); tfCity.setText(city); tfState.setText(state); tfZip.setText(zip); } /** * The main method is only needed for the IDE with limited JavaFX support. * Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } // (end class AddressBook) class FixedLengthStringIO { /** * Read fixed number of characters from a DataInput stream. (A DataInput * stream is an object of any class which implements the DataInput * interface.) */ public static String readFixedLengthString(int size, DataInput in) throws IOException { // Declare an array of characters char[] chars = new char[size]; // Read fixed number of characters to the array for (int i = 0; i < size; i++) { chars[i] = in.readChar(); } return new String(chars); } /** * Write fixed number of characters to a DataOutput stream. (A DataOutput * stream is an object of any class which implements the DataOutput * interface.) */ public static void writeFixedLengthString(String s, int size, DataOutput out) throws IOException { char[] chars = new char[size]; // Fill in string with characters s.getChars(0, s.length(), chars, 0); // Fill in blank characters in the rest of the array for (int i = Math.min(s.length(), size); i < chars.length; i++) { chars[i] = ' '; } // Create and write a new string padded with blank characters out.writeChars(new String(chars)); } }
/* * Copyright (C) 2012 DataStax 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.datastax.driver.core; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Keeps metadata on the connected cluster, including known nodes and schema definitions. */ public class Metadata { private static final Logger logger = LoggerFactory.getLogger(Metadata.class); private final Cluster.Manager cluster; volatile String clusterName; private final ConcurrentMap<InetAddress, Host> hosts = new ConcurrentHashMap<InetAddress, Host>(); private final ConcurrentMap<String, KeyspaceMetadata> keyspaces = new ConcurrentHashMap<String, KeyspaceMetadata>(); private volatile TokenMap<? extends Token> tokenMap; Metadata(Cluster.Manager cluster) { this.cluster = cluster; } // Synchronized to make it easy to detect dropped keyspaces synchronized void rebuildSchema(String keyspace, String table, ResultSet ks, ResultSet cfs, ResultSet cols) { Map<String, List<Row>> cfDefs = new HashMap<String, List<Row>>(); Map<String, Map<String, List<Row>>> colsDefs = new HashMap<String, Map<String, List<Row>>>(); // Gather cf defs for (Row row : cfs) { String ksName = row.getString(KeyspaceMetadata.KS_NAME); List<Row> l = cfDefs.get(ksName); if (l == null) { l = new ArrayList<Row>(); cfDefs.put(ksName, l); } l.add(row); } // Gather columns per Cf for (Row row : cols) { String ksName = row.getString(KeyspaceMetadata.KS_NAME); String cfName = row.getString(TableMetadata.CF_NAME); Map<String, List<Row>> colsByCf = colsDefs.get(ksName); if (colsByCf == null) { colsByCf = new HashMap<String, List<Row>>(); colsDefs.put(ksName, colsByCf); } List<Row> l = colsByCf.get(cfName); if (l == null) { l = new ArrayList<Row>(); colsByCf.put(cfName, l); } l.add(row); } if (table == null) { assert ks != null; Set<String> addedKs = new HashSet<String>(); for (Row ksRow : ks) { String ksName = ksRow.getString(KeyspaceMetadata.KS_NAME); KeyspaceMetadata ksm = KeyspaceMetadata.build(ksRow); if (cfDefs.containsKey(ksName)) { buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName)); } addedKs.add(ksName); keyspaces.put(ksName, ksm); } // If keyspace is null, it means we're rebuilding from scratch, so // remove anything that was not just added as it means it's a dropped keyspace if (keyspace == null) { Iterator<String> iter = keyspaces.keySet().iterator(); while (iter.hasNext()) { if (!addedKs.contains(iter.next())) iter.remove(); } } } else { assert keyspace != null; KeyspaceMetadata ksm = keyspaces.get(keyspace); // If we update a keyspace we don't know about, something went // wrong. Log an error an schedule a full schema rebuilt. if (ksm == null) { logger.error(String.format("Asked to rebuild table %s.%s but I don't know keyspace %s", keyspace, table, keyspace)); cluster.submitSchemaRefresh(null, null); return; } if (cfDefs.containsKey(keyspace)) buildTableMetadata(ksm, cfDefs.get(keyspace), colsDefs.get(keyspace)); } } private static void buildTableMetadata(KeyspaceMetadata ksm, List<Row> cfRows, Map<String, List<Row>> colsDefs) { boolean hasColumns = (colsDefs != null) && !colsDefs.isEmpty(); for (Row cfRow : cfRows) { String cfName = cfRow.getString(TableMetadata.CF_NAME); TableMetadata tm = TableMetadata.build(ksm, cfRow, hasColumns); if (!hasColumns || colsDefs.get(cfName) == null) continue; for (Row colRow : colsDefs.get(cfName)) { ColumnMetadata.build(tm, colRow); } } } @SuppressWarnings("unchecked") synchronized void rebuildTokenMap(String partitioner, Map<Host, Collection<String>> allTokens) { this.tokenMap = TokenMap.build(partitioner, allTokens); } Host add(InetAddress address) { Host newHost = new Host(address, cluster.convictionPolicyFactory); Host previous = hosts.putIfAbsent(address, newHost); if (previous == null) { newHost.getMonitor().register(cluster); return newHost; } else { return null; } } boolean remove(Host host) { return hosts.remove(host.getAddress()) != null; } Host getHost(InetAddress address) { return hosts.get(address); } // For internal use only Collection<Host> allHosts() { return hosts.values(); } /** * Returns the set of hosts that are replica for a given partition key. * <p> * Note that this method is a best effort method. Consumers should not rely * too heavily on the result of this method not being stale (or even empty). * * @param partitionKey the partition key for which to find the set of * replica. * @return the (immutable) set of replicas for {@code partitionKey} as know * by the driver. No strong guarantee is provided on the stalelessness of * this information. It is also not guarantee that the returned set won't * be empty (which is then some form of staleness). */ @SuppressWarnings("unchecked") public Set<Host> getReplicas(ByteBuffer partitionKey) { TokenMap current = tokenMap; if (current == null) { return Collections.emptySet(); } else { return current.getReplicas(current.factory.hash(partitionKey)); } } /** * Returns the Cassandra name for the cluster connect to. * * @return the Cassandra name for the cluster connect to. */ public String getClusterName() { return clusterName; } /** * Returns the known hosts of this cluster. * * @return A set will all the know host of this cluster. */ public Set<Host> getAllHosts() { return new HashSet<Host>(allHosts()); } /** * Returns the metadata of a keyspace given its name. * * @param keyspace the name of the keyspace for which metadata should be * returned. * @return the metadata of the requested keyspace or {@code null} if {@code * keyspace} is not a known keyspace. */ public KeyspaceMetadata getKeyspace(String keyspace) { return keyspaces.get(keyspace); } /** * Returns a list of all the defined keyspaces. * * @return a list of all the defined keyspaces. */ public List<KeyspaceMetadata> getKeyspaces() { return new ArrayList<KeyspaceMetadata>(keyspaces.values()); } /** * Returns a {@code String} containing CQL queries representing the schema * of this cluster. * * In other words, this method returns the queries that would allow to * recreate the schema of this cluster. * * Note that the returned String is formatted to be human readable (for * some definition of human readable at least). * * @return the CQL queries representing this cluster schema as a {code * String}. */ public String exportSchemaAsString() { StringBuilder sb = new StringBuilder(); for (KeyspaceMetadata ksm : keyspaces.values()) sb.append(ksm.exportAsString()).append("\n"); return sb.toString(); } static class TokenMap<T extends Token<T>> { private final Token.Factory<T> factory; private final Map<T, Set<Host>> tokenToHosts; private final List<T> ring; private TokenMap(Token.Factory<T> factory, Map<T, Set<Host>> tokenToHosts, List<T> ring) { this.factory = factory; this.tokenToHosts = tokenToHosts; this.ring = ring; } public static <T extends Token<T>> TokenMap<T> build(String partitioner, Map<Host, Collection<String>> allTokens) { @SuppressWarnings("unchecked") Token.Factory<T> factory = (Token.Factory<T>)Token.getFactory(partitioner); if (factory == null) return null; Map<T, Set<Host>> tokenToHosts = new HashMap<T, Set<Host>>(); Set<T> allSorted = new TreeSet<T>(); for (Map.Entry<Host, Collection<String>> entry : allTokens.entrySet()) { Host host = entry.getKey(); for (String tokenStr : entry.getValue()) { try { T t = factory.fromString(tokenStr); allSorted.add(t); Set<Host> hosts = tokenToHosts.get(t); if (hosts == null) { hosts = new HashSet<Host>(); tokenToHosts.put(t, hosts); } hosts.add(host); } catch (IllegalArgumentException e) { // If we failed parsing that token, skip it } } } // Make all the inet set immutable so we can share them publicly safely for (Map.Entry<T, Set<Host>> entry: tokenToHosts.entrySet()) { entry.setValue(Collections.unmodifiableSet(entry.getValue())); } return new TokenMap<T>(factory, tokenToHosts, new ArrayList<T>(allSorted)); } private Set<Host> getReplicas(T token) { // Find the primary replica int i = Collections.binarySearch(ring, token); if (i < 0) { i = (i + 1) * (-1); if (i >= ring.size()) i = 0; } return tokenToHosts.get(ring.get(i)); } } }
package com.example.android.sunshine.app; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.format.Time; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; /** * Created by gcarroll on 12/02/2016. A placeholder fragment containing a simple view. */ public class ForecastFragment extends Fragment { private ArrayAdapter<String> forecastAdapter; public ForecastFragment() {} @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. inflater.inflate(R.menu.forecastfragment, menu); } @Override public boolean onOptionsItemSelected(final MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. final int id = item.getItemId(); // noinspection SimplifiableIfStatement if (id == R.id.action_refresh) { new FetchWeatherTask().execute("Sligo"); return true; } return super.onOptionsItemSelected(item); } @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_main, container, false); final ArrayList forecasts = new ArrayList(); forecasts.add("Today - Sunny - 7/13"); forecasts.add("Tomorrow - Rainy - 7/13"); forecasts.add("Fri - Cloudy - 7/13"); forecasts.add("Sat - Foggy - 7/13"); forecasts.add("Sun - Sunny - 7/13"); forecasts.add("Mon - Cloudy - 7/13"); forecasts.add("Tues - Foggy - 7/13"); forecasts.add("Wed - Rainy - 7/13"); forecasts.add("Thurs - Sunny - 7/13"); forecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, forecasts); final ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast); listView.setAdapter(forecastAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { final String forecast = forecastAdapter.getItem(position); Toast.makeText(getActivity(), forecast, Toast.LENGTH_SHORT).show(); } }); return rootView; } public class FetchWeatherTask extends AsyncTask<String, Void, String[]> { private String LOG_TAG = this.getClass().getSimpleName(); /* * The date/time conversion code is going to be moved outside the asynctask later, so for convenience we're breaking * it out into its own method now. */ private String getReadableDateString(final long time) { // Because the API returns a unix timestamp (measured in seconds), // it must be converted to milliseconds in order to be converted to valid date. final SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd"); return shortenedDateFormat.format(time); } /** * Prepare the weather high/lows for presentation. */ private String formatHighLows(final double high, final double low) { // For presentation, assume the user doesn't care about tenths of a degree. final long roundedHigh = Math.round(high); final long roundedLow = Math.round(low); final String highLowStr = roundedHigh + "/" + roundedLow; return highLowStr; } /** * Take the String representing the complete forecast in JSON Format and pull out the data we need to construct the * Strings needed for the wireframes. Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private String[] getWeatherDataFromJson(final String forecastJsonStr, final int numDays) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DESCRIPTION = "main"; final JSONObject forecastJson = new JSONObject(forecastJsonStr); final JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. final int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); final String[] resultStrs = new String[numDays]; for (int i = 0; i < weatherArray.length(); i++) { // For now, using the format "Day, description, hi/low" final String day; final String description; final String highAndLow; // Get the JSON object representing the day final JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". final long dateTime; // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); day = getReadableDateString(dateTime); // description is in a child array called "weather", which is 1 element long. final JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. final JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); final double high = temperatureObject.getDouble(OWM_MAX); final double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low); resultStrs[i] = day + " - " + description + " - " + highAndLow; } final String LOG_TAG = this.getClass().getSimpleName(); for (final String s : resultStrs) { Log.v(LOG_TAG, "Forecast entry: " + s); } return resultStrs; } @Override protected String[] doInBackground(final String... params) { // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; final String format = "json"; final String units = "metric"; final int numDays = 7; final String appId = "ec4b243078b68181ff987171814d8653"; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "APPID"; final Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).appendQueryParameter(APPID_PARAM, appId) .build(); final URL url = new URL(builtUri.toString()); Log.v(LOG_TAG, "Built URI: " + builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String final InputStream inputStream = urlConnection.getInputStream(); final StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr); } catch (final IOException e) { Log.e("PlaceholderFragment", "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e("PlaceholderFragment", "Error closing stream", e); } } } try { return getWeatherDataFromJson(forecastJsonStr, numDays); } catch (final JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } // This will only happen if there is an error getting or parsing forecast data return null; } @Override protected void onPostExecute(final String[] result) { if (result != null) { forecastAdapter.clear(); for (final String dayForecastStr : result) { forecastAdapter.add(dayForecastStr); } } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/services/campaign_criterion_service.proto package com.google.ads.googleads.v9.services; /** * <pre> * Response message for campaign criterion mutate. * </pre> * * Protobuf type {@code google.ads.googleads.v9.services.MutateCampaignCriteriaResponse} */ public final class MutateCampaignCriteriaResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v9.services.MutateCampaignCriteriaResponse) MutateCampaignCriteriaResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MutateCampaignCriteriaResponse.newBuilder() to construct. private MutateCampaignCriteriaResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MutateCampaignCriteriaResponse() { results_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MutateCampaignCriteriaResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MutateCampaignCriteriaResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 18: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { results_ = new java.util.ArrayList<com.google.ads.googleads.v9.services.MutateCampaignCriterionResult>(); mutable_bitField0_ |= 0x00000001; } results_.add( input.readMessage(com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.parser(), extensionRegistry)); break; } case 26: { com.google.rpc.Status.Builder subBuilder = null; if (partialFailureError_ != null) { subBuilder = partialFailureError_.toBuilder(); } partialFailureError_ = input.readMessage(com.google.rpc.Status.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(partialFailureError_); partialFailureError_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { results_ = java.util.Collections.unmodifiableList(results_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.services.CampaignCriterionServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignCriteriaResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.services.CampaignCriterionServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignCriteriaResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse.class, com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse.Builder.class); } public static final int PARTIAL_FAILURE_ERROR_FIELD_NUMBER = 3; private com.google.rpc.Status partialFailureError_; /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> * @return Whether the partialFailureError field is set. */ @java.lang.Override public boolean hasPartialFailureError() { return partialFailureError_ != null; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> * @return The partialFailureError. */ @java.lang.Override public com.google.rpc.Status getPartialFailureError() { return partialFailureError_ == null ? com.google.rpc.Status.getDefaultInstance() : partialFailureError_; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> */ @java.lang.Override public com.google.rpc.StatusOrBuilder getPartialFailureErrorOrBuilder() { return getPartialFailureError(); } public static final int RESULTS_FIELD_NUMBER = 2; private java.util.List<com.google.ads.googleads.v9.services.MutateCampaignCriterionResult> results_; /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v9.services.MutateCampaignCriterionResult> getResultsList() { return results_; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v9.services.MutateCampaignCriterionResultOrBuilder> getResultsOrBuilderList() { return results_; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ @java.lang.Override public int getResultsCount() { return results_.size(); } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCriterionResult getResults(int index) { return results_.get(index); } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCriterionResultOrBuilder getResultsOrBuilder( int index) { return results_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < results_.size(); i++) { output.writeMessage(2, results_.get(i)); } if (partialFailureError_ != null) { output.writeMessage(3, getPartialFailureError()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < results_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, results_.get(i)); } if (partialFailureError_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, getPartialFailureError()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse)) { return super.equals(obj); } com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse other = (com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse) obj; if (hasPartialFailureError() != other.hasPartialFailureError()) return false; if (hasPartialFailureError()) { if (!getPartialFailureError() .equals(other.getPartialFailureError())) return false; } if (!getResultsList() .equals(other.getResultsList())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasPartialFailureError()) { hash = (37 * hash) + PARTIAL_FAILURE_ERROR_FIELD_NUMBER; hash = (53 * hash) + getPartialFailureError().hashCode(); } if (getResultsCount() > 0) { hash = (37 * hash) + RESULTS_FIELD_NUMBER; hash = (53 * hash) + getResultsList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Response message for campaign criterion mutate. * </pre> * * Protobuf type {@code google.ads.googleads.v9.services.MutateCampaignCriteriaResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v9.services.MutateCampaignCriteriaResponse) com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.services.CampaignCriterionServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignCriteriaResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.services.CampaignCriterionServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignCriteriaResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse.class, com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse.Builder.class); } // Construct using com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getResultsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (partialFailureErrorBuilder_ == null) { partialFailureError_ = null; } else { partialFailureError_ = null; partialFailureErrorBuilder_ = null; } if (resultsBuilder_ == null) { results_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { resultsBuilder_.clear(); } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v9.services.CampaignCriterionServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignCriteriaResponse_descriptor; } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse getDefaultInstanceForType() { return com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse build() { com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse buildPartial() { com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse result = new com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse(this); int from_bitField0_ = bitField0_; if (partialFailureErrorBuilder_ == null) { result.partialFailureError_ = partialFailureError_; } else { result.partialFailureError_ = partialFailureErrorBuilder_.build(); } if (resultsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { results_ = java.util.Collections.unmodifiableList(results_); bitField0_ = (bitField0_ & ~0x00000001); } result.results_ = results_; } else { result.results_ = resultsBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse) { return mergeFrom((com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse other) { if (other == com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse.getDefaultInstance()) return this; if (other.hasPartialFailureError()) { mergePartialFailureError(other.getPartialFailureError()); } if (resultsBuilder_ == null) { if (!other.results_.isEmpty()) { if (results_.isEmpty()) { results_ = other.results_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureResultsIsMutable(); results_.addAll(other.results_); } onChanged(); } } else { if (!other.results_.isEmpty()) { if (resultsBuilder_.isEmpty()) { resultsBuilder_.dispose(); resultsBuilder_ = null; results_ = other.results_; bitField0_ = (bitField0_ & ~0x00000001); resultsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getResultsFieldBuilder() : null; } else { resultsBuilder_.addAllMessages(other.results_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private com.google.rpc.Status partialFailureError_; private com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder> partialFailureErrorBuilder_; /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> * @return Whether the partialFailureError field is set. */ public boolean hasPartialFailureError() { return partialFailureErrorBuilder_ != null || partialFailureError_ != null; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> * @return The partialFailureError. */ public com.google.rpc.Status getPartialFailureError() { if (partialFailureErrorBuilder_ == null) { return partialFailureError_ == null ? com.google.rpc.Status.getDefaultInstance() : partialFailureError_; } else { return partialFailureErrorBuilder_.getMessage(); } } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> */ public Builder setPartialFailureError(com.google.rpc.Status value) { if (partialFailureErrorBuilder_ == null) { if (value == null) { throw new NullPointerException(); } partialFailureError_ = value; onChanged(); } else { partialFailureErrorBuilder_.setMessage(value); } return this; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> */ public Builder setPartialFailureError( com.google.rpc.Status.Builder builderForValue) { if (partialFailureErrorBuilder_ == null) { partialFailureError_ = builderForValue.build(); onChanged(); } else { partialFailureErrorBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> */ public Builder mergePartialFailureError(com.google.rpc.Status value) { if (partialFailureErrorBuilder_ == null) { if (partialFailureError_ != null) { partialFailureError_ = com.google.rpc.Status.newBuilder(partialFailureError_).mergeFrom(value).buildPartial(); } else { partialFailureError_ = value; } onChanged(); } else { partialFailureErrorBuilder_.mergeFrom(value); } return this; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> */ public Builder clearPartialFailureError() { if (partialFailureErrorBuilder_ == null) { partialFailureError_ = null; onChanged(); } else { partialFailureError_ = null; partialFailureErrorBuilder_ = null; } return this; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> */ public com.google.rpc.Status.Builder getPartialFailureErrorBuilder() { onChanged(); return getPartialFailureErrorFieldBuilder().getBuilder(); } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> */ public com.google.rpc.StatusOrBuilder getPartialFailureErrorOrBuilder() { if (partialFailureErrorBuilder_ != null) { return partialFailureErrorBuilder_.getMessageOrBuilder(); } else { return partialFailureError_ == null ? com.google.rpc.Status.getDefaultInstance() : partialFailureError_; } } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder> getPartialFailureErrorFieldBuilder() { if (partialFailureErrorBuilder_ == null) { partialFailureErrorBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder>( getPartialFailureError(), getParentForChildren(), isClean()); partialFailureError_ = null; } return partialFailureErrorBuilder_; } private java.util.List<com.google.ads.googleads.v9.services.MutateCampaignCriterionResult> results_ = java.util.Collections.emptyList(); private void ensureResultsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { results_ = new java.util.ArrayList<com.google.ads.googleads.v9.services.MutateCampaignCriterionResult>(results_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v9.services.MutateCampaignCriterionResult, com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.Builder, com.google.ads.googleads.v9.services.MutateCampaignCriterionResultOrBuilder> resultsBuilder_; /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public java.util.List<com.google.ads.googleads.v9.services.MutateCampaignCriterionResult> getResultsList() { if (resultsBuilder_ == null) { return java.util.Collections.unmodifiableList(results_); } else { return resultsBuilder_.getMessageList(); } } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public int getResultsCount() { if (resultsBuilder_ == null) { return results_.size(); } else { return resultsBuilder_.getCount(); } } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public com.google.ads.googleads.v9.services.MutateCampaignCriterionResult getResults(int index) { if (resultsBuilder_ == null) { return results_.get(index); } else { return resultsBuilder_.getMessage(index); } } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public Builder setResults( int index, com.google.ads.googleads.v9.services.MutateCampaignCriterionResult value) { if (resultsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureResultsIsMutable(); results_.set(index, value); onChanged(); } else { resultsBuilder_.setMessage(index, value); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public Builder setResults( int index, com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.Builder builderForValue) { if (resultsBuilder_ == null) { ensureResultsIsMutable(); results_.set(index, builderForValue.build()); onChanged(); } else { resultsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public Builder addResults(com.google.ads.googleads.v9.services.MutateCampaignCriterionResult value) { if (resultsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureResultsIsMutable(); results_.add(value); onChanged(); } else { resultsBuilder_.addMessage(value); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public Builder addResults( int index, com.google.ads.googleads.v9.services.MutateCampaignCriterionResult value) { if (resultsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureResultsIsMutable(); results_.add(index, value); onChanged(); } else { resultsBuilder_.addMessage(index, value); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public Builder addResults( com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.Builder builderForValue) { if (resultsBuilder_ == null) { ensureResultsIsMutable(); results_.add(builderForValue.build()); onChanged(); } else { resultsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public Builder addResults( int index, com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.Builder builderForValue) { if (resultsBuilder_ == null) { ensureResultsIsMutable(); results_.add(index, builderForValue.build()); onChanged(); } else { resultsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public Builder addAllResults( java.lang.Iterable<? extends com.google.ads.googleads.v9.services.MutateCampaignCriterionResult> values) { if (resultsBuilder_ == null) { ensureResultsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, results_); onChanged(); } else { resultsBuilder_.addAllMessages(values); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public Builder clearResults() { if (resultsBuilder_ == null) { results_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { resultsBuilder_.clear(); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public Builder removeResults(int index) { if (resultsBuilder_ == null) { ensureResultsIsMutable(); results_.remove(index); onChanged(); } else { resultsBuilder_.remove(index); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.Builder getResultsBuilder( int index) { return getResultsFieldBuilder().getBuilder(index); } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public com.google.ads.googleads.v9.services.MutateCampaignCriterionResultOrBuilder getResultsOrBuilder( int index) { if (resultsBuilder_ == null) { return results_.get(index); } else { return resultsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public java.util.List<? extends com.google.ads.googleads.v9.services.MutateCampaignCriterionResultOrBuilder> getResultsOrBuilderList() { if (resultsBuilder_ != null) { return resultsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(results_); } } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.Builder addResultsBuilder() { return getResultsFieldBuilder().addBuilder( com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.getDefaultInstance()); } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.Builder addResultsBuilder( int index) { return getResultsFieldBuilder().addBuilder( index, com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.getDefaultInstance()); } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCriterionResult results = 2;</code> */ public java.util.List<com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.Builder> getResultsBuilderList() { return getResultsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v9.services.MutateCampaignCriterionResult, com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.Builder, com.google.ads.googleads.v9.services.MutateCampaignCriterionResultOrBuilder> getResultsFieldBuilder() { if (resultsBuilder_ == null) { resultsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v9.services.MutateCampaignCriterionResult, com.google.ads.googleads.v9.services.MutateCampaignCriterionResult.Builder, com.google.ads.googleads.v9.services.MutateCampaignCriterionResultOrBuilder>( results_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); results_ = null; } return resultsBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v9.services.MutateCampaignCriteriaResponse) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v9.services.MutateCampaignCriteriaResponse) private static final com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse(); } public static com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MutateCampaignCriteriaResponse> PARSER = new com.google.protobuf.AbstractParser<MutateCampaignCriteriaResponse>() { @java.lang.Override public MutateCampaignCriteriaResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MutateCampaignCriteriaResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser<MutateCampaignCriteriaResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MutateCampaignCriteriaResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCriteriaResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * Copyright 2015 The AppAuth for Android Authors. 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 net.openid.appauth; import static net.openid.appauth.Preconditions.checkNotNull; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import net.openid.appauth.JsonUtil.BooleanField; import net.openid.appauth.JsonUtil.Field; import net.openid.appauth.JsonUtil.StringField; import net.openid.appauth.JsonUtil.StringListField; import net.openid.appauth.JsonUtil.UriField; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * An OpenID Connect 1.0 Discovery Document. * * @see <a href=https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata> * "OpenID Provider Metadata", OpenID Connect Discovery 1.0, Section 3</a> */ public class AuthorizationServiceDiscovery { @VisibleForTesting static final StringField ISSUER = str("issuer"); @VisibleForTesting static final UriField AUTHORIZATION_ENDPOINT = uri("authorization_endpoint"); @VisibleForTesting static final UriField TOKEN_ENDPOINT = uri("token_endpoint"); @VisibleForTesting static final UriField USERINFO_ENDPOINT = uri("userinfo_endpoint"); @VisibleForTesting static final UriField JWKS_URI = uri("jwks_uri"); @VisibleForTesting static final UriField REGISTRATION_ENDPOINT = uri("registration_endpoint"); @VisibleForTesting static final StringListField SCOPES_SUPPORTED = strList("scopes_supported"); @VisibleForTesting static final StringListField RESPONSE_TYPES_SUPPORTED = strList("response_types_supported"); @VisibleForTesting static final StringListField RESPONSE_MODES_SUPPORTED = strList("response_modes_supported"); @VisibleForTesting static final StringListField GRANT_TYPES_SUPPORTED = strList("grant_types_supported", Arrays.asList("authorization_code", "implicit")); @VisibleForTesting static final StringListField ACR_VALUES_SUPPORTED = strList("acr_values_supported"); @VisibleForTesting static final StringListField SUBJECT_TYPES_SUPPORTED = strList("subject_types_supported"); @VisibleForTesting static final StringListField ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED = strList("id_token_signing_alg_values_supported"); @VisibleForTesting static final StringListField ID_TOKEN_ENCRYPTION_ALG_VALUES_SUPPORTED = strList("id_token_encryption_enc_values_supported"); @VisibleForTesting static final StringListField ID_TOKEN_ENCRYPTION_ENC_VALUES_SUPPORTED = strList("id_token_encryption_enc_values_supported"); @VisibleForTesting static final StringListField USERINFO_SIGNING_ALG_VALUES_SUPPORTED = strList("userinfo_signing_alg_values_supported"); @VisibleForTesting static final StringListField USERINFO_ENCRYPTION_ALG_VALUES_SUPPORTED = strList("userinfo_encryption_alg_values_supported"); @VisibleForTesting static final StringListField USERINFO_ENCRYPTION_ENC_VALUES_SUPPORTED = strList("userinfo_encryption_enc_values_supported"); @VisibleForTesting static final StringListField REQUEST_OBJECT_SIGNING_ALG_VALUES_SUPPORTED = strList("request_object_signing_alg_values_supported"); @VisibleForTesting static final StringListField REQUEST_OBJECT_ENCRYPTION_ALG_VALUES_SUPPORTED = strList("request_object_encryption_alg_values_supported"); @VisibleForTesting static final StringListField REQUEST_OBJECT_ENCRYPTION_ENC_VALUES_SUPPORTED = strList("request_object_encryption_enc_values_supported"); @VisibleForTesting static final StringListField TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED = strList("token_endpoint_auth_methods_supported", Collections.singletonList("client_secret_basic")); @VisibleForTesting static final StringListField TOKEN_ENDPOINT_AUTH_SIGNING_ALG_VALUES_SUPPORTED = strList("token_endpoint_auth_signing_alg_values_supported"); @VisibleForTesting static final StringListField DISPLAY_VALUES_SUPPORTED = strList("display_values_supported"); @VisibleForTesting static final StringListField CLAIM_TYPES_SUPPORTED = strList("claim_types_supported", Collections.singletonList("normal")); @VisibleForTesting static final StringListField CLAIMS_SUPPORTED = strList("claims_supported"); @VisibleForTesting static final UriField SERVICE_DOCUMENTATION = uri("service_documentation"); @VisibleForTesting static final StringListField CLAIMS_LOCALES_SUPPORTED = strList("claims_locales_supported"); @VisibleForTesting static final StringListField UI_LOCALES_SUPPORTED = strList("ui_locales_supported"); @VisibleForTesting static final BooleanField CLAIMS_PARAMETER_SUPPORTED = bool("claims_parameter_supported", false); @VisibleForTesting static final BooleanField REQUEST_PARAMETER_SUPPORTED = bool("request_parameter_supported", false); @VisibleForTesting static final BooleanField REQUEST_URI_PARAMETER_SUPPORTED = bool("request_uri_parameter_supported", true); @VisibleForTesting static final BooleanField REQUIRE_REQUEST_URI_REGISTRATION = bool("require_request_uri_registration", false); @VisibleForTesting static final UriField OP_POLICY_URI = uri("op_policy_uri"); @VisibleForTesting static final UriField OP_TOS_URI = uri("op_tos_uri"); /** * The fields which are marked as mandatory in the OpenID discovery spec. */ private static final List<String> MANDATORY_METADATA = Arrays.asList( ISSUER.key, AUTHORIZATION_ENDPOINT.key, JWKS_URI.key, RESPONSE_TYPES_SUPPORTED.key, SUBJECT_TYPES_SUPPORTED.key, ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED.key); /** * The JSON representation of the discovery document. */ @NonNull public final JSONObject docJson; /** * Extracts a discovery document from its standard JSON representation. * @throws JSONException if the provided JSON does not match the expected structure. * @throws MissingArgumentException if a mandatory property is missing from the discovery * document. */ public AuthorizationServiceDiscovery(@NonNull JSONObject discoveryDoc) throws JSONException, MissingArgumentException { this.docJson = checkNotNull(discoveryDoc); for (String mandatory : MANDATORY_METADATA) { if (!this.docJson.has(mandatory) || this.docJson.get(mandatory) == null) { throw new MissingArgumentException(mandatory); } } } /** * Thrown when a mandatory property is missing from the discovery document. */ public static class MissingArgumentException extends Exception { private String mMissingField; /** * Indicates that the specified mandatory field is missing from the discovery document. */ public MissingArgumentException(String field) { super("Missing mandatory configuration field: " + field); mMissingField = field; } public String getMissingField() { return mMissingField; } } /** * Retrieves a metadata value from the discovery document. This need only be used * for the retrieval of a non-standard metadata value. Convenience methods are defined on this * class for all standard metadata values. */ private <T> T get(Field<T> field) { return JsonUtil.get(docJson, field); } /** * Retrieves a metadata value from the discovery document. This need only be used * for the retrieval of a non-standard metadata value. Convenience methods are defined on this * class for all standard metadata values. */ private <T> List<T> get(JsonUtil.ListField<T> field) { return JsonUtil.get(docJson, field); } /** * The asserted issuer identifier. * * @see <a href="https://openid.net/specs/openid-connect-discovery-1_0.html#IssuerDiscovery"> * "OpenID Connect Dynamic Client Registration 1.0"</a> */ @NonNull public String getIssuer() { return get(ISSUER); } /** * The OAuth 2 authorization endpoint URI. * * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint"> * "OpenID Connect Dynamic Client Registration 1.0"</a> */ @NonNull public Uri getAuthorizationEndpoint() { return get(AUTHORIZATION_ENDPOINT); } /** * The OAuth 2 token endpoint URI. Not specified if only the implicit flow is used. * * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint"> * "OpenID Connect Dynamic Client Registration 1.0"</a> */ @Nullable public Uri getTokenEndpoint() { return get(TOKEN_ENDPOINT); } /** * The OpenID Connect UserInfo endpoint URI. * * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html#UserInfo"> * "OpenID Connect Dynamic Client Registration 1.0"</a> */ @Nullable public Uri getUserinfoEndpoint() { return get(USERINFO_ENDPOINT); } /** * The JSON web key set document URI. * * @see <a href="http://tools.ietf.org/html/rfc7517">"JSON Web Key (JWK)"</a> */ @NonNull public Uri getJwksUri() { return get(JWKS_URI); } /** * The dynamic client registration endpoint URI. * * @see <a href="http://openid.net/specs/openid-connect-registration-1_0.html">"OpenID Connect * Dynamic Client Registration 1.0"</a> */ @Nullable public Uri getRegistrationEndpoint() { return get(REGISTRATION_ENDPOINT); } /** * The OAuth 2 scope values supported. * * @see <a href="http://tools.ietf.org/html/rfc6749#section-3.3">"The OAuth 2.0 Authorization * Framework"</a> */ public List<String> getScopesSupported() { return get(SCOPES_SUPPORTED); } /** * The OAuth 2 {@code response_type} values supported. */ @NonNull public List<String> getResponseTypesSupported() { return get(RESPONSE_TYPES_SUPPORTED); } /** * The OAuth 2 {@code response_mode} values supported. * * @see <a href="http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html"> * "OAuth 2.0 Multiple Response Type Encoding Practices"</a> */ @Nullable public List<String> getResponseModesSupported() { return get(RESPONSE_MODES_SUPPORTED); } /** * The OAuth 2 {@code grant_type} values supported. Defaults to * {@code authorization_code} and {@code implicit} if not specified in the discovery document, * as suggested by the discovery specification. */ @NonNull public List<String> getGrantTypesSupported() { return get(GRANT_TYPES_SUPPORTED); } /** * The authentication context class references supported. */ public List<String> getAcrValuesSupported() { return get(ACR_VALUES_SUPPORTED); } /** * The subject identifier types supported. */ @NonNull public List<String> getSubjectTypesSupported() { return get(SUBJECT_TYPES_SUPPORTED); } /** * The JWS signing algorithms (alg values) supported for encoding ID token claims. * * @see <a href="https://tools.ietf.org/html/rfc7519">"JSON Web Token (JWT)"</a> */ @NonNull public List<String> getIdTokenSigningAlgorithmValuesSupported() { return get(ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED); } /** * The JWE encryption algorithms (alg values) supported for encoding ID token claims. * * @see <a href="https://tools.ietf.org/html/rfc7519">"JSON Web Token (JWT)"</a> */ @Nullable public List<String> getIdTokenEncryptionAlgorithmValuesSupported() { return get(ID_TOKEN_ENCRYPTION_ALG_VALUES_SUPPORTED); } /** * The JWE encryption encodings (enc values) supported for encoding ID token claims. * * @see <a href="https://tools.ietf.org/html/rfc7519">"JSON Web Token (JWT)"</a> */ @Nullable public List<String> getIdTokenEncryptionEncodingValuesSupported() { return get(ID_TOKEN_ENCRYPTION_ENC_VALUES_SUPPORTED); } /** * The JWS signing algorithms (alg values) supported by the UserInfo Endpoint * for encoding ID token claims. * * @see <a href="https://tools.ietf.org/html/rfc7515">"JSON Web Signature (JWS)"</a> * @see <a href="https://tools.ietf.org/html/rfc7518">"JSON Web Algorithms (JWA)"</a> * @see <a href="https://tools.ietf.org/html/rfc7519">"JSON Web Token (JWT)"</a> */ @Nullable public List<String> getUserinfoSigningAlgorithmValuesSupported() { return get(USERINFO_SIGNING_ALG_VALUES_SUPPORTED); } /** * The JWE encryption algorithms (alg values) supported by the UserInfo Endpoint * for encoding ID token claims. * * @see <a href="https://tools.ietf.org/html/rfc7515">"JSON Web Signature (JWS)"</a> * @see <a href="https://tools.ietf.org/html/rfc7518">"JSON Web Algorithms (JWA)"</a> * @see <a href="https://tools.ietf.org/html/rfc7519">"JSON Web Token (JWT)"</a> */ @Nullable public List<String> getUserinfoEncryptionAlgorithmValuesSupported() { return get(USERINFO_ENCRYPTION_ALG_VALUES_SUPPORTED); } /** * The JWE encryption encodings (enc values) supported by the UserInfo Endpoint * for encoding ID token claims. * * @see <a href="https://tools.ietf.org/html/rfc7519">"JSON Web Token (JWT)"</a> */ @Nullable public List<String> getUserinfoEncryptionEncodingValuesSupported() { return get(USERINFO_ENCRYPTION_ENC_VALUES_SUPPORTED); } /** * The JWS signing algorithms (alg values) supported for Request Objects. * * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html#RequestObject"> * "OpenID Connect Core 1.0", Section 6.1</a> */ public List<String> getRequestObjectSigningAlgorithmValuesSupported() { return get(REQUEST_OBJECT_SIGNING_ALG_VALUES_SUPPORTED); } /** * The JWE encryption algorithms (alg values) supported for Request Objects. */ @Nullable public List<String> getRequestObjectEncryptionAlgorithmValuesSupported() { return get(REQUEST_OBJECT_ENCRYPTION_ALG_VALUES_SUPPORTED); } /** * The JWE encryption encodings (enc values) supported for Request Objects. */ @Nullable public List<String> getRequestObjectEncryptionEncodingValuesSupported() { return get(REQUEST_OBJECT_ENCRYPTION_ENC_VALUES_SUPPORTED); } /** * The client authentication methods supported by the token endpoint. Defaults to * {@code client_secret_basic} if the discovery document does not specify a value, as suggested * by the discovery specification. * * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html"> * "OpenID Connect Core 1.0"</a> * @see <a href="http://tools.ietf.org/html/rfc6749#section-2.3.1"> * "The OAuth 2.0 Authorization Framework"</a> */ @NonNull public List<String> getTokenEndpointAuthMethodsSupported() { return get(TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED); } /** * The JWS signing algorithms (alg values) supported by the token endpoint for the signature on * the JWT used to authenticate the client for the {@code private_key_jwt} and * {@code client_secret_jwt} authentication methods. * * @see <a href="https://tools.ietf.org/html/rfc7519">"JSON Web Token (JWT)"</a> */ @Nullable public List<String> getTokenEndpointAuthSigningAlgorithmValuesSupported() { return get(TOKEN_ENDPOINT_AUTH_SIGNING_ALG_VALUES_SUPPORTED); } /** * The {@code display} parameter values supported. * * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html#AuthRequest"> * "OpenID Connect Core 1.0"</a> */ @Nullable public List<String> getDisplayValuesSupported() { return get(DISPLAY_VALUES_SUPPORTED); } /** * The claim types supported. Defaults to {@code normal} if not specified by the discovery * document JSON, as suggested by the discovery specification. * * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimTypes"> * "OpenID Connect Core 1.0", Section 5.6</a> */ public List<String> getClaimTypesSupported() { return get(CLAIM_TYPES_SUPPORTED); } /** * The claim names of the claims that the provider <em>may</em> be able to supply values for. */ @Nullable public List<String> getClaimsSupported() { return get(CLAIMS_SUPPORTED); } /** * A page containing human-readable information that developers might want or need to know when * using this provider. */ @Nullable public Uri getServiceDocumentation() { return get(SERVICE_DOCUMENTATION); } /** * Languages and scripts supported for values in claims being returned. * Represented as a list of BCP47 language tag values. * * @see <a href="http://tools.ietf.org/html/rfc5646">"Tags for Identifying Languages"</a> */ @Nullable public List<String> getClaimsLocalesSupported() { return get(CLAIMS_LOCALES_SUPPORTED); } /** * Languages and scripts supported for the user interface. * Represented as a list of BCP47 language tag values. * * @see <a href="http://tools.ietf.org/html/rfc5646">"Tags for Identifying Languages"</a> */ @Nullable public List<String> getUiLocalesSupported() { return get(UI_LOCALES_SUPPORTED); } /** * Specifies whether the {@code claims} parameter is supported for authorization requests. * * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter"> * "OpenID Connect Core 1.0", Section 5.5</a> */ public boolean isClaimsParameterSupported() { return get(CLAIMS_PARAMETER_SUPPORTED); } /** * Specifies whether the {@code request} parameter is supported for authorization requests. * * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html#RequestObject"> * "OpenID Connect Core 1.0", Section 6.1</a> */ public boolean isRequestParameterSupported() { return get(REQUEST_PARAMETER_SUPPORTED); } /** * Specifies whether the {@code request_uri} is supported for authorization requests. * * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html#RequestUriParameter"> * "OpenID Connect Core 1.0", Section 6.2</a> */ public boolean isRequestUriParameterSupported() { return get(REQUEST_URI_PARAMETER_SUPPORTED); } /** * Specifies whether {@code request_uri} values are required to be pre-registered before use. * * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html#RequestUriParameter"> * "OpenID Connect Core 1.0", Section 6.2</a> */ public boolean requireRequestUriRegistration() { return get(REQUIRE_REQUEST_URI_REGISTRATION); } /** * A page articulating the policy regarding the use of data provided by the provider. */ @Nullable public Uri getOpPolicyUri() { return get(OP_POLICY_URI); } /** * A page articulating the terms of service for the provider. */ @Nullable public Uri getOpTosUri() { return get(OP_TOS_URI); } /** * Shorthand method for creating a string metadata extractor. */ private static StringField str(String key) { return new StringField(key); } /** * Shorthand method for creating a URI metadata extractor. */ private static UriField uri(String key) { return new UriField(key); } /** * Shorthand method for creating a string list metadata extractor. */ private static StringListField strList(String key) { return new StringListField(key); } /** * Shorthand method for creating a string list metadata extractor, with a default value. */ private static StringListField strList(String key, List<String> defaults) { return new StringListField(key, defaults); } /** * Shorthand method for creating a boolean metadata extractor. */ private static BooleanField bool(String key, boolean defaultValue) { return new BooleanField(key, defaultValue); } }
package noack; //Copyright (C) 2008 Andreas Noack // //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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.util.Map; import java.util.Set; import java.util.HashSet; import noack.Node; /** * Dialog with a simple graph visualization, displaying graph nodes * as circles of specified sizes and colors at specified positions. * * @author Andreas Noack * @version 21.01.2008 */ public class GraphFrame extends JFrame { /** * Constructs the dialog. * * @param nodeToPosition map from each graph node to its position. * Each position array must have at least two elements, * one for the horizontal position and one for the vertical position. * @param nodeToCluster map from each graph node to its cluster, * which is used as color (hue) of its representing circle. * The diameter of the circle is the square root of the node weight, * thus the circle areas are proportional to the node weights. */ public GraphFrame(Map<Node,double[]> nodeToPosition, Map<Node,Integer> nodeToCluster) { setTitle("LinLogLayout"); setSize(getToolkit().getScreenSize().width/2, getToolkit().getScreenSize().height/2); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().setLayout(new BorderLayout()); final GraphCanvas canvas = new GraphCanvas(nodeToPosition, nodeToCluster); getContentPane().add(BorderLayout.CENTER, canvas); JPanel southPanel = new JPanel(new BorderLayout()); final JLabel commentLabel = new JLabel( "Click right to search. " + "Move the mouse cursor over a node to display its name."); southPanel.add(BorderLayout.CENTER, commentLabel); final JCheckBox labelBox = new JCheckBox("Show all names.", false); labelBox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { canvas.setLabelEnabled(labelBox.isSelected()); } }); southPanel.add(BorderLayout.EAST, labelBox); getContentPane().add(BorderLayout.SOUTH, southPanel); } } /** * Canvas for a simple graph visualization. * * @author Andreas Noack */ class GraphCanvas extends JComponent { /** Map from each node to its position. */ private final Map<Node,double[]> nodeToPosition; /** Minimum and maximum positions of the nodes. */ private double minX, maxX, minY, maxY; /** Map from each node to its cluster. */ private final Map<Node,Integer> nodeToCluster; /** Maximum cluster of the nodes. */ private int maxCluster; /** Nodes whose names are displayed. */ private Set<Node> labelledNodes = new HashSet<Node>(); /** If <code>true</code>, all node names are displayed. */ private boolean labelsEnabled = false; /** Node name searched by the user. */ private String searchedName = null; /** * Constructs the canvas. */ public GraphCanvas(Map<Node,double[]> nodeToPosition, Map<Node,Integer> nodeToCluster) { this.nodeToPosition = nodeToPosition; this.nodeToCluster = nodeToCluster; // determine minimum and maximum positions of the nodes minX = Float.MAX_VALUE; maxX = -Float.MAX_VALUE; minY = Float.MAX_VALUE; maxY = -Float.MAX_VALUE; for (Node node : nodeToPosition.keySet()) { double[] position = nodeToPosition.get(node); double diameter = Math.sqrt(node.weight); minX = Math.min(minX, position[0] - diameter/2); maxX = Math.max(maxX, position[0] + diameter/2); minY = Math.min(minY, position[1] - diameter/2); maxY = Math.max(maxY, position[1] + diameter/2); } // determine maximum cluster of the nodes maxCluster = 0; for (int cluster : nodeToCluster.values()) { maxCluster = Math.max(cluster, maxCluster); } // show name of nodes when the mouse cursor is over them addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent event) { labelledNodes = nodesAt(event.getX(), event.getY()); repaint(); } }); // right click opens popup menu addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { showPopup(e.getX(), e.getY()); } } }); } /** * Shows a popup menu at the specified position. */ private void showPopup(int posX, int posY) { JPopupMenu menu = new JPopupMenu(); JMenuItem item = new JMenuItem("Search..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { searchedName = JOptionPane.showInputDialog("Search for node:"); repaint(); } }); menu.add(item); menu.show(this, posX, posY); } /** * Returns the nodes at the specified position. */ private Set<Node> nodesAt(int x, int y) { double scale = Math.min(getWidth() / (maxX-minX), getHeight() / (maxY-minY)); Set<Node> result = new HashSet<Node>(); for (Node node : nodeToPosition.keySet()) { int positionX = (int)Math.round((nodeToPosition.get(node)[0] - minX) * scale); int positionY = (int)Math.round((nodeToPosition.get(node)[1] - minY) * scale); int diameter = (int)Math.round(Math.sqrt(node.weight) * scale); if ( x >= positionX-diameter/2 && x <= positionX+diameter/2 && y >= positionY-diameter/2 && y <= positionY+diameter/2) { result.add(node); } } return result; } /** * Show names of all or only mouse-pointed nodes. */ public void setLabelEnabled(boolean labelsEnabled) { this.labelsEnabled = labelsEnabled; repaint(); } /** * Invoked by Swing to draw components. */ public void paint(Graphics g) { double scale = Math.min(getWidth() / (maxX-minX), getHeight() / (maxY-minY)); // draw nodes as circles ((Graphics2D)g).setComposite( AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f) ); for (Node node : nodeToPosition.keySet()) { float hue = nodeToCluster.get(node) / (float)(maxCluster+1); g.setColor(Color.getHSBColor(hue, 1.0f, 1.0f)); int positionX = (int)Math.round((nodeToPosition.get(node)[0] - minX) * scale); int positionY = (int)Math.round((nodeToPosition.get(node)[1] - minY) * scale); int diameter = (int)Math.round(Math.sqrt(node.weight) * scale); g.fillOval(positionX-diameter/2, positionY-diameter/2, diameter, diameter); } final int FONT_SIZE = 10; g.setFont(g.getFont().deriveFont(FONT_SIZE)); ((Graphics2D)g).setComposite( AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f) ); for (Node node : nodeToPosition.keySet()) { if (labelledNodes.contains(node)) continue; if (!node.name.equalsIgnoreCase(searchedName) && !labelsEnabled) continue; g.setColor(node.name.equalsIgnoreCase(searchedName) ? Color.RED : Color.BLACK); int positionX = (int)Math.round((nodeToPosition.get(node)[0] - minX) * scale); int positionY = (int)Math.round((nodeToPosition.get(node)[1] - minY) * scale); g.drawString(node.name, Math.min(positionX, getWidth() - g.getFontMetrics().stringWidth(node.name)), Math.max(positionY, FONT_SIZE)); } if (!labelledNodes.isEmpty()) { Node firstNode = labelledNodes.iterator().next(); int positionX = (int)Math.round((nodeToPosition.get(firstNode)[0] - minX) * scale); int positionY = (int)Math.round((nodeToPosition.get(firstNode)[1] - minY) * scale); positionY = Math.max(positionY, FONT_SIZE); for (Node node : labelledNodes) { g.setColor(node.name.equalsIgnoreCase(searchedName) ? Color.RED : Color.BLACK); g.drawString(node.name, Math.min(positionX, getWidth() - g.getFontMetrics().stringWidth(node.name)), positionY); positionY += FONT_SIZE; } } } }
/* * Copyright 2015 Kirby Banman, * Stuart Bildfell, * Elliot Colp, * Christian Ellinger, * Braedy Kuzma, * Ryan Thornhill * * 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 cmput301w15t07.TravelTracker.activity; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.UUID; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.SparseArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import cmput301w15t07.TravelTracker.R; import cmput301w15t07.TravelTracker.model.Claim; import cmput301w15t07.TravelTracker.model.DataSource; import cmput301w15t07.TravelTracker.model.Destination; import cmput301w15t07.TravelTracker.model.Geolocation; import cmput301w15t07.TravelTracker.model.Item; import cmput301w15t07.TravelTracker.model.Status; import cmput301w15t07.TravelTracker.model.Tag; import cmput301w15t07.TravelTracker.model.User; import cmput301w15t07.TravelTracker.model.UserData; import cmput301w15t07.TravelTracker.model.UserRole; import cmput301w15t07.TravelTracker.serverinterface.MultiCallback; import cmput301w15t07.TravelTracker.serverinterface.ResultCallback; import cmput301w15t07.TravelTracker.util.ApproverCommentAdapter; import cmput301w15t07.TravelTracker.util.ClaimUtilities; import cmput301w15t07.TravelTracker.util.DatePickerFragment; import cmput301w15t07.TravelTracker.util.DestinationAdapter; import cmput301w15t07.TravelTracker.util.DestinationEditorFragment; import cmput301w15t07.TravelTracker.util.Observer; import cmput301w15t07.TravelTracker.util.SelectTagFragment; /** * Activity for managing an individual Claim. Possible as a Claimant or * an Approver. * * @author kdbanman, * therabidsquirel, * colp, * skwidz * */ public class ClaimInfoActivity extends TravelTrackerActivity implements Observer<DataSource> { /** ID used to retrieve items from MutliCallback. */ public static final int MULTI_ITEMS_ID = 0; /** ID used to retrieve claimant from MutliCallback. */ public static final int MULTI_CLAIMANT_ID = 1; /** ID used to retrieve last approver from MutliCallback. */ public static final int MULTI_APPROVER_ID = 2; /** ID used to retrieve tags from MultiCallback. */ public static final int MULTI_TAGS_ID = 3; /** Data about the logged-in user. */ private UserData userData; /** UUID of the claim. */ private UUID claimID; /** The current claim. */ Claim claim = null; /** The list of all the tags this user has. */ ArrayList<Tag> userTags; /** The list of all the tags on this claim. */ ArrayList<Tag> claimTags; /** The list of all the tag UUIDs on this claim. */ ArrayList<UUID> claimTagIDs; /** The menu for the activity. */ private Menu menu = null; /** The custom adapter for claim destinations. */ DestinationAdapter destinationAdapter; /** The custom adapter for claim comments. */ ApproverCommentAdapter commentsListAdapter; /** The last alert dialog. */ AlertDialog lastAlertDialog = null; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.claim_info_menu, menu); this.menu = menu; if (claim != null) { hideMenuItems(menu, claim); } return true; } private void hideMenuItems(Menu menu, Claim claim) { // Menu items MenuItem addDestinationMenuItem = menu.findItem(R.id.claim_info_add_destination); MenuItem addItemMenuItem = menu.findItem(R.id.claim_info_add_item); MenuItem deleteClaimMenuItem = menu.findItem(R.id.claim_info_delete_claim); if (!isEditable(claim.getStatus(), userData.getRole())) { // Menu items that disappear when not editable addDestinationMenuItem.setEnabled(false).setVisible(false); addItemMenuItem.setEnabled(false).setVisible(false); } if (userData.getRole().equals(UserRole.APPROVER)) { deleteClaimMenuItem.setEnabled(false).setVisible(false); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.claim_info_add_destination: addDestination(); return true; case R.id.claim_info_add_item: addItem(claim); return true; case R.id.claim_info_delete_claim: promptDeleteClaim(); return true; case R.id.claim_info_sign_out: signOut(); return true; case android.R.id.home: onBackPressed(); return true; default: return false; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); // Retrieve user info from bundle Bundle bundle = getIntent().getExtras(); userData = (UserData) bundle.getSerializable(USER_DATA); appendNameToTitle(userData.getName()); // Get claim info claimID = (UUID) bundle.getSerializable(CLAIM_UUID); datasource.addObserver(this); } @Override protected void onResume() { super.onResume(); // Show loading circle setContentView(R.layout.loading_indeterminate); loading = true; updateActivity(); } @Override protected void onDestroy() { super.onDestroy(); datasource.removeObserver(this); } /** * Update the activity when the dataset changes. * Called in onResume() and update(DataSource observable). */ @Override public void updateActivity(){ datasource.getClaim(claimID, new ClaimCallback()); } /** * Get the last created AlertDialog. * @return The last dialog, or null if there isn't one. */ public AlertDialog getLastAlertDialog() { return lastAlertDialog; } /** * attach listeners to buttons/textviews/etc. * hide buttons/views according to user role * @param items Collection of a claims expense items * @param claimant User that created the claim * @param approver user that approved the claim (if exsists) */ public void onGetAllData(final Collection<Item> items, User claimant, User approver, Collection<Tag> tags) { if (!loading) { onLoaded(); return; } loading = false; setContentView(R.layout.claim_info_activity); populateClaimInfo(claim, items, claimant, approver, tags); if (menu != null) { hideMenuItems(menu, claim); } // Claim attributes LinearLayout statusLinearLayout = (LinearLayout) findViewById(R.id.claimInfoStatusLinearLayout); // Dates Button startDateButton = (Button) findViewById(R.id.claimInfoStartDateButton); Button endDateButton = (Button) findViewById(R.id.claimInfoEndDateButton); // Destinations list LinearLayout destinationsList = (LinearLayout) findViewById(R.id.claimInfoDestinationsLinearLayout); // Color the LinearLayout to visually cue the user that it can be edited. colorViewEnabled(destinationsList); // Tags list LinearLayout tagsLinearLayout = (LinearLayout) findViewById(R.id.claimInfoTagsLinearLayout); View tagsThickHorizontalDivider = (View) findViewById(R.id.claimInfoTagsThickHorizontalDivider); Button viewTagsButton = (Button) findViewById(R.id.claimInfoViewTagsButton); // Claimant claim modifiers Button submitClaimButton = (Button) findViewById(R.id.claimInfoClaimSubmitButton); // Approver claim modifiers LinearLayout approverButtonsLinearLayout = (LinearLayout) findViewById(R.id.claimInfoApproverButtonsLinearLayout); EditText commentEditText = (EditText) findViewById(R.id.claimInfoCommentEditText); // Attach view items listener to view items button Button viewItemsButton = (Button) findViewById(R.id.claimInfoViewItemsButton); viewItemsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchExpenseItemsList(); } }); if (userData.getRole().equals(UserRole.CLAIMANT)) { if (isEditable(claim.getStatus(), userData.getRole())) { // Attach edit date listener to start date button startDateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startDatePressed(); } }); // Attach edit date listener to end date button endDateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { endDatePressed(); } }); // Attach submit claim listener to submit claim button submitClaimButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { submitClaim(); } }); } else { // These views should do nothing if the claim isn't editable disableView(startDateButton); disableView(endDateButton); disableView(submitClaimButton); } // Add listener to view tags button. User should be able to manage claim's tags // whether the claim is editable or not. viewTagsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchTagSelect(); } }); // Views a claimant doesn't need to see or have access to approverButtonsLinearLayout.setVisibility(View.GONE); commentEditText.setVisibility(View.GONE); } else if (userData.getRole().equals(UserRole.APPROVER)) { // Attach return claim listener to return claim button Button returnClaimButton = (Button) findViewById(R.id.claimInfoClaimReturnButton); returnClaimButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { returnClaim(); } }); // Attach approve claim listener to approve claim button Button approveClaimButton = (Button) findViewById(R.id.claimInfoClaimApproveButton); approveClaimButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { approveClaim(); } }); // The approver should see these views, but cannot use them. disableView(startDateButton); disableView(endDateButton); // Views an approver doesn't need to see or have access to statusLinearLayout.setVisibility(View.GONE); tagsLinearLayout.setVisibility(View.GONE); tagsThickHorizontalDivider.setVisibility(View.GONE); submitClaimButton.setVisibility(View.GONE); // No last approver if (approver == null) { TextView lastApproverTextView = (TextView) findViewById(R.id.claimInfoApproverTextView); lastApproverTextView.setVisibility(View.GONE); } } onLoaded(); } public void addDestination() { Destination destination = new Destination("", null, ""); DestinationEditorFragment editor = new DestinationEditorFragment(new DestinationCallback(), null, destination, true); editor.show(getFragmentManager(), "destinationEditor"); } /** * Launches the ExpenseItemInfo activity for a new item * @param claim the current expense claim */ public void addItem(Claim claim) { datasource.addItem(claim, new CreateNewItemCallback()); } /** * Launches the ExpenseItemsList activity. */ private void launchExpenseItemsList() { Intent intent = new Intent(this, ExpenseItemsListActivity.class); intent.putExtra(ExpenseItemsListActivity.USER_DATA, userData); intent.putExtra(ExpenseItemsListActivity.CLAIM_UUID, claimID); startActivity(intent); } /** * Launches the ExpenseItemInfo activity for a selected item * @param item The selected expense item */ private void launchExpenseItemInfo(Item item) { Intent intent = new Intent(this, ExpenseItemInfoActivity.class); intent.putExtra(ExpenseItemInfoActivity.FROM_CLAIM_INFO, true); intent.putExtra(ExpenseItemInfoActivity.ITEM_UUID, item.getUUID()); intent.putExtra(ExpenseItemInfoActivity.CLAIM_UUID, claim.getUUID()); intent.putExtra(ExpenseItemInfoActivity.USER_DATA, userData); startActivity(intent); } /** * Prompt for deleting the claim. */ public void promptDeleteClaim() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.claim_info_delete_message) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteClaim(); } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do nothing } }); lastAlertDialog = builder.create(); lastAlertDialog.show(); } /** * Delete the claim and finish the activity. */ public void deleteClaim() { ignoreUpdates = true; datasource.deleteClaim(claimID, new DeleteCallback()); } /** * Populate the fields with data. * @param claim The claim being viewed. * @param items All items (which will be filtered by claim UUID). * @param claimant The claimant, or null if the current user is the claimant. * @param approver The last approver, or null if there isn't one. */ public void populateClaimInfo(Claim claim, Collection<Item> items, User claimant, User approver, Collection<Tag> tags) { Button startDateButton = (Button) findViewById(R.id.claimInfoStartDateButton); setButtonDate(startDateButton, claim.getStartDate()); Button endDateButton = (Button) findViewById(R.id.claimInfoEndDateButton); setButtonDate(endDateButton, claim.getEndDate()); TextView statusTextView = (TextView) findViewById(R.id.claimInfoStatusTextView); statusTextView.setText(claim.getStatus().getString(this)); // Get list of claim items ArrayList<Item> claimItems = new ArrayList<Item>(); for (Item item : items) { if (item.getClaim().equals(claim.getUUID())) { claimItems.add(item); } } // Format string for view items button String formatString = getString(R.string.claim_info_view_items); String viewItemsButtonText = String.format(formatString, claimItems.size()); Button viewItemsButton = (Button) findViewById(R.id.claimInfoViewItemsButton); viewItemsButton.setText(viewItemsButtonText); // List totals ArrayList<String> totals = ClaimUtilities.getTotals(claimItems); String totalsString = TextUtils.join("\n", totals); TextView totalsTextView = (TextView) findViewById(R.id.claimInfoCurrencyTotalsListTextView); totalsTextView.setText(totalsString); // Show destinations LinearLayout destinationsList = (LinearLayout) findViewById(R.id.claimInfoDestinationsLinearLayout); destinationAdapter = new DestinationAdapter(isEditable(claim.getStatus(), userData.getRole())); destinationsList.removeAllViews(); DestinationCallback callback = new DestinationCallback(); for (Destination destination : claim.getDestinations()) { View view = destinationAdapter.createView(destination, this); view = setNewDestinationViewListeners(view, callback); destinationsList.addView(view); } userTags = new ArrayList<Tag>(); claimTags = new ArrayList<Tag>(); claimTagIDs = new ArrayList<UUID>(); // From the list of all tags, fill the various tag lists for the claim. for (Tag tag : tags) { if (claim.getUser().equals(tag.getUser())) { userTags.add(tag); if (claim.getTags().contains(tag.getUUID())) { claimTags.add(tag); claimTagIDs.add(tag.getUUID()); } } } setTagTextViewFromSelection(claimTags); if (userData.getRole().equals(UserRole.APPROVER)) { // Claimant name TextView claimantNameTextView = (TextView) findViewById(R.id.claimInfoClaimantNameTextView); claimantNameTextView.setText(claimant.getUserName()); } else if (userData.getRole().equals(UserRole.CLAIMANT)) { LinearLayout claimantNameLinearLayout = (LinearLayout) findViewById(R.id.claimInfoClaimantNameLinearLayout); claimantNameLinearLayout.setVisibility(View.GONE); } // Approver name (if there is one) if (approver != null) { TextView approverTextView = (TextView) findViewById(R.id.claimInfoApproverTextView); approverTextView.setText(approver.getUserName()); } else { LinearLayout approverLinearLayout = (LinearLayout) findViewById(R.id.claimInfoApproverLinearLayout); approverLinearLayout.setVisibility(View.GONE); } // Show approver comments LinearLayout commentsList = (LinearLayout) findViewById(R.id.claimInfoCommentsLinearLayout); commentsListAdapter = new ApproverCommentAdapter(this, claim.getComments()); for (int i = 0; i < commentsListAdapter.getCount(); i++) { View commentView = commentsListAdapter.getView(i, null, null); commentsList.addView(commentView); } // Scroll to top now in case comment list has extended the layout // Referenced http://stackoverflow.com/a/4488149 on 12/03/15 final ScrollView scrollView = (ScrollView) findViewById(R.id.claimInfoScrollView); scrollView.post(new Runnable() { @Override public void run() { scrollView.fullScroll(ScrollView.FOCUS_UP); } }); } /** * spawns the datepicker fragment for startdate button */ public void startDatePressed() { Date date = claim.getStartDate(); DatePickerFragment datePicker = new DatePickerFragment(date, new StartDateCallback()); datePicker.show(getFragmentManager(), "datePicker"); } /** * spawns the datpicker fragment for the end date button */ public void endDatePressed() { Date date = claim.getEndDate(); DatePickerFragment datePicker = new DatePickerFragment(date, new EndDateCallback()); datePicker.show(getFragmentManager(), "datePicker"); } /** * Launch the fragment for selecting tags for this claim. */ private void launchTagSelect() { SelectTagFragment tagFragment = new SelectTagFragment(userTags, claimTagIDs, new SelectTagFragment.ResultCallback() { @Override public void onSelectTagFragmentResult(HashSet<UUID> selected) { claimTagIDs = new ArrayList<UUID>(selected); claimTags = getTagsFromUUIDs(claimTagIDs, userTags); setTagTextViewFromSelection(claimTags); claim.setTags(claimTagIDs); } @Override public void onSelectTagFragmentCancelled() {} }); tagFragment.show(getFragmentManager(), "selectTags"); } /** * Given a list of Tag objects, turn it into one string that is a comma-separated * list of all the tags (empty string if no tags). Set this string to the TextView * that is supposed to hold the tags. * @param claimTags The list of tags to set as a string to the TextView. */ private void setTagTextViewFromSelection(ArrayList<Tag> claimTags) { // Create a comma-separated list of all the tags on this claim. String tagString = ""; for (int i = 0; i < claimTags.size(); i++) { if (i == 0) { tagString = claimTags.get(i).getTitle(); } else { tagString += ", " + claimTags.get(i).getTitle(); } } // Set the tag string. TextView tagsTextView = (TextView) findViewById(R.id.claimInfoTagsTextView); tagsTextView.setText(tagString); } /** * Given a list of Tag UUIDs for the claim and a list of Tags for the user, return * the list of Tags for the claim. * @param claimTagIDs The list of Tag UUID objects associated with this claim. * @param userTags The list of Tag objects belonging to the current user. * @return The list of Tag objects associated with this claim. */ private ArrayList<Tag> getTagsFromUUIDs(ArrayList<UUID> claimTagIDs, ArrayList<Tag> userTags) { ArrayList<Tag> claimTags = new ArrayList<Tag>(); for (UUID id : claimTagIDs) { for (Tag tag : userTags) { if (tag.getUUID().equals(id)) { claimTags.add(tag); break; } } } return claimTags; } /** * Set onClick and onLongClick listeners to the view for a destination. onClick is for editing * the destination, onLongClick is for deleting the destination. * @param view The view to set listeners on. * @param callback The callback to use in the onClick listener. * @return The view with both listeners set. */ private View setNewDestinationViewListeners(View view, final DestinationCallback callback) { view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setBackgroundColor(getResources().getColor(DestinationAdapter.COLOR_SELECTED)); Destination destination = destinationAdapter.getDestinationFromView(v); boolean editable = destinationAdapter.isEditable(); DestinationEditorFragment editor = new DestinationEditorFragment(callback, v, destination, editable); editor.show(getFragmentManager(), "destinationEditor"); } }); view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { v.setBackgroundColor(getResources().getColor(DestinationAdapter.COLOR_SELECTED)); Destination destination = destinationAdapter.getDestinationFromView(v); DestinationDeletionFragment deleter = new DestinationDeletionFragment(v, destination); deleter.show(getFragmentManager(), "destinationDeleter"); return false; } }); return view; } /** * Given a view an edited destination belongs to, or null if the destination is new and * does not belong to a view yet, create a new destination from the new attributes. * Update the existing view or create and add a new one, and update the list of destinations * in the claim. * @param view The view of the destination to be edited or added. Will be null if a new destination. * @param location The new location of the destination. * @param geolocation The new geolocation of the destination. * @param reason The new reason of the destination. */ private void editDestination(View view, String location, Geolocation geolocation, String reason) { Destination destination = new Destination(location, geolocation, reason); LinearLayout linearLayout = (LinearLayout) findViewById(R.id.claimInfoDestinationsLinearLayout); ArrayList<Destination> destinations = claim.getDestinations(); // A null view means a new destination. if (view == null) { view = destinationAdapter.createView(destination, this); view = setNewDestinationViewListeners(view, new DestinationCallback()); linearLayout.addView(view); destinations.add(destination); } else { int index = destinations.indexOf(destinationAdapter.getDestinationFromView(view)); destinationAdapter.setDestinationOnView(view, destination); destinations.set(index, destination); } claim.setDestinations(destinations); } /** * Given a view, delete its destination from the claim's destinations list * and remove the view from the LinearLayout. * @param view The view of the destination to be deleted. */ private void deleteDestination(View view) { Destination destination = destinationAdapter.getDestinationFromView(view); LinearLayout linearLayout = (LinearLayout) findViewById(R.id.claimInfoDestinationsLinearLayout); ArrayList<Destination> destinations = claim.getDestinations(); destinations.remove(destination); linearLayout.removeView(view); claim.setDestinations(destinations); } /** * Submits the selected claim and adds a comment if there exists one in the field. */ public void submitClaim() { // Submit only if claim has at least one destination, a description, all items of // claim have a description, and all items of claim are flagged as complete. datasource.getAllItems(new ResultCallback<Collection<Item>>() { @Override public void onResult(Collection<Item> items) { int dialogMessage = R.string.claim_info_submit_confirm; if (claim.getDestinations().isEmpty()) { dialogMessage = R.string.claim_info_submit_error_destination; } else { boolean descriptions = false; boolean indicators = false; for(Item item : items) { // Only inspect items belonging to this claim. if (item.getClaim().equals(claim.getUUID())) { descriptions = (item.getDescription().isEmpty()) ? true : descriptions; indicators = (!item.isComplete()) ? true : indicators; } } if (descriptions && indicators) dialogMessage = R.string.claim_info_submit_error_item; else if (descriptions) dialogMessage = R.string.claim_info_submit_error_item_description; else if (indicators) dialogMessage = R.string.claim_info_submit_error_item_completeness; } DialogInterface.OnClickListener submitDialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: claim.setStatus(Status.SUBMITTED); ClaimInfoActivity.this.finish(); break; case DialogInterface.BUTTON_NEGATIVE: Toast.makeText(ClaimInfoActivity.this, R.string.claim_info_not_submitted, Toast.LENGTH_SHORT).show(); break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(ClaimInfoActivity.this); lastAlertDialog = builder.setMessage(dialogMessage) .setPositiveButton(android.R.string.yes, submitDialogClickListener) .setNegativeButton(android.R.string.no, submitDialogClickListener) .show(); } @Override public void onError(String message) { Toast.makeText(ClaimInfoActivity.this, message, Toast.LENGTH_SHORT).show(); } }); } /** * returns the selected claim and adds a comment if there exists one in the field */ public void returnClaim() { final String commentText = checkForComment(); if (commentText == null) { return; } DialogInterface.OnClickListener returnDialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: claim.addComment(commentText); claim.setApprover(userData.getUUID()); claim.setStatus(Status.RETURNED); ClaimInfoActivity.this.finish(); break; case DialogInterface.BUTTON_NEGATIVE: Toast.makeText(ClaimInfoActivity.this, R.string.claim_info_not_returned, Toast.LENGTH_SHORT).show(); break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(ClaimInfoActivity.this); lastAlertDialog = builder.setMessage(R.string.claim_info_return_confirm) .setPositiveButton(android.R.string.yes, returnDialogClickListener) .setNegativeButton(android.R.string.no, returnDialogClickListener) .show(); } /** * approves the selected claim and adds a comment if there exists one in the field */ public void approveClaim() { final String commentText = checkForComment(); if (commentText == null) { return; } DialogInterface.OnClickListener returnDialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: claim.addComment(commentText); claim.setApprover(userData.getUUID()); claim.setStatus(Status.APPROVED); ClaimInfoActivity.this.finish(); break; case DialogInterface.BUTTON_NEGATIVE: Toast.makeText(ClaimInfoActivity.this, R.string.claim_info_not_approved, Toast.LENGTH_SHORT).show(); break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(ClaimInfoActivity.this); lastAlertDialog = builder.setMessage(R.string.claim_info_approve_confirm) .setPositiveButton(android.R.string.yes, returnDialogClickListener) .setNegativeButton(android.R.string.no, returnDialogClickListener) .show(); } /** * Make sure the approver left a comment. Set an error otherwise. * @return The comment if there was one, else null. */ private String checkForComment() { EditText commentEditText = (EditText) findViewById(R.id.claimInfoCommentEditText); final String commentText = commentEditText.getText().toString(); if (commentText.trim().equals("")) { commentEditText.setError(getString(R.string.claim_info_no_comment_error)); return null; } return commentText; } /** * Set the date in the date button after * datePicker fragment is spawned and * interacted with by the user * @param dateButton The button to be set * @param date Date to set the button to */ private void setButtonDate(Button dateButton, Date date) { java.text.DateFormat dateFormat = DateFormat.getMediumDateFormat(this); String dateString = dateFormat.format(date); dateButton.setText(dateString); } /** * Callback for claim data. */ class ClaimCallback implements ResultCallback<Claim> { @Override public void onResult(Claim claim) { ClaimInfoActivity.this.claim = claim; // Retrieve data MultiCallback multi = new MultiCallback(new ClaimDataMultiCallback()); // Create callbacks for MultiCallback datasource.getAllItems(multi.<Collection<Item>>createCallback(MULTI_ITEMS_ID)); datasource.getUser(claim.getUser(), multi.<User>createCallback(MULTI_CLAIMANT_ID)); datasource.getAllTags(multi.<Collection<Tag>>createCallback(MULTI_TAGS_ID)); UUID approverID = claim.getApprover(); if (approverID != null) { datasource.getUser(approverID, multi.<User>createCallback(MULTI_APPROVER_ID)); } multi.ready(); } @Override public void onError(String message) { Toast.makeText(ClaimInfoActivity.this, message, Toast.LENGTH_LONG).show(); } } /** * Callback for multiple types of claim data. */ class ClaimDataMultiCallback implements ResultCallback<SparseArray<Object>> { @Override public void onResult(SparseArray<Object> result) { User claimant = (User) result.get(MULTI_CLAIMANT_ID); User approver = null; if (claim.getApprover() != null) { approver = (User) result.get(MULTI_APPROVER_ID); } // We know the return results are the right type, so unchecked casts shouldn't be problematic. @SuppressWarnings("unchecked") Collection<Item> items = (Collection<Item>) result.get(MULTI_ITEMS_ID); @SuppressWarnings("unchecked") Collection<Tag> tags = (Collection<Tag>) result.get(MULTI_TAGS_ID); onGetAllData(items, claimant, approver, tags); } @Override public void onError(String message) { Toast.makeText(ClaimInfoActivity.this, message, Toast.LENGTH_LONG).show(); } } /** * Callback for claim deletion. */ class DeleteCallback implements ResultCallback<Void> { @Override public void onResult(Void result) { finish(); } @Override public void onError(String message) { Toast.makeText(ClaimInfoActivity.this, message, Toast.LENGTH_LONG).show(); ignoreUpdates = false; } } /** * Callback for when a new start date is selected. */ class StartDateCallback implements DatePickerFragment.ResultCallback { @Override public void onDatePickerFragmentResult(Date result) { // Error if invalid date if (result.after(claim.getEndDate())) { String error = getString(R.string.claim_info_start_date_error); Toast.makeText(ClaimInfoActivity.this, error, Toast.LENGTH_LONG).show(); // Update date button and date } else { claim.setStartDate(result); Button button = (Button) findViewById(R.id.claimInfoStartDateButton); setButtonDate(button, result); } } @Override public void onDatePickerFragmentCancelled() {} } /** * Callback for when a new end date is selected. */ class EndDateCallback implements DatePickerFragment.ResultCallback { @Override public void onDatePickerFragmentResult(Date result) { // Error if invalid date if (result.before(claim.getStartDate())) { String error = getString(R.string.claim_info_end_date_error); Toast.makeText(ClaimInfoActivity.this, error, Toast.LENGTH_LONG).show(); // Update date button and calendar } else { claim.setEndDate(result); Button button = (Button) findViewById(R.id.claimInfoEndDateButton); setButtonDate(button, result); } } @Override public void onDatePickerFragmentCancelled() {} } /** * Callback for when a new item is added. */ class CreateNewItemCallback implements ResultCallback<Item> { @Override public void onResult(Item result){ launchExpenseItemInfo(result); } @Override public void onError(String message){ Toast.makeText(ClaimInfoActivity.this, message, Toast.LENGTH_SHORT).show(); } } /** * Callback for when new destination fields are approved. */ class DestinationCallback implements DestinationEditorFragment.ResultCallback { @Override public void onDestinationEditorFragmentResult(View view, String location, Geolocation geolocation, String reason) { editDestination(view, location, geolocation, reason); } @Override public void onDestinationEditorFragmentDismissed(View view) { if (view != null) view.setBackgroundColor(ClaimInfoActivity.this.getResources().getColor(DestinationAdapter.COLOR_PLAIN)); } } /** * Custom fragment for deleting a destination. */ class DestinationDeletionFragment extends DialogFragment { private View view; private String location; public DestinationDeletionFragment(View view, Destination destination) { this.view = view; this.location = destination.getLocation(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { String message = ClaimInfoActivity.this.getString(R.string.claim_info_delete_destination) + "\n\n\"" + location + "\""; return new AlertDialog.Builder(ClaimInfoActivity.this) .setMessage(message) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteDestination(view); } }) .setNegativeButton(android.R.string.no, null) .create(); } @Override public void onDismiss(DialogInterface dialog) { view.setBackgroundColor(ClaimInfoActivity.this.getResources().getColor(DestinationAdapter.COLOR_PLAIN)); super.onDismiss(dialog); } } }
package com.mentor.nucleus.bp.io.mdl.test; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import com.mentor.nucleus.bp.core.Domain_c; import com.mentor.nucleus.bp.core.Ooaofooa; import com.mentor.nucleus.bp.core.SystemModel_c; import com.mentor.nucleus.bp.core.common.ClassQueryInterface_c; import com.mentor.nucleus.bp.core.common.IPersistenceHierarchyMetaData; import com.mentor.nucleus.bp.core.common.NonRootModelElement; import com.mentor.nucleus.bp.core.common.PersistableModelComponent; import com.mentor.nucleus.bp.core.common.PersistenceManager; import com.mentor.nucleus.bp.test.common.BaseTest; public class MultilevelIntermTest extends BaseTest { boolean setupDone = false; Ooaofooa modelRoot = null; IFile file = null; public MultilevelIntermTest(String name) throws CoreException { super("multilevel", name); } protected void setUp() throws Exception { super.setUp(); if (!setupDone) { file = importFile(Ooaofooa.MODELS_DIRNAME + "/graphics4MLPersistence." + Ooaofooa.MODELS_EXT);//$NON-NLS-1$ setupDone = true; } } public void testComponentCreation() throws Exception { modelRoot = Ooaofooa.getInstance("graphics4MLPersistence-forexport"); SystemModel_c sysModel = getSystemModel(file.getProject()); if(sysModel == null){ sysModel = new SystemModel_c(Ooaofooa.getDefaultInstance()); sysModel.setName(file.getProject().getName()); } importModel(new NullProgressMonitor(), sysModel, file, modelRoot, false, false, true); PersistenceManager manager = PersistenceManager.getDefaultInstance(); PersistableModelComponent rootComponent = manager.registerModel( getDomain(modelRoot), file.getProject()); PersistableModelComponent parent = rootComponent.getParent(); if(!parent.isPersisted()){ rootComponent = parent; } writeComponentAndChildren(rootComponent); putSharedResult("loaded-domain", getDomain(modelRoot)); } private void writeComponentAndChildren(PersistableModelComponent component) throws CoreException { component.persist(); for (Iterator iterator = component.getChildren().iterator(); iterator .hasNext();) { PersistableModelComponent child = (PersistableModelComponent) iterator .next(); writeComponentAndChildren(child); } } protected void tearDown() throws Exception { } public void xtestHeirarchyMetaData() throws Exception{ SystemModel_c system = getSystemModel(file.getProject()); printME("", system); } private void printME(String tab, NonRootModelElement me) { IPersistenceHierarchyMetaData persistenceMetadata = PersistenceManager.getHierarchyMetaData(); String name = "Instance of " + me.getClass().getName(); if(persistenceMetadata.isComponentRoot(me)){ name = persistenceMetadata.getRootElementName(me); } System.out.println(tab + name); List children = persistenceMetadata.getChildren(me, true); for (Iterator iterator = children.iterator(); iterator.hasNext();) { NonRootModelElement element = (NonRootModelElement) iterator.next(); printME(tab + " ", element); } } private SystemModel_c getSystemModel(final IProject project){ return SystemModel_c.SystemModelInstance( Ooaofooa.getDefaultInstance(), new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { SystemModel_c selected = (SystemModel_c) candidate; return selected.getName().equals( project.getName()); } }); } private Domain_c getDomain(Ooaofooa modelRoot){ return Domain_c.DomainInstance(modelRoot); } private boolean compareModels(Domain_c domain1, Domain_c domain2){ return compareModelElement(domain1, domain2); } private boolean compareModelElement(NonRootModelElement me1, NonRootModelElement me2){ if(me1.identityEquals(me2)){ IPersistenceHierarchyMetaData metaData = PersistenceManager.getHierarchyMetaData(); List children1 = metaData.getChildren(me1, false); List children2 = metaData.getChildren(me2, false); if(children1.size() != children2.size()){ System.err.println("children of " + getName(me1) + " does not matches with children count of " + getName(me2) + " (" + children1.size() + ":" + children2.size() + ")"); return false; } for (int i = 0; i<children1.size(); i++) { NonRootModelElement childFrom1 = (NonRootModelElement)children1.get(i); NonRootModelElement childFrom2 = find(childFrom1, children2); boolean equal = false; if(childFrom2 != null){ children2.remove(childFrom2); equal = compareModelElement(childFrom1, childFrom2); if(!equal){ System.err.println(" parents:" + getName(me1) + "<->" + getName(me2)); return false; } }else{ System.err.println("could not find sibling of " + getName(childFrom1)); return false; } } return true; } System.err.println(">>>>>>>>>>>>>" + getName(me1) + " does not matches with " + getName(me2)); return false; } private NonRootModelElement find(NonRootModelElement me, List list){ for (int i = 0; i<list.size(); i++) { if(me.identityEquals(list.get(i))){ return (NonRootModelElement)list.get(i); } } return null; } private String getName(NonRootModelElement me){ Class clazz = me.getClass(); Method method = null; try { method = clazz.getMethod("getName", null); } catch (Exception e) { } if(method == null){ try { method = clazz.getMethod("get_Name", null); } catch (Exception e) { } } String name = null; if(method != null){ try { name = clazz.getName() + "(" + (String)method.invoke(me, null) + ")"; } catch (Exception e) { e.printStackTrace(); } } if(name == null){ name = "Instance of " + clazz.getName(); } return name; } }
/** * Copyright 2012 multibit.org * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.multibit.viewsystem.swing.action; import java.io.File; import java.io.IOException; import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; import org.multibit.ApplicationDataDirectoryLocator; import org.multibit.Constants; import org.multibit.CreateControllers; import org.multibit.controller.bitcoin.BitcoinController; import org.multibit.file.FileHandler; import org.multibit.functionaltests.GenesisBlockReplayTest; import org.multibit.network.MultiBitService; import org.multibit.viewsystem.simple.SimpleViewSystem; import org.multibit.viewsystem.swing.view.components.FontSizer; import org.multibit.viewsystem.swing.view.panels.SendBitcoinConfirmPanel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SendBitcoinNowSubmitActionTest extends TestCase { private static final String EXPECTED_ENTER_THE_WALLET_PASSWORD = "Enter the wallet password"; private static final String EXPECTED_TEST_SEND_FAILED_ERROR = " test - send failed"; private static final String EXPECTED_SEND_FAILED = "The send of your bitcoin failed."; private static final String EXPECTED_YOUR_BITCOIN_WERE_SENT_SUCCESSFULLY = "Your bitcoin were sent successfully."; private static final String EXPECTED_SENDING_BITCOIN = "Sending bitcoin..."; public static final CharSequence TEST_PASSWORD1 = "my hovercraft has eels"; public static final CharSequence WALLET_PASSWORD = "testing testing 123"; private static final int DELAY_TO_COMPLETE_OPERATION = 12000; // milliseconds private static final int DELAY_TO_UPDATE_MESSAGES = 4000; // milliseconds private File multiBitDirectory; private static final Logger log = LoggerFactory.getLogger(SendBitcoinNowSubmitActionTest.class); private BitcoinController controller; @Before @Override public void setUp() throws IOException { // Get the system property runFunctionalTest to see if the functional // tests need running. String runFunctionalTests = System.getProperty(Constants.RUN_FUNCTIONAL_TESTS_PARAMETER); if (Boolean.TRUE.toString().equalsIgnoreCase(runFunctionalTests)) { multiBitDirectory = createMultiBitRuntime(); // set the application data directory to be the one we just created ApplicationDataDirectoryLocator applicationDataDirectoryLocator = new ApplicationDataDirectoryLocator(multiBitDirectory); // Create MultiBit controller. final CreateControllers.Controllers controllers = CreateControllers.createControllers(applicationDataDirectoryLocator); controller = controllers.bitcoinController; log.debug("Creating Bitcoin service"); // create the MultiBitService that connects to the bitcoin network MultiBitService multiBitService = new MultiBitService(controller); controller.setMultiBitService(multiBitService); // Add the simple view system (no Swing). SimpleViewSystem simpleViewSystem = new SimpleViewSystem(); controllers.coreController.registerViewSystem(simpleViewSystem); // MultiBit runtime is now setup and running // Wait for a peer connection. log.debug("Waiting for peer connection. . . "); while (!simpleViewSystem.isOnline()) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug("Now online."); // Wait a little longer to get a second connection. try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } } } @Test public void testSendBitcoinWithNonEncryptedWallet() throws Exception { // Get the system property runFunctionalTest to see if the functional // tests need running. String runFunctionalTests = System.getProperty(Constants.RUN_FUNCTIONAL_TESTS_PARAMETER); if (Boolean.TRUE.toString().equalsIgnoreCase(runFunctionalTests)) { // Create a new unencrypted wallet and put it in the model as the // active wallet. ActionTestUtils.createNewActiveWallet(controller, "testAddReceivingAddressesWithNonEncryptedWallet", false, null); // Create a new SendBitcoinNowSubmitAction to test. FontSizer.INSTANCE.initialise(controller); SendBitcoinConfirmPanel sendBitcoinConfirmPanel = new SendBitcoinConfirmPanel(controller, null, null); SendBitcoinNowAction sendBitcoinNowAction = sendBitcoinConfirmPanel.getSendBitcoinNowAction(); assertNotNull("sendBitcoinNowAction was not created successfully", sendBitcoinNowAction); assertTrue("Wallet password was enabled when it should not be", !sendBitcoinConfirmPanel.isWalletPasswordFieldEnabled()); // Set the action up to use test parameters and succeed-on-send. sendBitcoinNowAction.setTestParameters(true, true); // Execute - this should give the sending message or sent message. sendBitcoinNowAction.actionPerformed(null); assertTrue( "Wrong message - expecting sending/sent on messageText1, was '" + sendBitcoinConfirmPanel.getMessageText1() + "'", "".equals(sendBitcoinConfirmPanel.getMessageText1().trim()) || EXPECTED_SENDING_BITCOIN.equals(sendBitcoinConfirmPanel.getMessageText1()) || EXPECTED_YOUR_BITCOIN_WERE_SENT_SUCCESSFULLY.equals(sendBitcoinConfirmPanel.getMessageText1())); assertEquals("Wrong message - expecting sending on messageText2", "", sendBitcoinConfirmPanel.getMessageText2().trim()); // Wait a while and the message should be that it has completed the // send. Thread.sleep(DELAY_TO_COMPLETE_OPERATION); // Bitcoins should now be sent assertEquals("Wrong message - expecting success on messageText1", EXPECTED_YOUR_BITCOIN_WERE_SENT_SUCCESSFULLY, sendBitcoinConfirmPanel.getMessageText1()); assertEquals("Wrong message - expecting success on messageText2", "", sendBitcoinConfirmPanel.getMessageText2().trim()); // Set the action up to use test parameters and fail-on-send. sendBitcoinNowAction.setTestParameters(true, false); Thread.sleep(DELAY_TO_UPDATE_MESSAGES); // Execute - this should give the sending or failed message. sendBitcoinNowAction.actionPerformed(null); Thread.sleep(DELAY_TO_UPDATE_MESSAGES); assertTrue( "Wrong message - expecting sending/sent on messageText1 was '" + sendBitcoinConfirmPanel.getMessageText1() + "'", "".equals(sendBitcoinConfirmPanel.getMessageText1().trim()) || EXPECTED_SENDING_BITCOIN.equals(sendBitcoinConfirmPanel.getMessageText1()) || EXPECTED_SEND_FAILED.equals(sendBitcoinConfirmPanel.getMessageText1())); assertEquals("Wrong message - expecting sending on messageText2", EXPECTED_TEST_SEND_FAILED_ERROR, sendBitcoinConfirmPanel.getMessageText2()); // Wait a while and the message should be that it has failed the // send. Thread.sleep(DELAY_TO_COMPLETE_OPERATION); assertEquals("Wrong message - expecting success on messageText1", EXPECTED_SEND_FAILED, sendBitcoinConfirmPanel.getMessageText1()); assertEquals("Wrong message - expecting success on messageText2", EXPECTED_TEST_SEND_FAILED_ERROR, sendBitcoinConfirmPanel.getMessageText2()); } } @Test public void testSendBitcoinWithEncryptedWallet() throws Exception { // Get the system property runFunctionalTest to see if the functional // tests need running. String runFunctionalTests = System.getProperty(Constants.RUN_FUNCTIONAL_TESTS_PARAMETER); if (Boolean.TRUE.toString().equalsIgnoreCase(runFunctionalTests)) { // Create a new encrypted wallet and put it in the model as the // active wallet. ActionTestUtils.createNewActiveWallet(controller, "testAddReceivingAddressesWithNonEncryptedWallet", true, WALLET_PASSWORD); // Create a new SendBitcoinNowSubmitAction to test. FontSizer.INSTANCE.initialise(controller); SendBitcoinConfirmPanel sendBitcoinConfirmPanel = new SendBitcoinConfirmPanel(controller, null, null); SendBitcoinNowAction sendBitcoinNowAction = sendBitcoinConfirmPanel.getSendBitcoinNowAction(); assertNotNull("sendBitcoinNowAction was not created successfully", sendBitcoinNowAction); assertTrue("Wallet password was disabled when it should not be", sendBitcoinConfirmPanel.isWalletPasswordFieldEnabled()); // Set the action up to use test parameters and succeed-on-send. sendBitcoinNowAction.setTestParameters(true, true); // Wait for peer connections Thread.sleep(5000); // Execute - this should complain that the wallet password is not // set. sendBitcoinNowAction.actionPerformed(null); // Wait a while and the message should be that it has completed the // send. Thread.sleep(DELAY_TO_UPDATE_MESSAGES); assertTrue( "Wrong message - expecting no wallet password on messageText1, was '" + sendBitcoinConfirmPanel.getMessageText1() + "'", EXPECTED_ENTER_THE_WALLET_PASSWORD.equals(sendBitcoinConfirmPanel.getMessageText1())); // Set the wallet password. sendBitcoinConfirmPanel.setWalletPassword(WALLET_PASSWORD); // Execute - this should give the sending message or sent message. sendBitcoinNowAction.actionPerformed(null); assertTrue( "Wrong message - expecting sending/sent on messageText1, was '" + sendBitcoinConfirmPanel.getMessageText1() + "'", "".equals(sendBitcoinConfirmPanel.getMessageText1().trim()) || EXPECTED_SENDING_BITCOIN.equals(sendBitcoinConfirmPanel.getMessageText1()) || EXPECTED_YOUR_BITCOIN_WERE_SENT_SUCCESSFULLY.equals(sendBitcoinConfirmPanel.getMessageText1())); assertEquals("Wrong message - expecting sending on messageText2", "", sendBitcoinConfirmPanel.getMessageText2().trim()); // Wait a while and the message should be that it has completed the // send. Thread.sleep(DELAY_TO_COMPLETE_OPERATION); // Bitcoins should now be sent assertEquals("Wrong message - expecting success on messageText1", EXPECTED_YOUR_BITCOIN_WERE_SENT_SUCCESSFULLY, sendBitcoinConfirmPanel.getMessageText1()); assertEquals("Wrong message - expecting success on messageText2", "", sendBitcoinConfirmPanel.getMessageText2().trim()); // Set the action up to use test parameters and fail-on-send. sendBitcoinNowAction.setTestParameters(true, false); // Execute - this should complain that the wallet password is not // set. sendBitcoinNowAction.actionPerformed(null); // Wait a while and the message should be that it has completed the // send. Thread.sleep(DELAY_TO_UPDATE_MESSAGES); assertTrue( "Wrong message - expecting no wallet password on messageText1, was '" + sendBitcoinConfirmPanel.getMessageText1() + "'", EXPECTED_ENTER_THE_WALLET_PASSWORD.equals(sendBitcoinConfirmPanel.getMessageText1())); // Set the wallet password. sendBitcoinConfirmPanel.setWalletPassword(WALLET_PASSWORD); // Execute - this should give the sending or failed message. sendBitcoinNowAction.actionPerformed(null); assertTrue( "Wrong message - expecting sending/failed on messageText1 was '" + sendBitcoinConfirmPanel.getMessageText1() + "'", "".equals(sendBitcoinConfirmPanel.getMessageText1().trim()) || EXPECTED_SENDING_BITCOIN.equals(sendBitcoinConfirmPanel.getMessageText1()) || EXPECTED_SEND_FAILED.equals(sendBitcoinConfirmPanel.getMessageText1())); assertTrue( "Wrong message - expecting blank/errormessage on messageText2 was '" + sendBitcoinConfirmPanel.getMessageText2() + "'", "".equals(sendBitcoinConfirmPanel.getMessageText2().trim()) || EXPECTED_TEST_SEND_FAILED_ERROR.equals(sendBitcoinConfirmPanel.getMessageText2()) || EXPECTED_SEND_FAILED.equals(sendBitcoinConfirmPanel.getMessageText1())); // Wait a while and the message should be that it has failed the // send. Thread.sleep(DELAY_TO_COMPLETE_OPERATION); assertEquals("Wrong message - expecting success on messageText1", EXPECTED_SEND_FAILED, sendBitcoinConfirmPanel.getMessageText1()); assertEquals("Wrong message - expecting success on messageText2", EXPECTED_TEST_SEND_FAILED_ERROR, sendBitcoinConfirmPanel.getMessageText2()); } } /** * Create a working, portable runtime of MultiBit in a temporary directory. * * @return the temporary directory the multibit runtime has been created in */ private File createMultiBitRuntime() throws IOException { File multiBitDirectory = FileHandler.createTempDirectory("multibit"); String multiBitDirectoryPath = multiBitDirectory.getAbsolutePath(); System.out.println("Building MultiBit runtime in : " + multiBitDirectory.getAbsolutePath()); // Create an empty multibit.properties. File multibitProperties = new File(multiBitDirectoryPath + File.separator + "multibit.properties"); multibitProperties.createNewFile(); multibitProperties.deleteOnExit(); // Copy in the blockchain stored in git - this is in source/main/resources/. File multibitBlockchain = new File(multiBitDirectoryPath + File.separator + "multibit.blockchain"); FileHandler.copyFile(new File("./src/main/resources/multibit.blockchain"), multibitBlockchain); multibitBlockchain.deleteOnExit(); // Copy in the checkpoints stored in git - this is in source/main/resources/. File multibitCheckpoints = new File(multiBitDirectoryPath + File.separator + "multibit.checkpoints"); FileHandler.copyFile(new File("./src/main/resources/multibit.checkpoints"), multibitCheckpoints); multibitCheckpoints.deleteOnExit(); return multiBitDirectory; } }
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.kaazing.k3po.driver.internal.behavior.visitor; import org.kaazing.k3po.lang.internal.ast.AstAcceptNode; import org.kaazing.k3po.lang.internal.ast.AstAcceptableNode; import org.kaazing.k3po.lang.internal.ast.AstAcceptedNode; import org.kaazing.k3po.lang.internal.ast.AstBoundNode; import org.kaazing.k3po.lang.internal.ast.AstChildClosedNode; import org.kaazing.k3po.lang.internal.ast.AstChildOpenedNode; import org.kaazing.k3po.lang.internal.ast.AstCloseNode; import org.kaazing.k3po.lang.internal.ast.AstClosedNode; import org.kaazing.k3po.lang.internal.ast.AstCommandNode; import org.kaazing.k3po.lang.internal.ast.AstConnectAbortNode; import org.kaazing.k3po.lang.internal.ast.AstConnectAbortedNode; import org.kaazing.k3po.lang.internal.ast.AstConnectNode; import org.kaazing.k3po.lang.internal.ast.AstConnectedNode; import org.kaazing.k3po.lang.internal.ast.AstDisconnectNode; import org.kaazing.k3po.lang.internal.ast.AstDisconnectedNode; import org.kaazing.k3po.lang.internal.ast.AstEventNode; import org.kaazing.k3po.lang.internal.ast.AstNode; import org.kaazing.k3po.lang.internal.ast.AstOpenedNode; import org.kaazing.k3po.lang.internal.ast.AstPropertyNode; import org.kaazing.k3po.lang.internal.ast.AstReadAbortNode; import org.kaazing.k3po.lang.internal.ast.AstReadAbortedNode; import org.kaazing.k3po.lang.internal.ast.AstReadAdviseNode; import org.kaazing.k3po.lang.internal.ast.AstReadAdvisedNode; import org.kaazing.k3po.lang.internal.ast.AstReadAwaitNode; import org.kaazing.k3po.lang.internal.ast.AstReadClosedNode; import org.kaazing.k3po.lang.internal.ast.AstReadConfigNode; import org.kaazing.k3po.lang.internal.ast.AstReadNotifyNode; import org.kaazing.k3po.lang.internal.ast.AstReadOptionNode; import org.kaazing.k3po.lang.internal.ast.AstReadValueNode; import org.kaazing.k3po.lang.internal.ast.AstRejectedNode; import org.kaazing.k3po.lang.internal.ast.AstScriptNode; import org.kaazing.k3po.lang.internal.ast.AstStreamNode; import org.kaazing.k3po.lang.internal.ast.AstStreamableNode; import org.kaazing.k3po.lang.internal.ast.AstUnbindNode; import org.kaazing.k3po.lang.internal.ast.AstUnboundNode; import org.kaazing.k3po.lang.internal.ast.AstWriteAbortNode; import org.kaazing.k3po.lang.internal.ast.AstWriteAbortedNode; import org.kaazing.k3po.lang.internal.ast.AstWriteAdviseNode; import org.kaazing.k3po.lang.internal.ast.AstWriteAdvisedNode; import org.kaazing.k3po.lang.internal.ast.AstWriteAwaitNode; import org.kaazing.k3po.lang.internal.ast.AstWriteCloseNode; import org.kaazing.k3po.lang.internal.ast.AstWriteConfigNode; import org.kaazing.k3po.lang.internal.ast.AstWriteFlushNode; import org.kaazing.k3po.lang.internal.ast.AstWriteNotifyNode; import org.kaazing.k3po.lang.internal.ast.AstWriteOptionNode; import org.kaazing.k3po.lang.internal.ast.AstWriteValueNode; // Note: this is no longer injecting, just validating, as injection is now generalized public class ValidateStreamsVisitor implements AstNode.Visitor<AstScriptNode, ValidateStreamsVisitor.State> { public enum StreamState { // @formatter:off OPEN, CLOSED, // @formatter:on } public static final class State { private StreamState readState; private StreamState writeState; public State() { readState = StreamState.OPEN; writeState = StreamState.OPEN; } } @Override public AstScriptNode visit(AstScriptNode script, State state) { for (AstStreamNode stream : script.getStreams()) { stream.accept(this, state); } return null; } @Override public AstScriptNode visit(AstPropertyNode propertyNode, State state) { return null; } @Override public AstScriptNode visit(AstAcceptNode acceptNode, State state) { for (AstStreamableNode streamable : acceptNode.getStreamables()) { streamable.accept(this, state); } for (AstAcceptableNode acceptable : acceptNode.getAcceptables()) { state.readState = StreamState.OPEN; state.writeState = StreamState.OPEN; acceptable.accept(this, state); } return null; } @Override public AstScriptNode visit(AstConnectNode connectNode, State state) { state.writeState = StreamState.OPEN; state.readState = StreamState.OPEN; for (AstStreamableNode streamable : connectNode.getStreamables()) { streamable.accept(this, state); } return null; } @Override public AstScriptNode visit(AstConnectAbortNode node, State state) { switch (state.writeState) { case OPEN: state.readState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstConnectAbortedNode node, State state) { switch (state.writeState) { case OPEN: state.readState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstReadConfigNode node, State state) { switch (state.readState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected read config event (%s) while reading in state %s", node .toString().trim(), state.readState)); } return null; } @Override public AstScriptNode visit(AstWriteConfigNode node, State state) { switch (state.writeState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected write config command (%s) while writing in state %s", node .toString().trim(), state.writeState)); } return null; } @Override public AstScriptNode visit(AstReadAdviseNode node, State state) { switch (state.readState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected read advise command (%s) while writing in state %s", node .toString().trim(), state.writeState)); } return null; } @Override public AstScriptNode visit(AstReadAdvisedNode node, State state) { switch (state.readState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected read advised event (%s) while writing in state %s", node .toString().trim(), state.writeState)); } return null; } @Override public AstScriptNode visit(AstWriteAdviseNode node, State state) { switch (state.writeState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected write advise command (%s) while writing in state %s", node .toString().trim(), state.writeState)); } return null; } @Override public AstScriptNode visit(AstWriteAdvisedNode node, State state) { switch (state.writeState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected write advised event (%s) while writing in state %s", node .toString().trim(), state.writeState)); } return null; } @Override public AstScriptNode visit(AstReadClosedNode node, State state) { switch (state.readState) { case OPEN: state.readState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInReadState(node, state)); } return null; } @Override public AstScriptNode visit(AstWriteCloseNode node, State state) { switch (state.writeState) { case OPEN: state.writeState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstWriteAbortNode node, State state) { switch (state.readState) { case OPEN: case CLOSED: state.writeState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInReadState(node, state)); } return null; } @Override public AstScriptNode visit(AstReadAbortNode node, State state) { switch (state.readState) { case OPEN: case CLOSED: state.readState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInReadState(node, state)); } return null; } @Override public AstScriptNode visit(AstReadAbortedNode node, State state) { switch (state.writeState) { case OPEN: case CLOSED: state.readState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstWriteAbortedNode node, State state) { switch (state.writeState) { case OPEN: case CLOSED: state.writeState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstReadValueNode node, State state) { switch (state.readState) { case OPEN: break; default: throw new IllegalStateException(unexpectedInReadState(node, state)); } return null; } @Override public AstScriptNode visit(AstWriteValueNode node, State state) { switch (state.writeState) { case OPEN: break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstWriteFlushNode node, State state) { switch (state.writeState) { case OPEN: break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstAcceptedNode node, State state) { for (AstStreamableNode streamable : node.getStreamables()) { streamable.accept(this, state); } return null; } @Override public AstScriptNode visit(AstRejectedNode node, State state) { for (AstStreamableNode streamable : node.getStreamables()) { streamable.accept(this, state); } return null; } @Override public AstScriptNode visit(AstDisconnectNode node, State state) { return null; } @Override public AstScriptNode visit(AstUnbindNode node, State state) { return null; } @Override public AstScriptNode visit(AstCloseNode node, State state) { return null; } @Override public AstScriptNode visit(AstChildOpenedNode node, State state) { return null; } @Override public AstScriptNode visit(AstChildClosedNode node, State state) { return null; } @Override public AstScriptNode visit(AstOpenedNode node, State state) { return null; } @Override public AstScriptNode visit(AstBoundNode node, State state) { return null; } @Override public AstScriptNode visit(AstConnectedNode node, State state) { return null; } @Override public AstScriptNode visit(AstDisconnectedNode node, State state) { return null; } @Override public AstScriptNode visit(AstUnboundNode node, State state) { return null; } @Override public AstScriptNode visit(AstClosedNode node, State state) { switch (state.readState) { case OPEN: state.readState = StreamState.CLOSED; break; case CLOSED: break; default: throw new IllegalStateException(unexpectedInReadState(node, state)); } switch (state.writeState) { case OPEN: state.writeState = StreamState.CLOSED; break; case CLOSED: break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstReadAwaitNode node, State state) { return null; } @Override public AstScriptNode visit(AstWriteAwaitNode node, State state) { return null; } @Override public AstScriptNode visit(AstReadNotifyNode node, State state) { return null; } @Override public AstScriptNode visit(AstWriteNotifyNode node, State state) { return null; } @Override public AstScriptNode visit(AstReadOptionNode node, State state) { return null; } @Override public AstScriptNode visit(AstWriteOptionNode node, State state) { return null; } private String unexpectedInReadState(AstNode node, State state) { return String.format("Unexpected %s while reading in state %s", description(node), state.readState); } private String unexpectedInWriteState(AstNode node, State state) { return String.format("Unexpected %s while writing in state %s", description(node), state.writeState); } private String description(AstNode node) { String description = node.toString().trim(); if (node instanceof AstEventNode) { description = String.format("event (%s)", description); } else if (node instanceof AstCommandNode) { description = String.format("command (%s)", description); } return description; } }
/* * Extremely Compiler Collection * Copyright (c) 2015-2020, Jianping Zeng. * * 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 backend.codegen.dagisel; import backend.codegen.*; import backend.codegen.dagisel.SDNode.*; import backend.debug.DebugLoc; import backend.mc.MCInstrDesc; import backend.mc.MCRegisterClass; import backend.mc.MCSymbol; import backend.target.TargetInstrInfo; import backend.target.TargetOpcode; import backend.target.TargetRegisterInfo; import backend.target.TargetSubtarget; import backend.type.Type; import backend.value.ConstantFP; import gnu.trove.map.hash.TObjectIntHashMap; import tools.Util; import java.util.HashSet; import java.util.LinkedList; import java.util.Objects; import java.util.Stack; import static backend.codegen.MachineInstrBuilder.buildMI; import static backend.codegen.dagisel.SDep.Kind.Data; import static backend.codegen.dagisel.SDep.Kind.Order; import static backend.mc.MCOperandInfo.OperandConstraint.TIED_TO; import static backend.target.TargetRegisterInfo.isPhysicalRegister; import static backend.target.TargetRegisterInfo.isVirtualRegister; /** * A ScheduleDAG for scheduling SDNode-based DAGs. * <p> * Edges between SUnits are initially based on edges in the SelectionDAG, * and additional edges can be added by the schedulers as heuristics. * SDNodes such as Constants, Registers, and a few others that are not * interesting to schedulers are not allocated SUnits. * <p> * SDNodes with MVT::Flag operands are grouped along with the flagged * nodes into a single SUnit so that they are scheduled together. * <p> * SDNode-based scheduling graphs do not use SDep::Anti or SDep::Output * edges. Physical register dependence information is not carried in * the DAG and must be handled explicitly by schedulers. */ public abstract class ScheduleDAGSDNodes extends ScheduleDAG { public SelectionDAG dag; public ScheduleDAGSDNodes(MachineFunction mf) { super(mf); } public void run(SelectionDAG dag, MachineBasicBlock mbb, int insertPos) { this.dag = dag; super.run(dag, mbb, insertPos); } private static boolean isPassiveNode(SDNode node) { if (node == null) return false; switch (node.getOpcode()) { case ISD.Constant: case ISD.TargetConstant: case ISD.ConstantFP: case ISD.TargetConstantFP: case ISD.GlobalAddress: case ISD.TargetGlobalAddress: case ISD.TargetGlobalTLSAddress: case ISD.GlobalTLSAddress: case ISD.Register: case ISD.BasicBlock: case ISD.FrameIndex: case ISD.TargetFrameIndex: case ISD.ConstantPool: case ISD.TargetConstantPool: case ISD.JumpTable: case ISD.TargetJumpTable: case ISD.ExternalSymbol: case ISD.BlockAddress: case ISD.TargetExternalSymbol: case ISD.TargetBlockAddress: case ISD.MEMOPERAND: case ISD.EntryToken: return true; default: return false; } } public SUnit newSUnit(SDNode n) { SUnit su = new SUnit(n, sunits.size()); su.originNode = su; sunits.add(su); return su; } public SUnit clone(SUnit u) { SUnit su = new SUnit(u.getNode(), -1); su.originNode = u.originNode; su.latency = u.latency; su.isTwoAddress = u.isTwoAddress; su.isCommutable = u.isCommutable; su.hasPhysRegDefs = u.hasPhysRegDefs; su.isCloned = true; return su; } public void buildSchedGraph() { buildSchedUnits(); addSchedEdges(); } public void computeLatency(SUnit su) { Util.shouldNotReachHere("Should not reach here!"); } public static int countResults(SDNode node) { int n = node.getNumValues(); while (n != 0 && node.getValueType(n - 1).getSimpleVT().simpleVT == MVT.Glue) --n; if (n > 0 && node.getValueType(n - 1).getSimpleVT().simpleVT == MVT.Other) --n; return n; } public static int countOperands(SDNode node) { int n = node.getNumOperands(); while (n > 0 && node.getOperand(n - 1).getValueType().getSimpleVT().simpleVT == MVT.Glue) --n; if (n > 0 && node.getOperand(n - 1).getValueType().getSimpleVT().simpleVT == MVT.Other) --n; while (n > 0 && node.getOperand(n - 1).getNode() instanceof MemOperandSDNode) --n; return n; } public void emitNode(SDNode node, boolean isClone, boolean isCloned, TObjectIntHashMap<SDValue> vrBaseMap) { // if this is a machine instruction. if (node.isMachineOpecode()) { int opc = node.getMachineOpcode(); if (opc == TargetOpcode.EXTRACT_SUBREG || opc == TargetOpcode.INSERT_SUBREG || opc == TargetOpcode.SUBREG_TO_REG) { emitSubregNode(node, vrBaseMap); return; } if (opc == TargetOpcode.COPY_TO_REGCLASS) { emitCopyToRegClassNode(node, vrBaseMap); return; } if (opc == TargetOpcode.IMPLICIT_DEF) { // We just want a unique VR for each IMPLICIT_DEF use. return; } MCInstrDesc tid = tii.get(opc); int numResults = countResults(node); int nodeOperands = countOperands(node); boolean hasPhysRegOuts = numResults > tid.getNumDefs() && tid.getImplicitDefs() != null && tid.getImplicitDefs().length > 0; // create a machine instruction. MachineInstr mi = buildMI(tid, node.getDebugLoc()).getMInstr(); if (numResults > 0) { createVirtualRegisters(node, mi, tid, isClone, isCloned, vrBaseMap); } boolean hasOptPRefs = tid.getNumDefs() > numResults; Util.assertion(!hasOptPRefs || !hasPhysRegOuts); int numSkip = hasOptPRefs ? tid.getNumDefs() - numResults : 0; // insert new operand into this machine instruction. for (int i = numSkip; i < nodeOperands; i++) { addOperand(mi, node.getOperand(i), i - numSkip + tid.getNumDefs(), tid, vrBaseMap); } mbb.insert(insertPos++, mi); if (hasPhysRegOuts) { for (int i = tid.getNumDefs(); i < numResults; i++) { int reg = tid.getImplicitDefs()[i - tid.getNumDefs()]; if (node.hasAnyUseOfValue(i)) emitCopyFromReg(node, i, isClone, isCloned, reg, vrBaseMap); } } return; } switch (node.getOpcode()) { default: Util.shouldNotReachHere( "This is target-independent node should have been selected"); break; case ISD.EntryToken: Util.shouldNotReachHere("EntryToken should have been excluded from the schedule!"); break; case ISD.MERGE_VALUES: case ISD.TokenFactor: break; case ISD.CopyToReg: { SDValue srcVal = node.getOperand(2); int srcReg; if (srcVal.getNode() instanceof RegisterSDNode) srcReg = ((RegisterSDNode) srcVal.getNode()).getReg(); else srcReg = getVR(srcVal, vrBaseMap); int destReg = ((RegisterSDNode) node.getOperand(1).getNode()).getReg(); if (srcReg == destReg) break; buildMI(mbb, insertPos++, node.getDebugLoc(), tii.get(TargetOpcode.COPY), destReg).addReg(srcReg); break; } case ISD.CopyFromReg: int srcReg = ((RegisterSDNode) node.getOperand(1).getNode()).getReg(); emitCopyFromReg(node, 0, isClone, isCloned, srcReg, vrBaseMap); break; case ISD.EH_LABEL: MCSymbol sym = ((EHLabelSDNode)node).getLabel(); buildMI(mbb, insertPos++, node.getDebugLoc(), tii.get(TargetOpcode.EH_LABEL)).addMCSym(sym); break; case ISD.INLINEASM: Util.shouldNotReachHere("InlineAsm not supported currently!"); break; } } public MachineBasicBlock emitSchedule() { TObjectIntHashMap<SDValue> vrBaseMap = new TObjectIntHashMap<>(); TObjectIntHashMap<SUnit> copyVRBaseMap = new TObjectIntHashMap<>(); for (SUnit su : sequence) { if (su == null) { emitNoop(); continue; } if (su.getNode() == null) { emitPhysRegCopy(su, copyVRBaseMap); continue; } LinkedList<SDNode> flaggedNodes = new LinkedList<>(); for (SDNode flag = su.getNode().getFlaggedNode(); flag != null; flag = flag.getFlaggedNode()) flaggedNodes.add(flag); while (!flaggedNodes.isEmpty()) { SDNode sn = flaggedNodes.removeLast(); emitNode(sn, !Objects.equals(su.originNode, su), su.isCloned, vrBaseMap); } emitNode(su.getNode(), !Objects.equals(su.originNode, su), su.isCloned, vrBaseMap); } return mbb; } @Override public abstract void schedule(); public void dumpNode(SUnit su) { if (su.getNode() == null) { System.err.println("PHYS REG COPY!"); return; } su.getNode().dump(dag); System.err.println(); LinkedList<SDNode> flaggedNodes = new LinkedList<>(); for (SDNode n = su.getNode().getFlaggedNode(); n != null; n = n.getFlaggedNode()) { flaggedNodes.add(n); } while (!flaggedNodes.isEmpty()) { System.err.print(" "); SDNode n = flaggedNodes.removeLast(); n.dump(dag); System.err.println(); } } public String getGraphNodeLabel(SUnit su) { StringBuilder sb = new StringBuilder(); sb.append("SU(").append(su.nodeNum).append("): "); if (su.getNode() != null) { LinkedList<SDNode> flaggedNodes = new LinkedList<>(); for (SDNode n = su.getNode(); n != null; n = n.getFlaggedNode()) flaggedNodes.add(n); while (!flaggedNodes.isEmpty()) { sb.append(SelectionDAGDotGraphTraits.getNodeLabel(flaggedNodes.getLast(), dag, false)); flaggedNodes.removeLast(); if (!flaggedNodes.isEmpty()) sb.append("\n "); } } else { sb.append("CROSS RC COPY"); } return sb.toString(); } /** * Generates machine instruction for subreg SDNode. * * @param node * @param vrBaseMap */ private void emitSubregNode(SDNode node, TObjectIntHashMap<SDValue> vrBaseMap) { int vrBase = 0; int opc = node.getMachineOpcode(); for (SDUse u : node.getUseList()) { SDNode user = u.getUser(); if (user.getOpcode() == ISD.CopyToReg && user.getOperand(2).getNode().equals(node)) { int destReg = ((RegisterSDNode) user.getOperand(1).getNode()).getReg(); if (isVirtualRegister(destReg)) { vrBase = destReg; break; } } } if (opc == TargetOpcode.EXTRACT_SUBREG) { long subIdx = ((ConstantSDNode) node.getOperand(1).getNode()).getZExtValue(); MachineInstr mi = buildMI(tii.get(TargetOpcode.EXTRACT_SUBREG), node.getDebugLoc()).getMInstr(); int vreg = getVR(node.getOperand(0), vrBaseMap); MCRegisterClass destRC = mri.getRegClass(vreg); MCRegisterClass srcRC = destRC.getSubRegisterRegClass(subIdx); Util.assertion(srcRC != null, "Invalid subregister index in EXTRACT_SUBREG"); if (vrBase == 0 || srcRC != mri.getRegClass(vrBase)) { vrBase = mri.createVirtualRegister(srcRC); } mi.addOperand(MachineOperand.createReg(vrBase, true, false)); addOperand(mi, node.getOperand(0), 0, null, vrBaseMap); mi.addOperand(MachineOperand.createImm(subIdx)); mbb.insert(insertPos++, mi); } else if (opc == TargetOpcode.INSERT_SUBREG || opc == TargetOpcode.SUBREG_TO_REG) { SDValue n0 = node.getOperand(0); SDValue n1 = node.getOperand(1); SDValue n2 = node.getOperand(2); int subReg = getVR(n1, vrBaseMap); int subIdx = (int) ((ConstantSDNode) n2.getNode()).getZExtValue(); MCRegisterClass destRC = mri.getRegClass(subReg); MCRegisterClass srcRC = destRC .getSuperRegisterRegClass(tri, destRC, subIdx, node.getValueType(0)); if (vrBase == 0 || !srcRC.equals(mri.getRegClass(vrBase))) { vrBase = mri.createVirtualRegister(srcRC); } MachineInstr mi = buildMI(tii.get(opc), node.getDebugLoc()).getMInstr(); mi.addOperand(MachineOperand.createReg(vrBase, true, false)); if (opc == TargetOpcode.SUBREG_TO_REG) { ConstantSDNode sdn = (ConstantSDNode) n0.getNode(); mi.addOperand(MachineOperand.createImm(sdn.getZExtValue())); } else addOperand(mi, n0, 0, null, vrBaseMap); addOperand(mi, n1, 0, null, vrBaseMap); mi.addOperand(MachineOperand.createImm(subIdx)); mbb.insert(insertPos++, mi); } else Util.shouldNotReachHere("Node is not insert_subreg, extract_subreg, or subreg_to_reg"); SDValue op = new SDValue(node, 0); Util.assertion(!vrBaseMap.containsKey(op), "Node emitted out of order!"); vrBaseMap.put(op, vrBase); } private void emitCopyToRegClassNode(SDNode node, TObjectIntHashMap<SDValue> vrBaseMap) { int vreg = getVR(node.getOperand(0), vrBaseMap); int destRCIdx = (int) ((ConstantSDNode) node.getOperand(1).getNode()).getZExtValue(); MCRegisterClass destRC = tri.getRegClass(destRCIdx); int newVReg = mri.createVirtualRegister(destRC); buildMI(mbb, insertPos++, node.getDebugLoc(), tii.get(TargetOpcode.COPY), newVReg).addReg(vreg); SDValue op = new SDValue(node, 0); Util.assertion(!vrBaseMap.containsKey(op)); vrBaseMap.put(op, newVReg); } /** * Return the virtual register corresponding to the * specified SDValue. */ private int getVR(SDValue op, TObjectIntHashMap<SDValue> vrBaseMap) { if (op.isMachineOpcode() && op.getMachineOpcode() == TargetOpcode.IMPLICIT_DEF) { int vreg = getDstOfOnlyCopyToRegUse(op.getNode(), op.getResNo()); if (vreg == 0) { MCRegisterClass rc = tli.getRegClassFor(op.getValueType()); vreg = mri.createVirtualRegister(rc); } buildMI(mbb, insertPos++, op.getDebugLoc(), tii.get(TargetOpcode.IMPLICIT_DEF), vreg); return vreg; } Util.assertion(vrBaseMap.containsKey(op)); return vrBaseMap.get(op); } private int getDstOfOnlyCopyToRegUse(SDNode node, int resNo) { if (!node.hasOneUse()) return 0; SDNode user = node.getUseList().get(0).getUser(); if (user.getOpcode() == ISD.CopyToReg && user.getOperand(2).getNode().equals(node) && user.getOperand(2).getResNo() == resNo) { int reg = ((RegisterSDNode) user.getOperand(1).getNode()).getReg(); if (isVirtualRegister(reg)) return reg; } return 0; } private void addOperand(MachineInstr mi, SDValue op, int iiOpNum, MCInstrDesc tid, TObjectIntHashMap<SDValue> vrBaseMap) { if (op.isMachineOpcode()) addRegisterOperand(mi, op, iiOpNum, tid, vrBaseMap); else if (op.getNode() instanceof ConstantSDNode) { long imm = ((ConstantSDNode) op.getNode()).getSExtValue(); mi.addOperand(MachineOperand.createImm(imm)); } else if (op.getNode() instanceof ConstantFPSDNode) { ConstantFP imm = ((ConstantFPSDNode) op.getNode()).getConstantFPValue(); mi.addOperand(MachineOperand.createFPImm(imm)); } else if (op.getNode() instanceof RegisterSDNode) { int reg = ((RegisterSDNode) op.getNode()).getReg(); boolean isImp = tid != null && iiOpNum >= tid.getNumOperands() && !tid.isVariadic(); mi.addOperand(MachineOperand.createReg(reg, false, isImp)); } else if (op.getNode() instanceof GlobalAddressSDNode) { GlobalAddressSDNode gas = (GlobalAddressSDNode) op.getNode(); mi.addOperand(MachineOperand.createGlobalAddress(gas.getGlobalValue(), gas.getOffset(), gas.getTargetFlags())); } else if (op.getNode() instanceof BasicBlockSDNode) { BasicBlockSDNode bb = (BasicBlockSDNode) op.getNode(); mi.addOperand(MachineOperand.createMBB(bb.getBasicBlock(), 0)); } else if (op.getNode() instanceof FrameIndexSDNode) { FrameIndexSDNode fi = (FrameIndexSDNode) op.getNode(); mi.addOperand(MachineOperand.createFrameIndex(fi.getFrameIndex())); } else if (op.getNode() instanceof JumpTableSDNode) { JumpTableSDNode jti = (JumpTableSDNode) op.getNode(); mi.addOperand(MachineOperand.createJumpTableIndex(jti.getJumpTableIndex(), jti.getTargetFlags())); } else if (op.getNode() instanceof ConstantPoolSDNode) { ConstantPoolSDNode cp = (ConstantPoolSDNode) op.getNode(); int offset = cp.getOffset(); int align = cp.getAlignment(); Type ty = cp.getType(); if (align == 0) { align = tm.getTargetData().getPrefTypeAlignment(ty); if (align == 0) { align = (int) tm.getTargetData().getTypeAllocSize(ty); } } int idx; if (cp.isMachineConstantPoolValue()) idx = mcpl.getConstantPoolIndex(cp.getMachineConstantPoolValue(), align); else idx = mcpl.getConstantPoolIndex(cp.getConstantValue(), align); mi.addOperand(MachineOperand.createConstantPoolIndex(idx, offset, cp.getTargetFlags())); } else if (op.getNode() instanceof ExternalSymbolSDNode) { ExternalSymbolSDNode es = (ExternalSymbolSDNode) op.getNode(); mi.addOperand(MachineOperand.createExternalSymbol(es.getExtSymol(), 0, es.getTargetFlags())); } else if (op.getNode() instanceof BlockAddressSDNode) { BlockAddressSDNode ba = (BlockAddressSDNode) op.getNode(); mi.addOperand(MachineOperand.createBlockAddress(ba.getBlockAddress(), ba.getTargetFlags())); } else { Util.assertion(!op.getValueType().equals(new EVT(MVT.Other)) && !op.getValueType().equals(new EVT(MVT.Glue))); addRegisterOperand(mi, op, iiOpNum, tid, vrBaseMap); } } private static final int MinRCSize = 4; private void addRegisterOperand(MachineInstr mi, SDValue op, int iiOpNum, MCInstrDesc tid, TObjectIntHashMap<SDValue> vrBaseMap) { Util.assertion(!op.getValueType().equals(new EVT(MVT.Other)) && !op.getValueType().equals(new EVT(MVT.Glue))); int vreg = getVR(op, vrBaseMap); Util.assertion(isVirtualRegister(vreg)); MCInstrDesc ii = mi.getDesc(); boolean isOptDef = iiOpNum < ii.getNumOperands() && ii.opInfo[iiOpNum].isOptionalDef(); if (tid != null) { MCRegisterClass srcRC = mri.getRegClass(vreg); MCRegisterClass destRC = null; if (iiOpNum < tid.getNumOperands()) destRC = tid.opInfo[iiOpNum].getRegisterClass(tri); Util.assertion(destRC != null || (ii.isVariadic() && iiOpNum >= ii.getNumOperands()), "Don't have operand info for this instruction!"); // It is normal to emit a copy between two different register classes, such as GPR to GPRnopc // but those two register classes have a common sub register class, GPRnopc, we use emit a // virtual register with the GPRnopc RC. if (destRC != null && mri.constraintRegClass(vreg, destRC, MinRCSize) == null) { int newVReg = mri.createVirtualRegister(destRC); buildMI(mbb, insertPos++, new DebugLoc(), tii.get(TargetOpcode.COPY), newVReg).addReg(vreg); vreg = newVReg; } } mi.addOperand(MachineOperand.createReg(vreg, isOptDef, false)); } private void emitCopyFromReg(SDNode node, int resNo, boolean isClone, boolean isCloned, int srcReg, TObjectIntHashMap<SDValue> vrBaseMap) { int vrbase = 0; if (isVirtualRegister(srcReg)) { SDValue op = new SDValue(node, resNo); if (isClone) vrBaseMap.remove(op); Util.assertion(!vrBaseMap.containsKey(op)); vrBaseMap.put(op, srcReg); return; } boolean matchReg = true; MCRegisterClass useRC = null; EVT vt = node.getValueType(resNo); if (tli.isTypeLegal(vt)) useRC = tli.getRegClassFor(vt); if (!isClone && !isCloned) { for (SDUse u : node.useList) { SDNode user = u.getUser(); boolean match = true; if (user.getOpcode() == ISD.CopyToReg && user.getOperand(2).getNode().equals(node) && user.getOperand(2).getResNo() == resNo) { int destReg = ((RegisterSDNode) user.getOperand(1).getNode()).getReg(); if (isVirtualRegister(destReg)) { vrbase = destReg; match = false; } else if (destReg != srcReg) { match = false; } } else { for (int i = 0, e = user.getNumOperands(); i < e; i++) { SDValue op = user.getOperand(i); if (!op.getNode().equals(node) || op.getResNo() != resNo) continue; if (vt.getSimpleVT().simpleVT == MVT.Other || vt.getSimpleVT().simpleVT == MVT.Glue) continue; match = false; if (user.isMachineOpecode()) { MCInstrDesc ii = tii.get(user.getMachineOpcode()); MCRegisterClass rc = null; if (i + ii.getNumDefs() < ii.getNumOperands()) rc = ii.opInfo[i + ii.getNumDefs()].getRegisterClass(tri); if (useRC == null) useRC = rc; else if (rc != null) { MCRegisterClass comRC = tri.getCommonSubClass(useRC, rc); if (comRC != null) useRC = comRC; } } } } matchReg &= match; if (vrbase != 0) break; } MCRegisterClass srcRC, destRC; srcRC = tri.getPhysicalRegisterRegClass(srcReg, vt); if (vrbase != 0) destRC = mri.getRegClass(vrbase); else if (useRC != null) destRC = useRC; else destRC = tli.getRegClassFor(vt); if (matchReg && srcRC.getCopyCost() < 0) vrbase = srcReg; else { vrbase = mri.createVirtualRegister(destRC); buildMI(mbb, insertPos++, node.getDebugLoc(), tii.get(TargetOpcode.COPY), vrbase).addReg(srcReg); } SDValue op = new SDValue(node, resNo); if (isClone) vrBaseMap.remove(op); Util.assertion(!vrBaseMap.containsKey(op), "Node emitted out of order!"); vrBaseMap.put(op, vrbase); } } private void createVirtualRegisters(SDNode node, MachineInstr mi, MCInstrDesc tid, boolean isClone, boolean isCloned, TObjectIntHashMap<SDValue> vrBaseMap) { Util.assertion(node.getMachineOpcode() != TargetOpcode.IMPLICIT_DEF); for (int i = 0; i < tid.getNumDefs(); i++) { int vrbase = 0; MCRegisterClass rc = tid.opInfo[i].getRegisterClass(tri); if (tid.opInfo[i].isOptionalDef()) { int numResult = countResults(node); vrbase = ((RegisterSDNode) node.getOperand(i - numResult).getNode()).getReg(); Util.assertion(isPhysicalRegister(vrbase)); mi.addOperand(MachineOperand.createReg(vrbase, true, false)); } if (vrbase == 0 && !isClone && !isCloned) { for (SDUse u : node.getUseList()) { SDNode user = u.getUser(); if (user.getOpcode() == ISD.CopyToReg && user.getOperand(2).getNode().equals(node) && user.getOperand(2).getResNo() == i) { int reg = ((RegisterSDNode) user.getOperand(1).getNode()).getReg(); if (isVirtualRegister(reg)) { MCRegisterClass regRC = mri.getRegClass(reg); if (regRC.equals(rc)) { vrbase = reg; mi.addOperand(MachineOperand.createReg(reg, true, false)); break; } } } } if (vrbase == 0) { Util.assertion(rc != null); vrbase = mri.createVirtualRegister(rc); mi.addOperand(MachineOperand.createReg(vrbase, true, false)); } SDValue op = new SDValue(node, i); if (isClone) vrBaseMap.remove(op); Util.assertion(!vrBaseMap.containsKey(op)); vrBaseMap.put(op, vrbase); } } } private void buildSchedUnits() { for (SDNode node : dag.allNodes) node.setNodeID(-1); boolean unitLatencies = forceUnitLatencies(); // Walk through the DAG in the order of depth-first, so that we can avoid traverse // those "dead" nodes (pruned from DAG by instruction selector). Stack<SDNode> worklist = new Stack<>(); worklist.push(dag.getRoot().getNode()); HashSet<SDNode> visited = new HashSet<>(); visited.add(dag.getRoot().getNode()); while (!worklist.isEmpty()) { SDNode curNode = worklist.pop(); // Add all operands to the worklist unless they've already been added. for (int i = 0, e = curNode.getNumOperands(); i < e; i++) { SDNode child = curNode.getOperand(i).getNode(); if (!visited.contains(child)) { visited.add(child); worklist.push(child); } } if (isPassiveNode(curNode) || curNode.getNodeID() != -1) continue; SUnit nodeSUnit = newSUnit(curNode); SDNode n = curNode; while (n.getNumOperands() != 0 && n.getOperand(n.getNumOperands() - 1).getValueType().getSimpleVT() .simpleVT == MVT.Glue) { n = n.getOperand(n.getNumOperands() - 1).getNode(); Util.assertion(n.getNodeID() == -1); n.setNodeID(nodeSUnit.nodeNum); } n = curNode; while (n.getValueType(n.getNumValues() - 1).getSimpleVT().simpleVT == MVT.Glue) { SDValue flagVal = new SDValue(n, n.getNumValues() - 1); boolean hasFlagUse = false; for (SDUse u : n.useList) { if (flagVal.isOperandOf(u.getUser())) { hasFlagUse = true; Util.assertion(n.getNodeID() == -1); n.setNodeID(nodeSUnit.nodeNum); n = u.getUser(); break; } } if (!hasFlagUse) break; } nodeSUnit.setNode(n); Util.assertion(n.getNodeID() == -1); n.setNodeID(nodeSUnit.nodeNum); if (unitLatencies) nodeSUnit.latency = 1; else computeLatency(nodeSUnit); } } private void addSchedEdges() { TargetSubtarget ts = tm.getSubtarget(); boolean unitLatencies = forceUnitLatencies(); for (int i = 0, e = sunits.size(); i < e; i++) { SUnit su = sunits.get(i); SDNode node = su.getNode(); if (node.isMachineOpecode()) { int opc = node.getMachineOpcode(); MCInstrDesc tid = tii.get(opc); for (int j = 0; j < tid.getNumOperands(); j++) { if (tid.getOperandConstraint(j, TIED_TO) != -1) { su.isTwoAddress = true; break; } } if (tid.isCommutable()) su.isCommutable = true; } for (SDNode n = su.getNode(); n != null; n = n.getFlaggedNode()) { if (n.isMachineOpecode() && tii.get(n.getMachineOpcode()).getImplicitDefs() != null) { su.hasPhysRegClobbers = true; int numUsed = countResults(n); while (numUsed != 0 && !n.hasAnyUseOfValue(numUsed - 1)) --numUsed; if (numUsed > tii.get(n.getMachineOpcode()).getNumDefs()) su.hasPhysRegDefs = true; } for (int j = 0, sz = n.getNumOperands(); j < sz; j++) { SDNode opN = n.getOperand(j).getNode(); if (isPassiveNode(opN)) continue; SUnit opSU = sunits.get(opN.getNodeID()); Util.assertion(opSU != null); if (Objects.equals(opSU, su)) continue; if (n.getOperand(j).getValueType().equals(new EVT(MVT.Glue))) continue; EVT opVT = n.getOperand(j).getValueType(); Util.assertion(!opVT.equals(new EVT(MVT.Glue))); boolean isChain = opVT.equals(new EVT(MVT.Other)); int[] res = checkForPhysRegDependency(opN, n, i, tri, tii); int physReg = res[0]; int cost = res[1]; Util.assertion(physReg == 0 || !isChain); if (cost >= 0) physReg = 0; SDep dep = new SDep(opSU, isChain ? Order : Data, opSU.latency, physReg, false, false, false); if (!isChain && !unitLatencies) { computeOperandLatency(opSU, su, dep); ts.adjustSchedDependency(opSU, su, dep); } su.addPred(dep); } } } } private static int[] checkForPhysRegDependency(SDNode def, SDNode user, int op, TargetRegisterInfo tri, TargetInstrInfo tii) { // returned array layouts as follows. // 0 -- phyReg // 1 -- cost. int[] res = {0, 1}; if (op != 2 || user.getOpcode() != ISD.CopyToReg) return res; int reg = ((RegisterSDNode) user.getOperand(1).getNode()).getReg(); if (isVirtualRegister(reg)) return res; int resNo = user.getOperand(2).getResNo(); if (def.isMachineOpecode()) { MCInstrDesc tid = tii.get(def.getMachineOpcode()); if (resNo >= tid.getNumDefs() && tid.implicitDefs != null && tid.implicitDefs[resNo - tid.getNumDefs()] == reg) { res[0] = reg; MCRegisterClass rc = tri.getPhysicalRegisterRegClass(reg, def.getValueType(resNo)); res[1] = rc.getCopyCost(); } } return res; } @Override public void addCustomGraphFeatures(ScheduleDAGDotTraits graphWriter) { if (dag != null) { graphWriter.emitSimpleNode(null, "plaintext=circle", "GraphRoot"); SDNode n = dag.getRoot().getNode(); if (n != null && n.getNodeID() != -1) { graphWriter.emitEdge(null, -1, sunits.get(n.getNodeID()), -1, "color=blue,style=dashed"); } } } }
/* * Copyright 2013-2017 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.real_logic.sbe.ir; import org.agrona.CloseHelper; import org.agrona.LangUtil; import org.agrona.MutableDirectBuffer; import org.agrona.concurrent.UnsafeBuffer; import uk.co.real_logic.sbe.PrimitiveType; import uk.co.real_logic.sbe.ir.generated.FrameCodecEncoder; import uk.co.real_logic.sbe.ir.generated.TokenCodecEncoder; import org.agrona.Verify; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Paths; import java.util.List; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.WRITE; import static uk.co.real_logic.sbe.ir.IrUtil.*; import static uk.co.real_logic.sbe.ir.generated.FrameCodecEncoder.namespaceNameCharacterEncoding; import static uk.co.real_logic.sbe.ir.generated.FrameCodecEncoder.packageNameCharacterEncoding; import static uk.co.real_logic.sbe.ir.generated.FrameCodecEncoder.semanticVersionCharacterEncoding; import static uk.co.real_logic.sbe.ir.generated.TokenCodecEncoder.*; public class IrEncoder implements AutoCloseable { private static final int CAPACITY = 4096; private final FileChannel channel; private final ByteBuffer resultBuffer; private final ByteBuffer buffer; private final MutableDirectBuffer directBuffer; private final Ir ir; private final FrameCodecEncoder frameEncoder = new FrameCodecEncoder(); private final TokenCodecEncoder tokenEncoder = new TokenCodecEncoder(); private final byte[] valArray = new byte[CAPACITY]; private final UnsafeBuffer valBuffer = new UnsafeBuffer(valArray); private int totalLength = 0; public IrEncoder(final String fileName, final Ir ir) { try { channel = FileChannel.open(Paths.get(fileName), READ, WRITE, CREATE); resultBuffer = null; buffer = ByteBuffer.allocateDirect(CAPACITY); directBuffer = new UnsafeBuffer(buffer); this.ir = ir; } catch (final IOException ex) { throw new RuntimeException(ex); } } public IrEncoder(final ByteBuffer buffer, final Ir ir) { channel = null; resultBuffer = buffer; this.buffer = ByteBuffer.allocateDirect(CAPACITY); directBuffer = new UnsafeBuffer(this.buffer); this.ir = ir; } public void close() { CloseHelper.quietClose(channel); } public int encode() { Verify.notNull(ir, "ir"); write(buffer, encodeFrame()); encodeTokenList(ir.headerStructure().tokens()); ir.messages().forEach(this::encodeTokenList); return totalLength; } private void encodeTokenList(final List<Token> tokenList) { for (final Token token : tokenList) { write(buffer, encodeToken(token)); } } private void write(final ByteBuffer buffer, final int length) { buffer.position(0); buffer.limit(length); if (channel != null) { try { channel.write(buffer); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } } else if (resultBuffer != null) { resultBuffer.put(buffer); } totalLength += length; } private int encodeFrame() { frameEncoder .wrap(directBuffer, 0) .irId(ir.id()) .irVersion(0) .schemaVersion(ir.version()); try { final byte[] packageBytes = ir.packageName().getBytes(packageNameCharacterEncoding()); frameEncoder.putPackageName(packageBytes, 0, packageBytes.length); final byte[] namespaceBytes = getBytes(ir.namespaceName(), namespaceNameCharacterEncoding()); frameEncoder.putNamespaceName(namespaceBytes, 0, namespaceBytes.length); final byte[] semanticVersionBytes = getBytes(ir.semanticVersion(), semanticVersionCharacterEncoding()); frameEncoder.putSemanticVersion(semanticVersionBytes, 0, semanticVersionBytes.length); } catch (final UnsupportedEncodingException ex) { LangUtil.rethrowUnchecked(ex); } return frameEncoder.encodedLength(); } private int encodeToken(final Token token) { final Encoding encoding = token.encoding(); final PrimitiveType type = encoding.primitiveType(); tokenEncoder .wrap(directBuffer, 0) .tokenOffset(token.offset()) .tokenSize(token.encodedLength()) .fieldId(token.id()) .tokenVersion(token.version()) .componentTokenCount(token.componentTokenCount()) .signal(mapSignal(token.signal())) .primitiveType(mapPrimitiveType(type)) .byteOrder(mapByteOrder(encoding.byteOrder())) .presence(mapPresence(encoding.presence())); try { final byte[] nameBytes = token.name().getBytes(TokenCodecEncoder.nameCharacterEncoding()); tokenEncoder.putName(nameBytes, 0, nameBytes.length); tokenEncoder.putConstValue(valArray, 0, put(valBuffer, encoding.constValue(), type)); tokenEncoder.putMinValue(valArray, 0, put(valBuffer, encoding.minValue(), type)); tokenEncoder.putMaxValue(valArray, 0, put(valBuffer, encoding.maxValue(), type)); tokenEncoder.putNullValue(valArray, 0, put(valBuffer, encoding.nullValue(), type)); final byte[] charEncodingBytes = getBytes( encoding.characterEncoding(), characterEncodingCharacterEncoding()); tokenEncoder.putCharacterEncoding(charEncodingBytes, 0, charEncodingBytes.length); final byte[] epochBytes = getBytes(encoding.epoch(), epochCharacterEncoding()); tokenEncoder.putEpoch(epochBytes, 0, epochBytes.length); final byte[] timeUnitBytes = getBytes(encoding.timeUnit(), timeUnitCharacterEncoding()); tokenEncoder.putTimeUnit(timeUnitBytes, 0, timeUnitBytes.length); final byte[] semanticTypeBytes = getBytes(encoding.semanticType(), semanticTypeCharacterEncoding()); tokenEncoder.putSemanticType(semanticTypeBytes, 0, semanticTypeBytes.length); final byte[] descriptionBytes = getBytes(token.description(), descriptionCharacterEncoding()); tokenEncoder.putDescription(descriptionBytes, 0, descriptionBytes.length); final byte[] referencedNameBytes = getBytes(token.referencedName(), referencedNameCharacterEncoding()); tokenEncoder.putReferencedName(referencedNameBytes, 0, referencedNameBytes.length); } catch (final UnsupportedEncodingException ex) { LangUtil.rethrowUnchecked(ex); } return tokenEncoder.encodedLength(); } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.airavata.model.appcatalog.computeresource; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Cloud Job Submission * * */ @SuppressWarnings("all") public class CloundJobSubmission implements org.apache.thrift.TBase<CloundJobSubmission, CloundJobSubmission._Fields>, java.io.Serializable, Cloneable, Comparable<CloundJobSubmission> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CloundJobSubmission"); private static final org.apache.thrift.protocol.TField JOB_SUBMISSION_INTERFACE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("jobSubmissionInterfaceId", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField SECURITY_PROTOCOL_FIELD_DESC = new org.apache.thrift.protocol.TField("securityProtocol", org.apache.thrift.protocol.TType.I32, (short)2); private static final org.apache.thrift.protocol.TField NODE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("nodeId", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField EXECUTABLE_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("executableType", org.apache.thrift.protocol.TType.STRING, (short)4); private static final org.apache.thrift.protocol.TField PROVIDER_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("providerName", org.apache.thrift.protocol.TType.I32, (short)5); private static final org.apache.thrift.protocol.TField USER_ACCOUNT_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("userAccountName", org.apache.thrift.protocol.TType.STRING, (short)6); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new CloundJobSubmissionStandardSchemeFactory()); schemes.put(TupleScheme.class, new CloundJobSubmissionTupleSchemeFactory()); } private String jobSubmissionInterfaceId; // required private SecurityProtocol securityProtocol; // required private String nodeId; // required private String executableType; // required private ProviderName providerName; // required private String userAccountName; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ @SuppressWarnings("all") public enum _Fields implements org.apache.thrift.TFieldIdEnum { JOB_SUBMISSION_INTERFACE_ID((short)1, "jobSubmissionInterfaceId"), /** * * @see SecurityProtocol */ SECURITY_PROTOCOL((short)2, "securityProtocol"), NODE_ID((short)3, "nodeId"), EXECUTABLE_TYPE((short)4, "executableType"), /** * * @see ProviderName */ PROVIDER_NAME((short)5, "providerName"), USER_ACCOUNT_NAME((short)6, "userAccountName"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // JOB_SUBMISSION_INTERFACE_ID return JOB_SUBMISSION_INTERFACE_ID; case 2: // SECURITY_PROTOCOL return SECURITY_PROTOCOL; case 3: // NODE_ID return NODE_ID; case 4: // EXECUTABLE_TYPE return EXECUTABLE_TYPE; case 5: // PROVIDER_NAME return PROVIDER_NAME; case 6: // USER_ACCOUNT_NAME return USER_ACCOUNT_NAME; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.JOB_SUBMISSION_INTERFACE_ID, new org.apache.thrift.meta_data.FieldMetaData("jobSubmissionInterfaceId", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.SECURITY_PROTOCOL, new org.apache.thrift.meta_data.FieldMetaData("securityProtocol", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, SecurityProtocol.class))); tmpMap.put(_Fields.NODE_ID, new org.apache.thrift.meta_data.FieldMetaData("nodeId", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.EXECUTABLE_TYPE, new org.apache.thrift.meta_data.FieldMetaData("executableType", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PROVIDER_NAME, new org.apache.thrift.meta_data.FieldMetaData("providerName", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, ProviderName.class))); tmpMap.put(_Fields.USER_ACCOUNT_NAME, new org.apache.thrift.meta_data.FieldMetaData("userAccountName", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CloundJobSubmission.class, metaDataMap); } public CloundJobSubmission() { this.jobSubmissionInterfaceId = "DO_NOT_SET_AT_CLIENTS"; } public CloundJobSubmission( String jobSubmissionInterfaceId, SecurityProtocol securityProtocol, String nodeId, String executableType, ProviderName providerName, String userAccountName) { this(); this.jobSubmissionInterfaceId = jobSubmissionInterfaceId; this.securityProtocol = securityProtocol; this.nodeId = nodeId; this.executableType = executableType; this.providerName = providerName; this.userAccountName = userAccountName; } /** * Performs a deep copy on <i>other</i>. */ public CloundJobSubmission(CloundJobSubmission other) { if (other.isSetJobSubmissionInterfaceId()) { this.jobSubmissionInterfaceId = other.jobSubmissionInterfaceId; } if (other.isSetSecurityProtocol()) { this.securityProtocol = other.securityProtocol; } if (other.isSetNodeId()) { this.nodeId = other.nodeId; } if (other.isSetExecutableType()) { this.executableType = other.executableType; } if (other.isSetProviderName()) { this.providerName = other.providerName; } if (other.isSetUserAccountName()) { this.userAccountName = other.userAccountName; } } public CloundJobSubmission deepCopy() { return new CloundJobSubmission(this); } @Override public void clear() { this.jobSubmissionInterfaceId = "DO_NOT_SET_AT_CLIENTS"; this.securityProtocol = null; this.nodeId = null; this.executableType = null; this.providerName = null; this.userAccountName = null; } public String getJobSubmissionInterfaceId() { return this.jobSubmissionInterfaceId; } public void setJobSubmissionInterfaceId(String jobSubmissionInterfaceId) { this.jobSubmissionInterfaceId = jobSubmissionInterfaceId; } public void unsetJobSubmissionInterfaceId() { this.jobSubmissionInterfaceId = null; } /** Returns true if field jobSubmissionInterfaceId is set (has been assigned a value) and false otherwise */ public boolean isSetJobSubmissionInterfaceId() { return this.jobSubmissionInterfaceId != null; } public void setJobSubmissionInterfaceIdIsSet(boolean value) { if (!value) { this.jobSubmissionInterfaceId = null; } } /** * * @see SecurityProtocol */ public SecurityProtocol getSecurityProtocol() { return this.securityProtocol; } /** * * @see SecurityProtocol */ public void setSecurityProtocol(SecurityProtocol securityProtocol) { this.securityProtocol = securityProtocol; } public void unsetSecurityProtocol() { this.securityProtocol = null; } /** Returns true if field securityProtocol is set (has been assigned a value) and false otherwise */ public boolean isSetSecurityProtocol() { return this.securityProtocol != null; } public void setSecurityProtocolIsSet(boolean value) { if (!value) { this.securityProtocol = null; } } public String getNodeId() { return this.nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public void unsetNodeId() { this.nodeId = null; } /** Returns true if field nodeId is set (has been assigned a value) and false otherwise */ public boolean isSetNodeId() { return this.nodeId != null; } public void setNodeIdIsSet(boolean value) { if (!value) { this.nodeId = null; } } public String getExecutableType() { return this.executableType; } public void setExecutableType(String executableType) { this.executableType = executableType; } public void unsetExecutableType() { this.executableType = null; } /** Returns true if field executableType is set (has been assigned a value) and false otherwise */ public boolean isSetExecutableType() { return this.executableType != null; } public void setExecutableTypeIsSet(boolean value) { if (!value) { this.executableType = null; } } /** * * @see ProviderName */ public ProviderName getProviderName() { return this.providerName; } /** * * @see ProviderName */ public void setProviderName(ProviderName providerName) { this.providerName = providerName; } public void unsetProviderName() { this.providerName = null; } /** Returns true if field providerName is set (has been assigned a value) and false otherwise */ public boolean isSetProviderName() { return this.providerName != null; } public void setProviderNameIsSet(boolean value) { if (!value) { this.providerName = null; } } public String getUserAccountName() { return this.userAccountName; } public void setUserAccountName(String userAccountName) { this.userAccountName = userAccountName; } public void unsetUserAccountName() { this.userAccountName = null; } /** Returns true if field userAccountName is set (has been assigned a value) and false otherwise */ public boolean isSetUserAccountName() { return this.userAccountName != null; } public void setUserAccountNameIsSet(boolean value) { if (!value) { this.userAccountName = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case JOB_SUBMISSION_INTERFACE_ID: if (value == null) { unsetJobSubmissionInterfaceId(); } else { setJobSubmissionInterfaceId((String)value); } break; case SECURITY_PROTOCOL: if (value == null) { unsetSecurityProtocol(); } else { setSecurityProtocol((SecurityProtocol)value); } break; case NODE_ID: if (value == null) { unsetNodeId(); } else { setNodeId((String)value); } break; case EXECUTABLE_TYPE: if (value == null) { unsetExecutableType(); } else { setExecutableType((String)value); } break; case PROVIDER_NAME: if (value == null) { unsetProviderName(); } else { setProviderName((ProviderName)value); } break; case USER_ACCOUNT_NAME: if (value == null) { unsetUserAccountName(); } else { setUserAccountName((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case JOB_SUBMISSION_INTERFACE_ID: return getJobSubmissionInterfaceId(); case SECURITY_PROTOCOL: return getSecurityProtocol(); case NODE_ID: return getNodeId(); case EXECUTABLE_TYPE: return getExecutableType(); case PROVIDER_NAME: return getProviderName(); case USER_ACCOUNT_NAME: return getUserAccountName(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case JOB_SUBMISSION_INTERFACE_ID: return isSetJobSubmissionInterfaceId(); case SECURITY_PROTOCOL: return isSetSecurityProtocol(); case NODE_ID: return isSetNodeId(); case EXECUTABLE_TYPE: return isSetExecutableType(); case PROVIDER_NAME: return isSetProviderName(); case USER_ACCOUNT_NAME: return isSetUserAccountName(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof CloundJobSubmission) return this.equals((CloundJobSubmission)that); return false; } public boolean equals(CloundJobSubmission that) { if (that == null) return false; boolean this_present_jobSubmissionInterfaceId = true && this.isSetJobSubmissionInterfaceId(); boolean that_present_jobSubmissionInterfaceId = true && that.isSetJobSubmissionInterfaceId(); if (this_present_jobSubmissionInterfaceId || that_present_jobSubmissionInterfaceId) { if (!(this_present_jobSubmissionInterfaceId && that_present_jobSubmissionInterfaceId)) return false; if (!this.jobSubmissionInterfaceId.equals(that.jobSubmissionInterfaceId)) return false; } boolean this_present_securityProtocol = true && this.isSetSecurityProtocol(); boolean that_present_securityProtocol = true && that.isSetSecurityProtocol(); if (this_present_securityProtocol || that_present_securityProtocol) { if (!(this_present_securityProtocol && that_present_securityProtocol)) return false; if (!this.securityProtocol.equals(that.securityProtocol)) return false; } boolean this_present_nodeId = true && this.isSetNodeId(); boolean that_present_nodeId = true && that.isSetNodeId(); if (this_present_nodeId || that_present_nodeId) { if (!(this_present_nodeId && that_present_nodeId)) return false; if (!this.nodeId.equals(that.nodeId)) return false; } boolean this_present_executableType = true && this.isSetExecutableType(); boolean that_present_executableType = true && that.isSetExecutableType(); if (this_present_executableType || that_present_executableType) { if (!(this_present_executableType && that_present_executableType)) return false; if (!this.executableType.equals(that.executableType)) return false; } boolean this_present_providerName = true && this.isSetProviderName(); boolean that_present_providerName = true && that.isSetProviderName(); if (this_present_providerName || that_present_providerName) { if (!(this_present_providerName && that_present_providerName)) return false; if (!this.providerName.equals(that.providerName)) return false; } boolean this_present_userAccountName = true && this.isSetUserAccountName(); boolean that_present_userAccountName = true && that.isSetUserAccountName(); if (this_present_userAccountName || that_present_userAccountName) { if (!(this_present_userAccountName && that_present_userAccountName)) return false; if (!this.userAccountName.equals(that.userAccountName)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(CloundJobSubmission other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetJobSubmissionInterfaceId()).compareTo(other.isSetJobSubmissionInterfaceId()); if (lastComparison != 0) { return lastComparison; } if (isSetJobSubmissionInterfaceId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.jobSubmissionInterfaceId, other.jobSubmissionInterfaceId); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetSecurityProtocol()).compareTo(other.isSetSecurityProtocol()); if (lastComparison != 0) { return lastComparison; } if (isSetSecurityProtocol()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.securityProtocol, other.securityProtocol); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetNodeId()).compareTo(other.isSetNodeId()); if (lastComparison != 0) { return lastComparison; } if (isSetNodeId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.nodeId, other.nodeId); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetExecutableType()).compareTo(other.isSetExecutableType()); if (lastComparison != 0) { return lastComparison; } if (isSetExecutableType()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.executableType, other.executableType); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetProviderName()).compareTo(other.isSetProviderName()); if (lastComparison != 0) { return lastComparison; } if (isSetProviderName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.providerName, other.providerName); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetUserAccountName()).compareTo(other.isSetUserAccountName()); if (lastComparison != 0) { return lastComparison; } if (isSetUserAccountName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.userAccountName, other.userAccountName); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("CloundJobSubmission("); boolean first = true; sb.append("jobSubmissionInterfaceId:"); if (this.jobSubmissionInterfaceId == null) { sb.append("null"); } else { sb.append(this.jobSubmissionInterfaceId); } first = false; if (!first) sb.append(", "); sb.append("securityProtocol:"); if (this.securityProtocol == null) { sb.append("null"); } else { sb.append(this.securityProtocol); } first = false; if (!first) sb.append(", "); sb.append("nodeId:"); if (this.nodeId == null) { sb.append("null"); } else { sb.append(this.nodeId); } first = false; if (!first) sb.append(", "); sb.append("executableType:"); if (this.executableType == null) { sb.append("null"); } else { sb.append(this.executableType); } first = false; if (!first) sb.append(", "); sb.append("providerName:"); if (this.providerName == null) { sb.append("null"); } else { sb.append(this.providerName); } first = false; if (!first) sb.append(", "); sb.append("userAccountName:"); if (this.userAccountName == null) { sb.append("null"); } else { sb.append(this.userAccountName); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (!isSetJobSubmissionInterfaceId()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'jobSubmissionInterfaceId' is unset! Struct:" + toString()); } if (!isSetSecurityProtocol()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'securityProtocol' is unset! Struct:" + toString()); } if (!isSetNodeId()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'nodeId' is unset! Struct:" + toString()); } if (!isSetExecutableType()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'executableType' is unset! Struct:" + toString()); } if (!isSetProviderName()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'providerName' is unset! Struct:" + toString()); } if (!isSetUserAccountName()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'userAccountName' is unset! Struct:" + toString()); } // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class CloundJobSubmissionStandardSchemeFactory implements SchemeFactory { public CloundJobSubmissionStandardScheme getScheme() { return new CloundJobSubmissionStandardScheme(); } } private static class CloundJobSubmissionStandardScheme extends StandardScheme<CloundJobSubmission> { public void read(org.apache.thrift.protocol.TProtocol iprot, CloundJobSubmission struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // JOB_SUBMISSION_INTERFACE_ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.jobSubmissionInterfaceId = iprot.readString(); struct.setJobSubmissionInterfaceIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // SECURITY_PROTOCOL if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.securityProtocol = SecurityProtocol.findByValue(iprot.readI32()); struct.setSecurityProtocolIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // NODE_ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.nodeId = iprot.readString(); struct.setNodeIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // EXECUTABLE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.executableType = iprot.readString(); struct.setExecutableTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // PROVIDER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.providerName = ProviderName.findByValue(iprot.readI32()); struct.setProviderNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // USER_ACCOUNT_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.userAccountName = iprot.readString(); struct.setUserAccountNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, CloundJobSubmission struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.jobSubmissionInterfaceId != null) { oprot.writeFieldBegin(JOB_SUBMISSION_INTERFACE_ID_FIELD_DESC); oprot.writeString(struct.jobSubmissionInterfaceId); oprot.writeFieldEnd(); } if (struct.securityProtocol != null) { oprot.writeFieldBegin(SECURITY_PROTOCOL_FIELD_DESC); oprot.writeI32(struct.securityProtocol.getValue()); oprot.writeFieldEnd(); } if (struct.nodeId != null) { oprot.writeFieldBegin(NODE_ID_FIELD_DESC); oprot.writeString(struct.nodeId); oprot.writeFieldEnd(); } if (struct.executableType != null) { oprot.writeFieldBegin(EXECUTABLE_TYPE_FIELD_DESC); oprot.writeString(struct.executableType); oprot.writeFieldEnd(); } if (struct.providerName != null) { oprot.writeFieldBegin(PROVIDER_NAME_FIELD_DESC); oprot.writeI32(struct.providerName.getValue()); oprot.writeFieldEnd(); } if (struct.userAccountName != null) { oprot.writeFieldBegin(USER_ACCOUNT_NAME_FIELD_DESC); oprot.writeString(struct.userAccountName); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class CloundJobSubmissionTupleSchemeFactory implements SchemeFactory { public CloundJobSubmissionTupleScheme getScheme() { return new CloundJobSubmissionTupleScheme(); } } private static class CloundJobSubmissionTupleScheme extends TupleScheme<CloundJobSubmission> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, CloundJobSubmission struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; oprot.writeString(struct.jobSubmissionInterfaceId); oprot.writeI32(struct.securityProtocol.getValue()); oprot.writeString(struct.nodeId); oprot.writeString(struct.executableType); oprot.writeI32(struct.providerName.getValue()); oprot.writeString(struct.userAccountName); } @Override public void read(org.apache.thrift.protocol.TProtocol prot, CloundJobSubmission struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; struct.jobSubmissionInterfaceId = iprot.readString(); struct.setJobSubmissionInterfaceIdIsSet(true); struct.securityProtocol = SecurityProtocol.findByValue(iprot.readI32()); struct.setSecurityProtocolIsSet(true); struct.nodeId = iprot.readString(); struct.setNodeIdIsSet(true); struct.executableType = iprot.readString(); struct.setExecutableTypeIsSet(true); struct.providerName = ProviderName.findByValue(iprot.readI32()); struct.setProviderNameIsSet(true); struct.userAccountName = iprot.readString(); struct.setUserAccountNameIsSet(true); } } }
/* * Copyright (c) 2009-2018 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.input; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.input.controls.*; import com.jme3.math.FastMath; import com.jme3.math.Vector3f; import com.jme3.renderer.Camera; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Spatial; import com.jme3.scene.control.Control; import com.jme3.util.clone.Cloner; import com.jme3.util.clone.JmeCloneable; import java.io.IOException; /** * A camera that follows a spatial and can turn around it by dragging the mouse * @author nehon */ public class ChaseCamera implements ActionListener, AnalogListener, Control, JmeCloneable { protected Spatial target = null; protected float minVerticalRotation = 0.00f; protected float maxVerticalRotation = FastMath.PI / 2; protected float minDistance = 1.0f; protected float maxDistance = 40.0f; protected float distance = 20; protected float rotationSpeed = 1.0f; protected float rotation = 0; protected float trailingRotationInertia = 0.05f; protected float zoomSensitivity = 2f; protected float rotationSensitivity = 5f; protected float chasingSensitivity = 5f; protected float trailingSensitivity = 0.5f; protected float vRotation = FastMath.PI / 6; protected boolean smoothMotion = false; protected boolean trailingEnabled = true; protected float rotationLerpFactor = 0; protected float trailingLerpFactor = 0; protected boolean rotating = false; protected boolean vRotating = false; protected float targetRotation = rotation; protected InputManager inputManager; protected Vector3f initialUpVec; protected float targetVRotation = vRotation; protected float vRotationLerpFactor = 0; protected float targetDistance = distance; protected float distanceLerpFactor = 0; protected boolean zooming = false; protected boolean trailing = false; protected boolean chasing = false; protected boolean veryCloseRotation = true; protected boolean canRotate; protected float offsetDistance = 0.002f; protected Vector3f prevPos; protected boolean targetMoves = false; protected boolean enabled = true; protected Camera cam = null; protected final Vector3f targetDir = new Vector3f(); protected float previousTargetRotation; protected final Vector3f pos = new Vector3f(); protected Vector3f targetLocation = new Vector3f(0, 0, 0); protected boolean dragToRotate = true; protected Vector3f lookAtOffset = new Vector3f(0, 0, 0); protected boolean leftClickRotate = true; protected boolean rightClickRotate = true; protected Vector3f temp = new Vector3f(0, 0, 0); protected boolean invertYaxis = false; protected boolean invertXaxis = false; /** * @deprecated use {@link CameraInput#CHASECAM_DOWN} */ @Deprecated public final static String ChaseCamDown = "ChaseCamDown"; /** * @deprecated use {@link CameraInput#CHASECAM_UP} */ @Deprecated public final static String ChaseCamUp = "ChaseCamUp"; /** * @deprecated use {@link CameraInput#CHASECAM_ZOOMIN} */ @Deprecated public final static String ChaseCamZoomIn = "ChaseCamZoomIn"; /** * @deprecated use {@link CameraInput#CHASECAM_ZOOMOUT} */ @Deprecated public final static String ChaseCamZoomOut = "ChaseCamZoomOut"; /** * @deprecated use {@link CameraInput#CHASECAM_MOVELEFT} */ @Deprecated public final static String ChaseCamMoveLeft = "ChaseCamMoveLeft"; /** * @deprecated use {@link CameraInput#CHASECAM_MOVERIGHT} */ @Deprecated public final static String ChaseCamMoveRight = "ChaseCamMoveRight"; /** * @deprecated use {@link CameraInput#CHASECAM_TOGGLEROTATE} */ @Deprecated public final static String ChaseCamToggleRotate = "ChaseCamToggleRotate"; protected boolean zoomin; protected boolean hideCursorOnRotate = true; /** * Constructs the chase camera * @param cam the application camera * @param target the spatial to follow */ public ChaseCamera(Camera cam, final Spatial target) { this(cam); target.addControl(this); } /** * Constructs the chase camera * if you use this constructor you have to attach the cam later to a spatial * doing spatial.addControl(chaseCamera); * @param cam the application camera */ public ChaseCamera(Camera cam) { this.cam = cam; initialUpVec = cam.getUp().clone(); } /** * Constructs the chase camera, and registers inputs * if you use this constructor you have to attach the cam later to a spatial * doing spatial.addControl(chaseCamera); * @param cam the application camera * @param inputManager the inputManager of the application to register inputs */ public ChaseCamera(Camera cam, InputManager inputManager) { this(cam); registerWithInput(inputManager); } /** * Constructs the chase camera, and registers inputs * @param cam the application camera * @param target the spatial to follow * @param inputManager the inputManager of the application to register inputs */ public ChaseCamera(Camera cam, final Spatial target, InputManager inputManager) { this(cam, target); registerWithInput(inputManager); } public void onAction(String name, boolean keyPressed, float tpf) { if (dragToRotate) { if (name.equals(CameraInput.CHASECAM_TOGGLEROTATE) && enabled) { if (keyPressed) { canRotate = true; if (hideCursorOnRotate) { inputManager.setCursorVisible(false); } } else { canRotate = false; if (hideCursorOnRotate) { inputManager.setCursorVisible(true); } } } } } public void onAnalog(String name, float value, float tpf) { if (name.equals(CameraInput.CHASECAM_MOVELEFT)) { rotateCamera(-value); } else if (name.equals(CameraInput.CHASECAM_MOVERIGHT)) { rotateCamera(value); } else if (name.equals(CameraInput.CHASECAM_UP)) { vRotateCamera(value); } else if (name.equals(CameraInput.CHASECAM_DOWN)) { vRotateCamera(-value); } else if (name.equals(CameraInput.CHASECAM_ZOOMIN)) { zoomCamera(-value); if (zoomin == false) { distanceLerpFactor = 0; } zoomin = true; } else if (name.equals(CameraInput.CHASECAM_ZOOMOUT)) { zoomCamera(+value); if (zoomin == true) { distanceLerpFactor = 0; } zoomin = false; } } /** * Registers inputs with the input manager * @param inputManager */ public final void registerWithInput(InputManager inputManager) { String[] inputs = {CameraInput.CHASECAM_TOGGLEROTATE, CameraInput.CHASECAM_DOWN, CameraInput.CHASECAM_UP, CameraInput.CHASECAM_MOVELEFT, CameraInput.CHASECAM_MOVERIGHT, CameraInput.CHASECAM_ZOOMIN, CameraInput.CHASECAM_ZOOMOUT}; this.inputManager = inputManager; if (!invertYaxis) { inputManager.addMapping(CameraInput.CHASECAM_DOWN, new MouseAxisTrigger(MouseInput.AXIS_Y, true)); inputManager.addMapping(CameraInput.CHASECAM_UP, new MouseAxisTrigger(MouseInput.AXIS_Y, false)); } else { inputManager.addMapping(CameraInput.CHASECAM_DOWN, new MouseAxisTrigger(MouseInput.AXIS_Y, false)); inputManager.addMapping(CameraInput.CHASECAM_UP, new MouseAxisTrigger(MouseInput.AXIS_Y, true)); } inputManager.addMapping(CameraInput.CHASECAM_ZOOMIN, new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false)); inputManager.addMapping(CameraInput.CHASECAM_ZOOMOUT, new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true)); if (!invertXaxis) { inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, new MouseAxisTrigger(MouseInput.AXIS_X, true)); inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, new MouseAxisTrigger(MouseInput.AXIS_X, false)); } else { inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, new MouseAxisTrigger(MouseInput.AXIS_X, false)); inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, new MouseAxisTrigger(MouseInput.AXIS_X, true)); } inputManager.addMapping(CameraInput.CHASECAM_TOGGLEROTATE, new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); inputManager.addMapping(CameraInput.CHASECAM_TOGGLEROTATE, new MouseButtonTrigger(MouseInput.BUTTON_RIGHT)); inputManager.addListener(this, inputs); } /** * Cleans up the input mappings from the input manager. * Undoes the work of registerWithInput(). * @param inputManager InputManager from which to cleanup mappings. */ public void cleanupWithInput(InputManager mgr){ mgr.deleteMapping(CameraInput.CHASECAM_TOGGLEROTATE); mgr.deleteMapping(CameraInput.CHASECAM_DOWN); mgr.deleteMapping(CameraInput.CHASECAM_UP); mgr.deleteMapping(CameraInput.CHASECAM_MOVELEFT); mgr.deleteMapping(CameraInput.CHASECAM_MOVERIGHT); mgr.deleteMapping(CameraInput.CHASECAM_ZOOMIN); mgr.deleteMapping(CameraInput.CHASECAM_ZOOMOUT); mgr.removeListener(this); } /** * Sets custom triggers for toggling the rotation of the cam * default are * new MouseButtonTrigger(MouseInput.BUTTON_LEFT) left mouse button * new MouseButtonTrigger(MouseInput.BUTTON_RIGHT) right mouse button * @param triggers */ public void setToggleRotationTrigger(Trigger... triggers) { inputManager.deleteMapping(CameraInput.CHASECAM_TOGGLEROTATE); inputManager.addMapping(CameraInput.CHASECAM_TOGGLEROTATE, triggers); inputManager.addListener(this, CameraInput.CHASECAM_TOGGLEROTATE); } /** * Sets custom triggers for zooming in the cam * default is * new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true) mouse wheel up * @param triggers */ public void setZoomInTrigger(Trigger... triggers) { inputManager.deleteMapping(CameraInput.CHASECAM_ZOOMIN); inputManager.addMapping(CameraInput.CHASECAM_ZOOMIN, triggers); inputManager.addListener(this, CameraInput.CHASECAM_ZOOMIN); } /** * Sets custom triggers for zooming out the cam * default is * new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false) mouse wheel down * @param triggers */ public void setZoomOutTrigger(Trigger... triggers) { inputManager.deleteMapping(CameraInput.CHASECAM_ZOOMOUT); inputManager.addMapping(CameraInput.CHASECAM_ZOOMOUT, triggers); inputManager.addListener(this, CameraInput.CHASECAM_ZOOMOUT); } protected void computePosition() { float hDistance = (distance) * FastMath.sin((FastMath.PI / 2) - vRotation); pos.set(hDistance * FastMath.cos(rotation), (distance) * FastMath.sin(vRotation), hDistance * FastMath.sin(rotation)); pos.addLocal(target.getWorldTranslation()); } //rotate the camera around the target on the horizontal plane protected void rotateCamera(float value) { if (!canRotate || !enabled) { return; } rotating = true; targetRotation += value * rotationSpeed; } //move the camera toward or away the target protected void zoomCamera(float value) { if (!enabled) { return; } zooming = true; targetDistance += value * zoomSensitivity; if (targetDistance > maxDistance) { targetDistance = maxDistance; } if (targetDistance < minDistance) { targetDistance = minDistance; } if (veryCloseRotation) { if ((targetVRotation < minVerticalRotation) && (targetDistance > (minDistance + 1.0f))) { targetVRotation = minVerticalRotation; } } } //rotate the camera around the target on the vertical plane protected void vRotateCamera(float value) { if (!canRotate || !enabled) { return; } vRotating = true; float lastGoodRot = targetVRotation; targetVRotation += value * rotationSpeed; if (targetVRotation > maxVerticalRotation) { targetVRotation = lastGoodRot; } if (veryCloseRotation) { if ((targetVRotation < minVerticalRotation) && (targetDistance > (minDistance + 1.0f))) { targetVRotation = minVerticalRotation; } else if (targetVRotation < -FastMath.DEG_TO_RAD * 90) { targetVRotation = lastGoodRot; } } else { if ((targetVRotation < minVerticalRotation)) { targetVRotation = lastGoodRot; } } } /** * Updates the camera, should only be called internally */ protected void updateCamera(float tpf) { if (enabled) { targetLocation.set(target.getWorldTranslation()).addLocal(lookAtOffset); if (smoothMotion) { //computation of target direction targetDir.set(targetLocation).subtractLocal(prevPos); float dist = targetDir.length(); //Low pass filtering on the target postition to avoid shaking when physics are enabled. if (offsetDistance < dist) { //target moves, start chasing. chasing = true; //target moves, start trailing if it has to. if (trailingEnabled) { trailing = true; } //target moves... targetMoves = true; } else { //if target was moving, we compute a slight offset in rotation to avoid a rought stop of the cam //We do not if the player is rotationg the cam if (targetMoves && !canRotate) { if (targetRotation - rotation > trailingRotationInertia) { targetRotation = rotation + trailingRotationInertia; } else if (targetRotation - rotation < -trailingRotationInertia) { targetRotation = rotation - trailingRotationInertia; } } //Target stops targetMoves = false; } //the user is rotating the cam by dragging the mouse if (canRotate) { //reset the trailing lerp factor trailingLerpFactor = 0; //stop trailing user has the control trailing = false; } if (trailingEnabled && trailing) { if (targetMoves) { //computation if the inverted direction of the target Vector3f a = targetDir.negate().normalizeLocal(); //the x unit vector Vector3f b = Vector3f.UNIT_X; //2d is good enough a.y = 0; //computation of the rotation angle between the x axis and the trail if (targetDir.z > 0) { targetRotation = FastMath.TWO_PI - FastMath.acos(a.dot(b)); } else { targetRotation = FastMath.acos(a.dot(b)); } if (targetRotation - rotation > FastMath.PI || targetRotation - rotation < -FastMath.PI) { targetRotation -= FastMath.TWO_PI; } //if there is an important change in the direction while trailing reset of the lerp factor to avoid jumpy movements if (targetRotation != previousTargetRotation && FastMath.abs(targetRotation - previousTargetRotation) > FastMath.PI / 8) { trailingLerpFactor = 0; } previousTargetRotation = targetRotation; } //computing lerp factor trailingLerpFactor = Math.min(trailingLerpFactor + tpf * tpf * trailingSensitivity, 1); //computing rotation by linear interpolation rotation = FastMath.interpolateLinear(trailingLerpFactor, rotation, targetRotation); //if the rotation is near the target rotation we're good, that's over if (targetRotation + 0.01f >= rotation && targetRotation - 0.01f <= rotation) { trailing = false; trailingLerpFactor = 0; } } //linear interpolation of the distance while chasing if (chasing) { distance = temp.set(targetLocation).subtractLocal(cam.getLocation()).length(); distanceLerpFactor = Math.min(distanceLerpFactor + (tpf * tpf * chasingSensitivity * 0.05f), 1); distance = FastMath.interpolateLinear(distanceLerpFactor, distance, targetDistance); if (targetDistance + 0.01f >= distance && targetDistance - 0.01f <= distance) { distanceLerpFactor = 0; chasing = false; } } //linear interpolation of the distance while zooming if (zooming) { distanceLerpFactor = Math.min(distanceLerpFactor + (tpf * tpf * zoomSensitivity), 1); distance = FastMath.interpolateLinear(distanceLerpFactor, distance, targetDistance); if (targetDistance + 0.1f >= distance && targetDistance - 0.1f <= distance) { zooming = false; distanceLerpFactor = 0; } } //linear interpolation of the rotation while rotating horizontally if (rotating) { rotationLerpFactor = Math.min(rotationLerpFactor + tpf * tpf * rotationSensitivity, 1); rotation = FastMath.interpolateLinear(rotationLerpFactor, rotation, targetRotation); if (targetRotation + 0.01f >= rotation && targetRotation - 0.01f <= rotation) { rotating = false; rotationLerpFactor = 0; } } //linear interpolation of the rotation while rotating vertically if (vRotating) { vRotationLerpFactor = Math.min(vRotationLerpFactor + tpf * tpf * rotationSensitivity, 1); vRotation = FastMath.interpolateLinear(vRotationLerpFactor, vRotation, targetVRotation); if (targetVRotation + 0.01f >= vRotation && targetVRotation - 0.01f <= vRotation) { vRotating = false; vRotationLerpFactor = 0; } } //computing the position computePosition(); //setting the position at last cam.setLocation(pos.addLocal(lookAtOffset)); } else { //easy no smooth motion vRotation = targetVRotation; rotation = targetRotation; distance = targetDistance; computePosition(); cam.setLocation(pos.addLocal(lookAtOffset)); } //keeping track on the previous position of the target prevPos.set(targetLocation); //the cam looks at the target cam.lookAt(targetLocation, initialUpVec); } } /** * Return the enabled/disabled state of the camera * @return true if the camera is enabled */ public boolean isEnabled() { return enabled; } /** * Enable or disable the camera * @param enabled true to enable */ public void setEnabled(boolean enabled) { this.enabled = enabled; if (!enabled) { canRotate = false; // reset this flag in-case it was on before } } /** * Returns the max zoom distance of the camera (default is 40) * @return maxDistance */ public float getMaxDistance() { return maxDistance; } /** * Sets the max zoom distance of the camera (default is 40) * @param maxDistance */ public void setMaxDistance(float maxDistance) { this.maxDistance = maxDistance; if (maxDistance < distance) { zoomCamera(maxDistance - distance); } } /** * Returns the min zoom distance of the camera (default is 1) * @return minDistance */ public float getMinDistance() { return minDistance; } /** * Sets the min zoom distance of the camera (default is 1) */ public void setMinDistance(float minDistance) { this.minDistance = minDistance; if (minDistance > distance) { zoomCamera(distance - minDistance); } } /** * clone this camera for a spatial * * @param spatial * @return */ @Deprecated @Override public Control cloneForSpatial(Spatial spatial) { throw new UnsupportedOperationException(); } @Override public Object jmeClone() { ChaseCamera cc = new ChaseCamera(cam, inputManager); cc.target = target; cc.setMaxDistance(getMaxDistance()); cc.setMinDistance(getMinDistance()); return cc; } @Override public void cloneFields( Cloner cloner, Object original ) { this.target = cloner.clone(target); computePosition(); prevPos = new Vector3f(target.getWorldTranslation()); cam.setLocation(pos); } /** * Sets the spacial for the camera control, should only be used internally * @param spatial */ public void setSpatial(Spatial spatial) { target = spatial; if (spatial == null) { return; } computePosition(); prevPos = new Vector3f(target.getWorldTranslation()); cam.setLocation(pos); } /** * update the camera control, should only be used internally * @param tpf */ public void update(float tpf) { updateCamera(tpf); } /** * renders the camera control, should only be used internally * @param rm * @param vp */ public void render(RenderManager rm, ViewPort vp) { //nothing to render } /** * Write the camera * @param ex the exporter * @throws IOException */ public void write(JmeExporter ex) throws IOException { throw new UnsupportedOperationException("remove ChaseCamera before saving"); } /** * Read the camera * @param im * @throws IOException */ public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); maxDistance = ic.readFloat("maxDistance", 40); minDistance = ic.readFloat("minDistance", 1); } /** * @return The maximal vertical rotation angle in radian of the camera around the target */ public float getMaxVerticalRotation() { return maxVerticalRotation; } /** * Sets the maximal vertical rotation angle in radian of the camera around the target. Default is Pi/2; * @param maxVerticalRotation */ public void setMaxVerticalRotation(float maxVerticalRotation) { this.maxVerticalRotation = maxVerticalRotation; } /** * * @return The minimal vertical rotation angle in radian of the camera around the target */ public float getMinVerticalRotation() { return minVerticalRotation; } /** * Sets the minimal vertical rotation angle in radian of the camera around the target default is 0; * @param minHeight */ public void setMinVerticalRotation(float minHeight) { this.minVerticalRotation = minHeight; } /** * @return True is smooth motion is enabled for this chase camera */ public boolean isSmoothMotion() { return smoothMotion; } /** * Enables smooth motion for this chase camera * @param smoothMotion */ public void setSmoothMotion(boolean smoothMotion) { this.smoothMotion = smoothMotion; } /** * returns the chasing sensitivity * @return */ public float getChasingSensitivity() { return chasingSensitivity; } /** * * Sets the chasing sensitivity, the lower the value the slower the camera will follow the target when it moves * default is 5 * Only has an effect if smoothMotion is set to true and trailing is enabled * @param chasingSensitivity */ public void setChasingSensitivity(float chasingSensitivity) { this.chasingSensitivity = chasingSensitivity; } /** * Returns the rotation sensitivity * @return */ public float getRotationSensitivity() { return rotationSensitivity; } /** * Sets the rotation sensitivity, the lower the value the slower the camera will rotates around the target when dragging with the mouse * default is 5, values over 5 should have no effect. * If you want a significant slow down try values below 1. * Only has an effect if smoothMotion is set to true * @param rotationSensitivity */ public void setRotationSensitivity(float rotationSensitivity) { this.rotationSensitivity = rotationSensitivity; } /** * returns true if the trailing is enabled * @return */ public boolean isTrailingEnabled() { return trailingEnabled; } /** * Enable the camera trailing : The camera smoothly go in the targets trail when it moves. * Only has an effect if smoothMotion is set to true * @param trailingEnabled */ public void setTrailingEnabled(boolean trailingEnabled) { this.trailingEnabled = trailingEnabled; } /** * * returns the trailing rotation inertia * @return */ public float getTrailingRotationInertia() { return trailingRotationInertia; } /** * Sets the trailing rotation inertia : default is 0.1. This prevent the camera to roughtly stop when the target stops moving * before the camera reached the trail position. * Only has an effect if smoothMotion is set to true and trailing is enabled * @param trailingRotationInertia */ public void setTrailingRotationInertia(float trailingRotationInertia) { this.trailingRotationInertia = trailingRotationInertia; } /** * returns the trailing sensitivity * @return */ public float getTrailingSensitivity() { return trailingSensitivity; } /** * Only has an effect if smoothMotion is set to true and trailing is enabled * Sets the trailing sensitivity, the lower the value, the slower the camera will go in the target trail when it moves. * default is 0.5; * @param trailingSensitivity */ public void setTrailingSensitivity(float trailingSensitivity) { this.trailingSensitivity = trailingSensitivity; } /** * returns the zoom sensitivity * @return */ public float getZoomSensitivity() { return zoomSensitivity; } /** * Sets the zoom sensitivity, the lower the value, the slower the camera will zoom in and out. * default is 2. * @param zoomSensitivity */ public void setZoomSensitivity(float zoomSensitivity) { this.zoomSensitivity = zoomSensitivity; } /** * Returns the rotation speed when the mouse is moved. * * @return the rotation speed when the mouse is moved. */ public float getRotationSpeed() { return rotationSpeed; } /** * Sets the rotate amount when user moves his mouse, the lower the value, * the slower the camera will rotate. default is 1. * * @param rotationSpeed Rotation speed on mouse movement, default is 1. */ public void setRotationSpeed(float rotationSpeed) { this.rotationSpeed = rotationSpeed; } /** * Sets the default distance at start of application * @param defaultDistance */ public void setDefaultDistance(float defaultDistance) { distance = defaultDistance; targetDistance = distance; } /** * sets the default horizontal rotation in radian of the camera at start of the application * @param angleInRad */ public void setDefaultHorizontalRotation(float angleInRad) { rotation = angleInRad; targetRotation = angleInRad; } /** * sets the default vertical rotation in radian of the camera at start of the application * @param angleInRad */ public void setDefaultVerticalRotation(float angleInRad) { vRotation = angleInRad; targetVRotation = angleInRad; } /** * @return If drag to rotate feature is enabled. * * @see FlyByCamera#setDragToRotate(boolean) */ public boolean isDragToRotate() { return dragToRotate; } /** * @param dragToRotate When true, the user must hold the mouse button * and drag over the screen to rotate the camera, and the cursor is * visible until dragged. Otherwise, the cursor is invisible at all times * and holding the mouse button is not needed to rotate the camera. * This feature is disabled by default. */ public void setDragToRotate(boolean dragToRotate) { this.dragToRotate = dragToRotate; this.canRotate = !dragToRotate; inputManager.setCursorVisible(dragToRotate); } /** * @param rotateOnlyWhenClose When this flag is set to false the chase * camera will always rotate around its spatial independently of their * distance to one another. If set to true, the chase camera will only * be allowed to rotated below the "horizon" when the distance is smaller * than minDistance + 1.0f (when fully zoomed-in). */ public void setDownRotateOnCloseViewOnly(boolean rotateOnlyWhenClose) { veryCloseRotation = rotateOnlyWhenClose; } /** * @return True if rotation below the vertical plane of the spatial tied * to the camera is allowed only when zoomed in at minDistance + 1.0f. * False if vertical rotation is always allowed. */ public boolean getDownRotateOnCloseViewOnly() { return veryCloseRotation; } /** * return the current distance from the camera to the target * @return */ public float getDistanceToTarget() { return distance; } /** * returns the current horizontal rotation around the target in radians * @return */ public float getHorizontalRotation() { return rotation; } /** * returns the current vertical rotation around the target in radians. * @return */ public float getVerticalRotation() { return vRotation; } /** * returns the offset from the target's position where the camera looks at * @return */ public Vector3f getLookAtOffset() { return lookAtOffset; } /** * Sets the offset from the target's position where the camera looks at * @param lookAtOffset */ public void setLookAtOffset(Vector3f lookAtOffset) { this.lookAtOffset = lookAtOffset; } /** * Sets the up vector of the camera used for the lookAt on the target * @param up */ public void setUpVector(Vector3f up) { initialUpVec = up; } /** * Returns the up vector of the camera used for the lookAt on the target * @return */ public Vector3f getUpVector() { return initialUpVec; } public boolean isHideCursorOnRotate() { return hideCursorOnRotate; } public void setHideCursorOnRotate(boolean hideCursorOnRotate) { this.hideCursorOnRotate = hideCursorOnRotate; } /** * invert the vertical axis movement of the mouse * @param invertYaxis */ public void setInvertVerticalAxis(boolean invertYaxis) { this.invertYaxis = invertYaxis; inputManager.deleteMapping(CameraInput.CHASECAM_DOWN); inputManager.deleteMapping(CameraInput.CHASECAM_UP); if (!invertYaxis) { inputManager.addMapping(CameraInput.CHASECAM_DOWN, new MouseAxisTrigger(MouseInput.AXIS_Y, true)); inputManager.addMapping(CameraInput.CHASECAM_UP, new MouseAxisTrigger(MouseInput.AXIS_Y, false)); } else { inputManager.addMapping(CameraInput.CHASECAM_DOWN, new MouseAxisTrigger(MouseInput.AXIS_Y, false)); inputManager.addMapping(CameraInput.CHASECAM_UP, new MouseAxisTrigger(MouseInput.AXIS_Y, true)); } inputManager.addListener(this, CameraInput.CHASECAM_DOWN, CameraInput.CHASECAM_UP); } /** * invert the Horizontal axis movement of the mouse * @param invertXaxis */ public void setInvertHorizontalAxis(boolean invertXaxis) { this.invertXaxis = invertXaxis; inputManager.deleteMapping(CameraInput.CHASECAM_MOVELEFT); inputManager.deleteMapping(CameraInput.CHASECAM_MOVERIGHT); if (!invertXaxis) { inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, new MouseAxisTrigger(MouseInput.AXIS_X, true)); inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, new MouseAxisTrigger(MouseInput.AXIS_X, false)); } else { inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, new MouseAxisTrigger(MouseInput.AXIS_X, false)); inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, new MouseAxisTrigger(MouseInput.AXIS_X, true)); } inputManager.addListener(this, CameraInput.CHASECAM_MOVELEFT, CameraInput.CHASECAM_MOVERIGHT); } }
/* * $Id$ * This file is a part of the Arakhne Foundation Classes, http://www.arakhne.org/afc * * Copyright (c) 2000-2012 Stephane GALLAND. * Copyright (c) 2005-10, Multiagent Team, Laboratoire Systemes et Transports, * Universite de Technologie de Belfort-Montbeliard. * Copyright (c) 2013-2020 The original authors, and other 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.arakhne.afc.math.geometry.d2.afp; import java.util.NoSuchElementException; import org.eclipse.xtext.xbase.lib.Pure; import org.arakhne.afc.math.MathUtil; import org.arakhne.afc.math.geometry.CrossingComputationType; import org.arakhne.afc.math.geometry.GeomConstants; import org.arakhne.afc.math.geometry.PathWindingRule; import org.arakhne.afc.math.geometry.d2.Point2D; import org.arakhne.afc.math.geometry.d2.Transform2D; import org.arakhne.afc.math.geometry.d2.Vector2D; import org.arakhne.afc.vmutil.asserts.AssertMessages; /** Fonctional interface that represented a 2D circle on a plane. * * @param <ST> is the type of the general implementation. * @param <IT> is the type of the implementation of this shape. * @param <IE> is the type of the path elements. * @param <P> is the type of the points. * @param <V> is the type of the vectors. * @param <B> is the type of the bounding boxes. * @author $Author: sgalland$ * @author $Author: hjaffali$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 13.0 */ public interface Circle2afp< ST extends Shape2afp<?, ?, IE, P, V, B>, IT extends Circle2afp<?, ?, IE, P, V, B>, IE extends PathElement2afp, P extends Point2D<? super P, ? super V>, V extends Vector2D<? super V, ? super P>, B extends Rectangle2afp<?, ?, IE, P, V, B>> extends Ellipse2afp<ST, IT, IE, P, V, B> { /** * Replies if the given point is inside the given ellipse. * * @param px is the point to test. * @param py is the point to test. * @param cx is the center of the circle. * @param cy is the center of the circle. * @param radius is the radius of the circle. * @return <code>true</code> if the point is inside the circle; * <code>false</code> if not. */ @Pure static boolean containsCirclePoint(double cx, double cy, double radius, double px, double py) { assert radius >= 0 : AssertMessages.positiveOrZeroParameter(2); return Point2D.getDistanceSquaredPointPoint( px, py, cx, cy) <= (radius * radius); } /** Replies if a rectangle is inside in the circle. * * @param cx is the center of the circle. * @param cy is the center of the circle. * @param radius is the radius of the circle. * @param rxmin is the lowest corner of the rectangle. * @param rymin is the lowest corner of the rectangle. * @param rxmax is the uppest corner of the rectangle. * @param rymax is the uppest corner of the rectangle. * @return <code>true</code> if the given rectangle is inside the circle; * otherwise <code>false</code>. */ @Pure @SuppressWarnings("checkstyle:magicnumber") static boolean containsCircleRectangle(double cx, double cy, double radius, double rxmin, double rymin, double rxmax, double rymax) { assert radius >= 0 : AssertMessages.positiveOrZeroParameter(2); assert rxmin <= rxmax : AssertMessages.lowerEqualParameters(3, rxmin, 5, rxmax); assert rymin <= rymax : AssertMessages.lowerEqualParameters(4, rymin, 6, rymax); final double rcx = (rxmin + rxmax) / 2; final double rcy = (rymin + rymax) / 2; final double farX; if (cx <= rcx) { farX = rxmax; } else { farX = rxmin; } final double farY; if (cy <= rcy) { farY = rymax; } else { farY = rymin; } return containsCirclePoint(cx, cy, radius, farX, farY); } /** Replies if two circles are intersecting. * * @param x1 is the center of the first circle * @param y1 is the center of the first circle * @param radius1 is the radius of the first circle * @param x2 is the center of the second circle * @param y2 is the center of the second circle * @param radius2 is the radius of the second circle * @return <code>true</code> if the two shapes are intersecting; otherwise * <code>false</code> */ @Pure @SuppressWarnings("checkstyle:magicnumber") static boolean intersectsCircleCircle(double x1, double y1, double radius1, double x2, double y2, double radius2) { assert radius1 >= 0 : AssertMessages.positiveOrZeroParameter(2); assert radius1 >= 0 : AssertMessages.positiveOrZeroParameter(5); final double r = radius1 + radius2; return Point2D.getDistanceSquaredPointPoint(x1, y1, x2, y2) < (r * r); } /** Replies if a circle and a rectangle are intersecting. * * @param x1 is the center of the circle * @param y1 is the center of the circle * @param radius is the radius of the circle * @param x2 is the first corner of the rectangle. * @param y2 is the first corner of the rectangle. * @param x3 is the second corner of the rectangle. * @param y3 is the second corner of the rectangle. * @return <code>true</code> if the two shapes are intersecting; otherwise * <code>false</code> */ @Pure @SuppressWarnings("checkstyle:magicnumber") static boolean intersectsCircleRectangle(double x1, double y1, double radius, double x2, double y2, double x3, double y3) { assert radius >= 0 : AssertMessages.positiveOrZeroParameter(2); assert x2 <= x3 : AssertMessages.lowerEqualParameters(3, x2, 5, x3); assert y2 <= y3 : AssertMessages.lowerEqualParameters(4, y2, 6, y3); final double dx; if (x1 < x2) { dx = x2 - x1; } else if (x1 > x3) { dx = x1 - x3; } else { dx = 0; } final double dy; if (y1 < y2) { dy = y2 - y1; } else if (y1 > y3) { dy = y1 - y3; } else { dy = 0; } return (dx * dx + dy * dy) < (radius * radius); } /** Replies if a circle and a line are intersecting. * * @param x1 is the center of the circle * @param y1 is the center of the circle * @param radius is the radius of the circle * @param x2 is the first point of the line. * @param y2 is the first point of the line. * @param x3 is the second point of the line. * @param y3 is the second point of the line. * @return <code>true</code> if the two shapes are intersecting; otherwise * <code>false</code> */ @Pure static boolean intersectsCircleLine(double x1, double y1, double radius, double x2, double y2, double x3, double y3) { assert radius >= 0 : AssertMessages.positiveOrZeroParameter(2); final double d = Segment2afp.calculatesDistanceSquaredLinePoint(x2, y2, x3, y3, x1, y1); return d < (radius * radius); } /** Replies if a circle and a segment are intersecting. * * @param x1 is the center of the circle * @param y1 is the center of the circle * @param radius is the radius of the circle * @param x2 is the first point of the segment. * @param y2 is the first point of the segment. * @param x3 is the second point of the segment. * @param y3 is the second point of the segment. * @return <code>true</code> if the two shapes are intersecting; otherwise * <code>false</code> */ @Pure static boolean intersectsCircleSegment(double x1, double y1, double radius, double x2, double y2, double x3, double y3) { assert radius >= 0 : AssertMessages.positiveOrZeroParameter(2); final double d = Segment2afp.calculatesDistanceSquaredSegmentPoint(x2, y2, x3, y3, x1, y1); return d < (radius * radius); } @Pure @Override default boolean equalsToShape(IT shape) { if (shape == null) { return false; } if (shape == this) { return true; } return getX() == shape.getX() && getY() == shape.getY() && getRadius() == shape.getRadius(); } /** Replies the center X. * * @return the center x. */ @Pure double getX(); /** Replies the center y. * * @return the center y. */ @Pure double getY(); @Override @Pure default double getCenterX() { return getX(); } @Override @Pure default double getCenterY() { return getY(); } @Pure @Override default P getCenter() { return getGeomFactory().newPoint(getX(), getY()); } /** Change the center. * * @param center the center point. */ default void setCenter(Point2D<?, ?> center) { assert center != null : AssertMessages.notNullParameter(); set(center.getX(), center.getY(), getRadius()); } /** Change the center. * * @param x x coordinate of the center point. * @param y y coordinate of the center point. */ default void setCenter(double x, double y) { setX(x); setY(y); } /** Change the x coordinate of the center. * * @param x x coordinate of the center point. */ void setX(double x); /** Change the y coordinate of the center. * * @param y y coordinate of the center point. */ void setY(double y); /** Replies the radius. * * @return the radius. */ @Pure double getRadius(); /** Set the radius. * * @param radius is the radius. */ void setRadius(double radius); /** Change the frame of the circle. * * @param x x coordinate of the center point. * @param y y coordinate of the center point. * @param radius the radius. */ // Not a default implementation for ensuring atomic change. void set(double x, double y, double radius); /** Change the frame of the circle. * * @param center the center point. * @param radius the radius. */ default void set(Point2D<?, ?> center, double radius) { assert center != null : AssertMessages.notNullParameter(); set(center.getX(), center.getY(), radius); } @Override default void set(IT shape) { assert shape != null : AssertMessages.notNullParameter(); set(shape.getX(), shape.getY(), shape.getRadius()); } @Override default void clear() { set(0, 0, 0); } @Override default void toBoundingBox(B box) { assert box != null : AssertMessages.notNullParameter(); final double x = getX(); final double y = getY(); final double radius = getRadius(); box.setFromCorners( x - radius, y - radius, x + radius, y + radius); } @Override default boolean isEmpty() { return MathUtil.isEpsilonZero(getRadius()); } @Pure @Override default double getDistance(Point2D<?, ?> pt) { assert pt != null : AssertMessages.notNullParameter(); double distance = Point2D.getDistancePointPoint(getX(), getY(), pt.getX(), pt.getY()); distance = distance - getRadius(); return Math.max(0., distance); } @Pure @Override default double getDistanceSquared(Point2D<?, ?> pt) { assert pt != null : AssertMessages.notNullParameter(); final double x = getX(); final double y = getY(); final double radius = getRadius(); final double vx = pt.getX() - x; final double vy = pt.getY() - y; final double sqLength = vx * vx + vy * vy; final double sqRadius = radius * radius; if (sqLength <= sqRadius) { return 0; } return Math.max(0., sqLength - 2 * Math.sqrt(sqLength) * radius + sqRadius); } @Pure @Override default double getDistanceL1(Point2D<?, ?> pt) { assert pt != null : AssertMessages.notNullParameter(); final Point2D<?, ?> r = getClosestPointTo(pt); return r.getDistanceL1(pt); } @Pure @Override default double getDistanceLinf(Point2D<?, ?> pt) { assert pt != null : AssertMessages.notNullParameter(); final Point2D<?, ?> r = getClosestPointTo(pt); return r.getDistanceLinf(pt); } @Pure @Override default boolean contains(double x, double y) { return containsCirclePoint(getX(), getY(), getRadius(), x, y); } @Override default boolean contains(Rectangle2afp<?, ?, ?, ?, ?, ?> rectangle) { assert rectangle != null : AssertMessages.notNullParameter(); return containsCircleRectangle(getX(), getY(), getRadius(), rectangle.getMinX(), rectangle.getMinY(), rectangle.getMaxX(), rectangle.getMaxY()); } @Override default void translate(double dx, double dy) { setCenter(getX() + dx, getY() + dy); } @Pure @Override default boolean intersects(Rectangle2afp<?, ?, ?, ?, ?, ?> rectangle) { assert rectangle != null : AssertMessages.notNullParameter(); return intersectsCircleRectangle( getX(), getY(), getRadius(), rectangle.getMinX(), rectangle.getMinY(), rectangle.getMaxX(), rectangle.getMaxY()); } @Pure @Override default boolean intersects(Ellipse2afp<?, ?, ?, ?, ?, ?> ellipse) { assert ellipse != null : AssertMessages.notNullParameter(); return Ellipse2afp.intersectsEllipseCircle( ellipse.getMinX(), ellipse.getMinY(), ellipse.getWidth(), ellipse.getHeight(), getX(), getY(), getRadius()); } @Pure @Override default boolean intersects(Circle2afp<?, ?, ?, ?, ?, ?> circle) { assert circle != null : AssertMessages.notNullParameter(); return intersectsCircleCircle( getX(), getY(), getRadius(), circle.getX(), circle.getY(), circle.getRadius()); } @Pure @Override default boolean intersects(Triangle2afp<?, ?, ?, ?, ?, ?> triangle) { assert triangle != null : AssertMessages.notNullParameter(); return Triangle2afp.intersectsTriangleCircle( triangle.getX1(), triangle.getY1(), triangle.getX2(), triangle.getY2(), triangle.getX3(), triangle.getY3(), getX(), getY(), getRadius()); } @Pure @Override default boolean intersects(Segment2afp<?, ?, ?, ?, ?, ?> segment) { assert segment != null : AssertMessages.notNullParameter(); return intersectsCircleSegment( getX(), getY(), getRadius(), segment.getX1(), segment.getY1(), segment.getX2(), segment.getY2()); } @Pure @Override default boolean intersects(OrientedRectangle2afp<?, ?, ?, ?, ?, ?> orientedRectangle) { assert orientedRectangle != null : AssertMessages.notNullParameter(); return OrientedRectangle2afp.intersectsOrientedRectangleCircle( orientedRectangle.getCenterX(), orientedRectangle.getCenterY(), orientedRectangle.getFirstAxisX(), orientedRectangle.getFirstAxisY(), orientedRectangle.getFirstAxisExtent(), orientedRectangle.getSecondAxisExtent(), getX(), getY(), getRadius()); } @Pure @Override default boolean intersects(Parallelogram2afp<?, ?, ?, ?, ?, ?> parallelogram) { assert parallelogram != null : AssertMessages.notNullParameter(); return Parallelogram2afp.intersectsParallelogramCircle( parallelogram.getCenterX(), parallelogram.getCenterY(), parallelogram.getFirstAxisX(), parallelogram.getFirstAxisY(), parallelogram.getFirstAxisExtent(), parallelogram.getSecondAxisX(), parallelogram.getSecondAxisY(), parallelogram.getSecondAxisExtent(), getX(), getY(), getRadius()); } @Pure @Override default boolean intersects(PathIterator2afp<?> iterator) { assert iterator != null : AssertMessages.notNullParameter(); final int mask = iterator.getWindingRule() == PathWindingRule.NON_ZERO ? -1 : 2; final int crossings = Path2afp.calculatesCrossingsPathIteratorCircleShadow( 0, iterator, getX(), getY(), getRadius(), CrossingComputationType.SIMPLE_INTERSECTION_WHEN_NOT_POLYGON); return crossings == GeomConstants.SHAPE_INTERSECTS || (crossings & mask) != 0; } @Pure @Override default boolean intersects(RoundRectangle2afp<?, ?, ?, ?, ?, ?> roundRectangle) { assert roundRectangle != null : AssertMessages.notNullParameter(); return RoundRectangle2afp.intersectsRoundRectangleCircle( roundRectangle.getMinX(), roundRectangle.getMinY(), roundRectangle.getMaxX(), roundRectangle.getMaxY(), roundRectangle.getArcWidth(), roundRectangle.getArcHeight(), getX(), getY(), getRadius()); } @Pure @Override default boolean intersects(MultiShape2afp<?, ?, ?, ?, ?, ?, ?> multishape) { assert multishape != null : AssertMessages.notNullParameter(); return multishape.intersects(this); } @Pure @Override default P getClosestPointTo(Point2D<?, ?> pt) { assert pt != null : AssertMessages.notNullParameter(); final double x = getX(); final double y = getY(); final double radius = getRadius(); final double vx = pt.getX() - x; final double vy = pt.getY() - y; final double sqLength = vx * vx + vy * vy; if (sqLength <= (radius * radius)) { return getGeomFactory().convertToPoint(pt); } final double s = radius / Math.sqrt(sqLength); return getGeomFactory().newPoint(x + vx * s, y + vy * s); } @Pure @Override default P getClosestPointTo(Ellipse2afp<?, ?, ?, ?, ?, ?> ellipse) { assert ellipse != null : AssertMessages.notNullParameter(); final Point2D<?, ?> point = ellipse.getClosestPointTo(getCenter()); return getClosestPointTo(point); } @Pure @Override default P getClosestPointTo(Circle2afp<?, ?, ?, ?, ?, ?> circle) { assert circle != null : AssertMessages.notNullParameter(); final Point2D<?, ?> point = circle.getClosestPointTo(getCenter()); return getClosestPointTo(point); } @Pure @Override default P getClosestPointTo(Rectangle2afp<?, ?, ?, ?, ?, ?> rectangle) { assert rectangle != null : AssertMessages.notNullParameter(); final Point2D<?, ?> point = rectangle.getClosestPointTo(getCenter()); return getClosestPointTo(point); } @Pure @Override default P getClosestPointTo(Segment2afp<?, ?, ?, ?, ?, ?> segment) { assert segment != null : AssertMessages.notNullParameter(); final Point2D<?, ?> point = segment.getClosestPointTo(getCenter()); return getClosestPointTo(point); } @Pure @Override default P getClosestPointTo(Triangle2afp<?, ?, ?, ?, ?, ?> triangle) { assert triangle != null : AssertMessages.notNullParameter(); final Point2D<?, ?> point = triangle.getClosestPointTo(getCenter()); return getClosestPointTo(point); } @Pure @Override default P getClosestPointTo(Path2afp<?, ?, ?, ?, ?, ?> path) { assert path != null : AssertMessages.notNullParameter(); final Point2D<?, ?> point = path.getClosestPointTo(getCenter()); return getClosestPointTo(point); } @Pure @Override default P getClosestPointTo(OrientedRectangle2afp<?, ?, ?, ?, ?, ?> orientedRectangle) { assert orientedRectangle != null : AssertMessages.notNullParameter(); final Point2D<?, ?> point = orientedRectangle.getClosestPointTo(getCenter()); return getClosestPointTo(point); } @Pure @Override default P getClosestPointTo(Parallelogram2afp<?, ?, ?, ?, ?, ?> parallelogram) { assert parallelogram != null : AssertMessages.notNullParameter(); final Point2D<?, ?> point = parallelogram.getClosestPointTo(getCenter()); return getClosestPointTo(point); } @Pure @Override default P getClosestPointTo(RoundRectangle2afp<?, ?, ?, ?, ?, ?> roundRectangle) { assert roundRectangle != null : AssertMessages.notNullParameter(); final Point2D<?, ?> point = roundRectangle.getClosestPointTo(getCenter()); return getClosestPointTo(point); } @Pure @Override default P getClosestPointTo(MultiShape2afp<?, ?, ?, ?, ?, ?, ?> multishape) { assert multishape != null : AssertMessages.notNullParameter(); final Point2D<?, ?> point = multishape.getClosestPointTo(getCenter()); return getClosestPointTo(point); } @Pure @Override default P getFarthestPointTo(Point2D<?, ?> pt) { assert pt != null : AssertMessages.notNullParameter(); final double x = getX(); final double y = getY(); final double vx = x - pt.getX(); final double vy = y - pt.getY(); final double radius = getRadius(); final double sqLength = vx * vx + vy * vy; if (sqLength <= 0.) { return getGeomFactory().newPoint(radius, 0); } final double s = radius / Math.sqrt(sqLength); return getGeomFactory().newPoint(x + vx * s, y + vy * s); } @Pure @Override default PathIterator2afp<IE> getPathIterator(Transform2D transform) { if (transform == null || transform.isIdentity()) { return new CirclePathIterator<>(this); } return new TransformedCirclePathIterator<>(this, transform); } @Override @Pure default double getHorizontalRadius() { return getRadius(); } @Override @Pure default double getVerticalRadius() { return getRadius(); } /** {@inheritDoc} * * <p>The circle is set in order to be enclosed inside the given box. * It means that the center of the circle is the center of the box, and the * radius of the circle is the minimum of the demi-width and demi-height. */ @Override default void setFromCenter(double centerX, double centerY, double cornerX, double cornerY) { final double demiWidth = Math.abs(cornerX - centerX); final double demiHeight = Math.abs(cornerY - centerY); if (demiWidth <= demiHeight) { set(centerX, centerY, demiWidth); } else { set(centerX, centerY, demiHeight); } } /** {@inheritDoc} * * <p>The circle is set in order to be enclosed inside the given box. * It means that the center of the circle is the center of the box, and the * radius of the circle is the minimum of the demi-width and demi-height. */ @Override default void setFromCorners(double x1, double y1, double x2, double y2) { setFromCenter((x1 + x2) / 2., (y1 + y2) / 2., x2, y2); } @Override default double getMinX() { return getX() - getRadius(); } /** {@inheritDoc} * * <p>Assuming that the maximum X coordinate should not change, the center of * the circle is the point between the new minimum and the current maximum coordinates, * and the radius of the circle is set to the difference between the new minimum and * center coordinates. * * <p>If the new minimum is greater than the current maximum, the coordinates are automatically * swapped. */ @Override default void setMinX(double x) { final double cx = (x + getX() + getRadius()) / 2.; final double radius = Math.abs(cx - x); set(cx, getY(), radius); } @Override default double getMaxX() { return getX() + getRadius(); } /** {@inheritDoc} * * <p>Assuming that the minimum X coordinate should not change, the center of * the circle is the point between the new maximum and the current minimum coordinates, * and the radius of the circle is set to the difference between the new maximum and * center coordinates. * * <p>If the new maximum is lower than the current minimum, the coordinates are automatically * swapped. */ @Override default void setMaxX(double x) { final double cx = (x + getX() - getRadius()) / 2.; final double radius = Math.abs(cx - x); set(cx, getY(), radius); } @Override default double getMinY() { return getY() - getRadius(); } /** {@inheritDoc} * * <p>Assuming that the maximum Y coordinate should not change, the center of * the circle is the point between the new minimum and the current maximum coordinates, * and the radius of the circle is set to the difference between the new minimum and * center coordinates. * * <p>If the new minimum is greater than the current maximum, the coordinates are automatically * swapped. */ @Override default void setMinY(double y) { final double cy = (y + getY() + getRadius()) / 2.; final double radius = Math.abs(cy - y); set(getX(), cy, radius); } @Override default double getMaxY() { return getY() + getRadius(); } /** {@inheritDoc} * * <p>Assuming that the minimum Y coordinate should not change, the center of * the circle is the point between the new maximum and the current minimum coordinates, * and the radius of the circle is set to the difference between the new maximum and * center coordinates. * * <p>If the new maximum is lower than the current minimum, the coordinates are automatically * swapped. */ @Override default void setMaxY(double y) { final double cy = (y + getY() - getRadius()) / 2.; final double radius = Math.abs(cy - y); set(getX(), cy, radius); } /** Abstract iterator on the path elements of the circle. * * <h3>Discretization of the circle with Bezier</h3> * * <p>For n segments on the circle, the optimal distance to the control points, in the sense that the * middle of the curve lies on the circle itself, is (4/3)*tan(pi/(2n)). * * <p><img alt="" src="./doc-files/circlebezier.png" width="100%" > * * <p>In the case of a discretization with 4 bezier curves, the distance is is * (4/3)*tan(pi/8) = 4*(sqrt(2)-1)/3 = 0.552284749831. * * <p><img alt="" src="./doc-files/circlepathiterator.png" width="100%" > * * @param <T> the type of the path elements. * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ abstract class AbstractCirclePathIterator<T extends PathElement2afp> implements PathIterator2afp<T> { /** * Distance from a Bezier curve control point on the circle to the other control point. * * <p>4/3 tan (PI/(2*n)), where n is the number on points on the circle. */ public static final double CTRL_POINT_DISTANCE = 0.5522847498307933; /** * Contains the control points for a set of 4 cubic * bezier curves that approximate a circle of radius 1 * centered at (0, 0). */ public static final double[][] BEZIER_CONTROL_POINTS = { // First quarter: max x, max y. {1, CTRL_POINT_DISTANCE, CTRL_POINT_DISTANCE, 1, 0, 1}, // Second quarter: min x, max y. {-CTRL_POINT_DISTANCE, 1, -1, CTRL_POINT_DISTANCE, -1, 0}, // Third quarter: min x, min y. {-1, -CTRL_POINT_DISTANCE, -CTRL_POINT_DISTANCE, -1, 0, -1}, // Fourth quarter: max x, min y. {CTRL_POINT_DISTANCE, -1, 1, -CTRL_POINT_DISTANCE, 1, 0}, }; /** 4 segments + close. */ protected static final int NUMBER_ELEMENTS = 5; /** The iterated shape. */ protected final Circle2afp<?, ?, T, ?, ?, ?> circle; /** Constructor. * @param circle the circle. */ public AbstractCirclePathIterator(Circle2afp<?, ?, T, ?, ?, ?> circle) { assert circle != null : AssertMessages.notNullParameter(); this.circle = circle; } @Override public GeomFactory2afp<T, ?, ?, ?> getGeomFactory() { return this.circle.getGeomFactory(); } @Pure @Override public PathWindingRule getWindingRule() { return PathWindingRule.NON_ZERO; } @Pure @Override public boolean isPolyline() { return false; } @Override public boolean isCurved() { return true; } @Override public boolean isPolygon() { return true; } @Pure @Override public boolean isMultiParts() { return false; } } /** Iterator on the path elements of the circle. * * @param <T> the type of the path elements. * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ class CirclePathIterator<T extends PathElement2afp> extends AbstractCirclePathIterator<T> { private double x; private double y; private double radius; private int index; private double movex; private double movey; private double lastx; private double lasty; /** Constructor. * @param circle the circle to iterate on. */ public CirclePathIterator(Circle2afp<?, ?, T, ?, ?, ?> circle) { super(circle); if (circle.isEmpty()) { this.index = NUMBER_ELEMENTS; } else { this.radius = circle.getRadius(); this.x = circle.getX(); this.y = circle.getY(); this.index = -1; } } @Override public PathIterator2afp<T> restartIterations() { return new CirclePathIterator<>(this.circle); } @Pure @Override public boolean hasNext() { return this.index < NUMBER_ELEMENTS; } @Override @SuppressWarnings("checkstyle:magicnumber") public T next() { if (this.index >= NUMBER_ELEMENTS) { throw new NoSuchElementException(); } final int idx = this.index; ++this.index; if (idx < 0) { final double[] ctrls = BEZIER_CONTROL_POINTS[3]; this.movex = this.x + ctrls[4] * this.radius; this.movey = this.y + ctrls[5] * this.radius; this.lastx = this.movex; this.lasty = this.movey; return getGeomFactory().newMovePathElement( this.lastx, this.lasty); } if (idx < (NUMBER_ELEMENTS - 1)) { final double[] ctrls = BEZIER_CONTROL_POINTS[idx]; final double ppx = this.lastx; final double ppy = this.lasty; this.lastx = this.x + ctrls[4] * this.radius; this.lasty = this.y + ctrls[5] * this.radius; return getGeomFactory().newCurvePathElement( ppx, ppy, this.x + ctrls[0] * this.radius, this.y + ctrls[1] * this.radius, this.x + ctrls[2] * this.radius, this.y + ctrls[3] * this.radius, this.lastx, this.lasty); } return getGeomFactory().newClosePathElement( this.lastx, this.lasty, this.movex, this.movey); } } /** Iterator on the path elements of the circle. * * @param <T> the type of the path elements. * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ class TransformedCirclePathIterator<T extends PathElement2afp> extends AbstractCirclePathIterator<T> { private final Transform2D transform; private final Point2D<?, ?> tmpPoint; private double x; private double y; private double radius; private double movex; private double movey; private double lastx; private double lasty; private int index; /** Constructor. * @param circle the iterated circle. * @param transform the transformation to apply. */ public TransformedCirclePathIterator(Circle2afp<?, ?, T, ?, ?, ?> circle, Transform2D transform) { super(circle); assert transform != null : AssertMessages.notNullParameter(1); this.transform = transform; if (circle.isEmpty()) { this.index = NUMBER_ELEMENTS; this.tmpPoint = null; } else { this.tmpPoint = new InnerComputationPoint2afp(); this.radius = circle.getRadius(); this.x = circle.getX(); this.y = circle.getY(); this.index = -1; } } @Override public PathIterator2afp<T> restartIterations() { return new TransformedCirclePathIterator<>(this.circle, this.transform); } @Pure @Override public boolean hasNext() { return this.index < NUMBER_ELEMENTS; } @Override @SuppressWarnings("checkstyle:magicnumber") public T next() { if (this.index >= NUMBER_ELEMENTS) { throw new NoSuchElementException(); } final int idx = this.index; ++this.index; if (idx < 0) { final double[] ctrls = BEZIER_CONTROL_POINTS[3]; this.tmpPoint.set(this.x + ctrls[4] * this.radius, this.y + ctrls[5] * this.radius); this.transform.transform(this.tmpPoint); this.movex = this.tmpPoint.getX(); this.lastx = this.movex; this.movey = this.tmpPoint.getY(); this.lasty = this.movey; return getGeomFactory().newMovePathElement( this.lastx, this.lasty); } if (idx < (NUMBER_ELEMENTS - 1)) { final double[] ctrls = BEZIER_CONTROL_POINTS[idx]; final double ppx = this.lastx; final double ppy = this.lasty; this.tmpPoint.set(this.x + ctrls[0] * this.radius, this.y + ctrls[1] * this.radius); this.transform.transform(this.tmpPoint); final double ctrlX1 = this.tmpPoint.getX(); final double ctrlY1 = this.tmpPoint.getY(); this.tmpPoint.set(this.x + ctrls[2] * this.radius, this.y + ctrls[3] * this.radius); this.transform.transform(this.tmpPoint); final double ctrlX2 = this.tmpPoint.getX(); final double ctrlY2 = this.tmpPoint.getY(); this.tmpPoint.set(this.x + ctrls[4] * this.radius, this.y + ctrls[5] * this.radius); this.transform.transform(this.tmpPoint); this.lastx = this.tmpPoint.getX(); this.lasty = this.tmpPoint.getY(); return getGeomFactory().newCurvePathElement( ppx, ppy, ctrlX1, ctrlY1, ctrlX2, ctrlY2, this.lastx, this.lasty); } return getGeomFactory().newClosePathElement( this.lastx, this.lasty, this.movex, this.movey); } } }
/* * Copyright 2007 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.bc.document.validation.impl; import org.kuali.kfs.coa.businessobject.Organization; import org.kuali.kfs.coa.service.ChartService; import org.kuali.kfs.coa.service.OrganizationService; import org.kuali.kfs.module.bc.businessobject.BudgetConstructionOrganizationReports; import org.kuali.kfs.module.bc.document.service.BudgetConstructionOrganizationReportsService; import org.kuali.kfs.sys.KFSConstants; import org.kuali.kfs.sys.KFSKeyConstants; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.rice.core.api.parameter.ParameterEvaluatorService; import org.kuali.rice.kns.document.MaintenanceDocument; import org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase; import org.kuali.rice.krad.util.ObjectUtils; public class BudgetConstructionOrganizationReportsRule extends MaintenanceDocumentRuleBase { protected static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BudgetConstructionOrganizationReportsRule.class); protected OrganizationService orgService; protected ChartService chartService; protected BudgetConstructionOrganizationReportsService bcOrgReportsService; protected BudgetConstructionOrganizationReports oldBCOrgReports; protected BudgetConstructionOrganizationReports newBCOrgReports; public BudgetConstructionOrganizationReportsRule() { super(); // Pseudo-inject some services. // // This approach is being used to make it simpler to convert the Rule classes // to spring-managed with these services injected by Spring at some later date. // When this happens, just remove these calls to the setters with // SpringContext, and configure the bean defs for spring. this.setOrgService(SpringContext.getBean(OrganizationService.class)); this.setChartService(SpringContext.getBean(ChartService.class)); this.setBCOrgReportsService(SpringContext.getBean(BudgetConstructionOrganizationReportsService.class)); } /** * @see org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase#processCustomApproveDocumentBusinessRules(org.kuali.rice.kns.document.MaintenanceDocument) */ protected boolean processCustomApproveDocumentBusinessRules(MaintenanceDocument document) { boolean success = true; LOG.debug("Entering processCustomApproveDocumentBusinessRules()"); // check reporting hierarchy is valid success &= checkSimpleRules(document); return success; } /** * @see org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase#processCustomRouteDocumentBusinessRules(org.kuali.rice.kns.document.MaintenanceDocument) */ protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) { boolean success = true; LOG.debug("Entering processCustomRouteDocumentBusinessRules()"); // check reporting hierarchy is valid success &= checkSimpleRules(document); return success; } /** * @see org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase#processCustomSaveDocumentBusinessRules(org.kuali.rice.kns.document.MaintenanceDocument) */ protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument document) { LOG.debug("Entering processCustomSaveDocumentBusinessRules()"); // check reporting hierarchy is valid checkSimpleRules(document); return true; } protected boolean checkSimpleRules(MaintenanceDocument document) { boolean success = true; String lastReportsToChartOfAccountsCode; String lastReportsToOrganizationCode; boolean continueSearch; BudgetConstructionOrganizationReports tempBCOrgReports; Organization tempOrg; Integer loopCount; Integer maxLoopCount = 40; boolean orgMustReportToSelf = false; tempOrg = null; // Get the Org business object so that we can check the org type if (ObjectUtils.isNotNull(newBCOrgReports.getChartOfAccountsCode()) && ObjectUtils.isNotNull(newBCOrgReports.getOrganizationCode())) { tempOrg = orgService.getByPrimaryId(newBCOrgReports.getChartOfAccountsCode(), newBCOrgReports.getOrganizationCode()); // Check the Org Type of the Org business object to see if it is the root (reports to self) if (ObjectUtils.isNotNull(tempOrg)) { if (/*REFACTORME*/SpringContext.getBean(ParameterEvaluatorService.class).getParameterEvaluator(Organization.class, KFSConstants.ChartApcParms.ORG_MUST_REPORT_TO_SELF_ORG_TYPES, tempOrg.getOrganizationTypeCode()).evaluationSucceeds()) { orgMustReportToSelf = true; } } } // Reports To Chart/Org should not be same as this Chart/Org // However, allow special case where organization type is listed in the business rules if (ObjectUtils.isNotNull(newBCOrgReports.getReportsToChartOfAccountsCode()) && ObjectUtils.isNotNull(newBCOrgReports.getReportsToOrganizationCode()) && ObjectUtils.isNotNull(newBCOrgReports.getChartOfAccountsCode()) && ObjectUtils.isNotNull(newBCOrgReports.getOrganizationCode())) { if (!orgMustReportToSelf) { if ((newBCOrgReports.getReportsToChartOfAccountsCode().equals(newBCOrgReports.getChartOfAccountsCode())) && (newBCOrgReports.getReportsToOrganizationCode().equals(newBCOrgReports.getOrganizationCode()))) { putFieldError("reportsToOrganizationCode", KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_CANNOT_BE_SAME_ORG); success = false; } else { // Don't allow a circular reference on Reports to Chart/Org // terminate the search when a top-level org is found lastReportsToChartOfAccountsCode = newBCOrgReports.getReportsToChartOfAccountsCode(); lastReportsToOrganizationCode = newBCOrgReports.getReportsToOrganizationCode(); continueSearch = true; loopCount = 0; do { tempBCOrgReports = bcOrgReportsService.getByPrimaryId(lastReportsToChartOfAccountsCode, lastReportsToOrganizationCode); loopCount++; if (ObjectUtils.isNull(tempBCOrgReports)) { continueSearch = false; // if a null is returned on the first iteration, then the reports-to org does not exist // fail the validation if (loopCount == 1) { putFieldError("reportsToOrganizationCode", KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_MUST_EXIST); success = false; } } else { { // LOG.info("Found Org = " + lastReportsToChartOfAccountsCode + "/" + // lastReportsToOrganizationCode); lastReportsToChartOfAccountsCode = tempBCOrgReports.getReportsToChartOfAccountsCode(); lastReportsToOrganizationCode = tempBCOrgReports.getReportsToOrganizationCode(); if ((tempBCOrgReports.getReportsToChartOfAccountsCode().equals(newBCOrgReports.getChartOfAccountsCode())) && (tempBCOrgReports.getReportsToOrganizationCode().equals(newBCOrgReports.getOrganizationCode()))) { putFieldError("reportsToOrganizationCode", KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_CANNOT_BE_CIRCULAR_REF_TO_SAME_ORG); success = false; continueSearch = false; } } } if (loopCount > maxLoopCount) { continueSearch = false; } // stop the search if we reach an org that reports to itself if (continueSearch && (tempBCOrgReports.getReportsToChartOfAccountsCode().equals(tempBCOrgReports.getReportsToChartOfAccountsCode())) && (tempBCOrgReports.getReportsToOrganizationCode().equals(tempBCOrgReports.getOrganizationCode()))) continueSearch = false; } while (continueSearch == true); } // end else (checking for circular ref) } else { // org must report to self (university level organization) if (!(newBCOrgReports.getReportsToChartOfAccountsCode().equals(newBCOrgReports.getChartOfAccountsCode()) && newBCOrgReports.getReportsToOrganizationCode().equals(newBCOrgReports.getOrganizationCode()))) { putFieldError("reportsToOrganizationCode", KFSKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_MUST_BE_SAME_ORG); success = false; } } } return success; } /** * This method sets the convenience objects like newAccount and oldAccount, so you have short and easy handles to the new and * old objects contained in the maintenance document. It also calls the BusinessObjectBase.refresh(), which will attempt to load * all sub-objects from the DB by their primary keys, if available. * * @param document - the maintenanceDocument being evaluated */ public void setupConvenienceObjects() { // setup oldAccount convenience objects, make sure all possible sub-objects are populated oldBCOrgReports = (BudgetConstructionOrganizationReports) super.getOldBo(); // setup newAccount convenience objects, make sure all possible sub-objects are populated newBCOrgReports = (BudgetConstructionOrganizationReports) super.getNewBo(); } /** * Sets the orgService attribute value. * * @param orgService The orgService to set. */ public void setOrgService(OrganizationService orgService) { this.orgService = orgService; } /** * Sets the chartService attribute value. * * @param chartService The orgService to set. */ public void setChartService(ChartService chartService) { this.chartService = chartService; } /** * Sets the bcOrgReportsService attribute value. * * @param bcOrgReportsService The bcOrgReportsService to set. */ public void setBCOrgReportsService(BudgetConstructionOrganizationReportsService bcOrgReportsService) { this.bcOrgReportsService = bcOrgReportsService; } }
package xyz.grand.grandeur; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.OptionalPendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import xyz.grand.grandeur.adapter.UsersChatAdapter; public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener { public static ProgressDialog mProgressDialog; private FirebaseAuth mAuth; private DatabaseReference userDatabase; CoordinatorLayout cl_login; ProgressBar progressBar; AutoCompleteTextView inputEmail; EditText inputPassword; Button btnLogin, btnLoginGoogle, btnSignup, btnResetPassword; Toast toast; View toastView; public static String loginEmail, loginPwd; private static String loginPassword; private static final String TAG = "SignInActivity"; private static final int RC_SIGN_IN = 9001; private GoogleApiClient mGoogleApiClient; // private TextView mStatusTextView; private static FirebaseDatabase firebaseDatabase; public static FirebaseDatabase getDatabase() { if (firebaseDatabase == null) { firebaseDatabase = FirebaseDatabase.getInstance(); firebaseDatabase.setPersistenceEnabled(true); } return firebaseDatabase; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Get Firebase auth instance mAuth = FirebaseAuth.getInstance(); // [START configure_signin] // Configure sign-in to request the user's ID, email address, and basic // profile. ID and basic profile are included in DEFAULT_SIGN_IN. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); // [END configure_signin] // [START build_client] // Build a GoogleApiClient with access to the Google Sign-In API and the // options specified by gso. mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); // [END build_client] if (mAuth.getCurrentUser() != null) { startActivity(new Intent(LoginActivity.this, MainActivity.class)); finish(); } // set the view now setContentView(R.layout.activity_login); cl_login = (CoordinatorLayout) findViewById(R.id.activity_login); progressBar = (ProgressBar) findViewById(R.id.progressBar); inputEmail = (AutoCompleteTextView) findViewById(R.id.email); inputPassword = (EditText) findViewById(R.id.password); btnLogin = (Button) findViewById(R.id.btn_login); btnLoginGoogle = (Button) findViewById(R.id.btn_login_with_google); btnSignup = (Button) findViewById(R.id.btn_sign_up); btnResetPassword = (Button) findViewById(R.id.btn_reset_password); // [START customize_button] // Set the dimensions of the sign-in button. // btnLoginGoogle.setSize(SignInButton.SIZE_STANDARD); // [END customize_button] //Get Firebase auth instance mAuth = FirebaseAuth.getInstance(); btnSignup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LoginActivity.this, SignupActivity.class)); } }); btnResetPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class)); } }); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginEmail = inputEmail.getText().toString(); loginPassword = inputPassword.getText().toString(); if (TextUtils.isEmpty(loginEmail)) { inputEmail.setError(getString(R.string.empty_email)); return; } if (!(android.util.Patterns.EMAIL_ADDRESS.matcher(loginEmail).matches())) { inputEmail.setError("Incorrect email format"); return; } if (TextUtils.isEmpty(loginPassword)) { inputPassword.setError(getString(R.string.empty_password)); return; } if (loginPassword.length() < 6) { inputPassword.setError(getString(R.string.minimum_password)); return; } progressBar.setVisibility(View.VISIBLE); //authenticate user mAuth.signInWithEmailAndPassword(loginEmail, loginPassword) .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. progressBar.setVisibility(View.GONE); if (!task.isSuccessful()) { // there was an error if (loginEmail.length() < 6) { inputPassword.setError(getString(R.string.minimum_password)); } else { if(!isNetworkAvailable()) { toast = Toast.makeText(LoginActivity.this, R.string.disconnected, Toast.LENGTH_LONG); toastView = toast.getView(); toast.show(); } else { toast = Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG); toastView = toast.getView(); toast.show(); } } } else { Intent intent = new Intent(LoginActivity.this, MainActivity.class); finish(); startActivity(intent); } } }); } }); btnLoginGoogle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Toast.makeText(getApplicationContext(), "Not yet implemented, we're still fixing the issue", Toast.LENGTH_LONG).show(); if(Auth.GoogleSignInApi == null) signIn(); else { Intent intentToMain = new Intent(getApplicationContext(), MainActivity.class); startActivity(intentToMain); } } }); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } @Override public void onStart() { super.onStart(); OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient); if (opr.isDone()) { // If the user's cached credentials are valid, the OptionalPendingResult will be "done" // and the GoogleSignInResult will be available instantly. Log.d(TAG, "Got cached sign-in"); GoogleSignInResult result = opr.get(); handleSignInResult(result); } else { // If the user has not previously signed in on this device or the sign-in has expired, // this asynchronous branch will attempt to sign in the user silently. Cross-device // single sign-on will occur in this branch. showProgressDialog(); opr.setResultCallback(new ResultCallback<GoogleSignInResult>() { @Override public void onResult(@NonNull GoogleSignInResult googleSignInResult) { hideProgressDialog(); handleSignInResult(googleSignInResult); } }); } } // [START onActivityResult] @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); handleSignInResult(result); } } // [END onActivityResult] // [START handleSignInResult] private void handleSignInResult(GoogleSignInResult result) { Log.d(TAG, "handleSignInResult:" + result.isSuccess()); if (result.isSuccess()) { // Signed in successfully, show authenticated UI. GoogleSignInAccount googleAcct = result.getSignInAccount(); assert googleAcct != null; String signInResult = getString(R.string.signed_in_fmt, googleAcct.getDisplayName()); for(int hsir = 0; hsir < 1; hsir++) { Intent intentToMain = new Intent(this, MainActivity.class); Toast.makeText(getApplicationContext(), signInResult, Toast.LENGTH_SHORT).show(); startActivity(intentToMain); } // updateUI(true); // } else { // Signed out, show unauthenticated UI. // updateUI(false); } } // [END handleSignInResult] // [START signIn] private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } // [END signIn] // [START signOut] private void signOut() { Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { // [START_EXCLUDE] // updateUI(false); // [END_EXCLUDE] } }); if(mAuth.getCurrentUser()!=null ) { String userId = mAuth.getCurrentUser().getUid(); userDatabase.child(userId).child("connection").setValue(UsersChatAdapter.OFFLINE); } } // [END signOut] // [START revokeAccess] private void revokeAccess() { Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { // [START_EXCLUDE] // updateUI(false); // [END_EXCLUDE] } }); } // [END revokeAccess] @Override public void onConnectionFailed(ConnectionResult connectionResult) { // An unresolvable error has occurred and Google APIs (including Sign-In) will not // be available. Log.d(TAG, "onConnectionFailed:" + connectionResult); } private void showProgressDialog() { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(getString(R.string.loading)); mProgressDialog.setIndeterminate(true); } // mProgressDialog.show(); } private void hideProgressDialog() { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.hide(); } } // private void updateUI(boolean signedIn) { // if (signedIn) { // findViewById(R.id.sign_in_button).setVisibility(View.GONE); // findViewById(R.id.action_sign_out).setVisibility(View.VISIBLE); // } else { // Toast.makeText(getApplicationContext(), R.string.signed_out, Toast.LENGTH_SHORT).show(); //// Snackbar.make(cl_loginToMain, R.string.signed_out, Snackbar.LENGTH_SHORT); // findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE); // findViewById(R.id.action_sign_out).setVisibility(View.GONE); // } // } protected void setGooglePlusButtonText(SignInButton btnLoginProvider, String buttonText) { // Find the TextView that is inside of the SignInButton and set its text for (int i = 0; i < btnLoginProvider.getChildCount(); i++) { View v = btnLoginProvider.getChildAt(i); buttonText = "SIGN IN WITH GOOGLE"; if (v instanceof TextView) { TextView tv = (TextView) v; tv.setText(buttonText); return; } } } // Prevent going to MainActivity before login @Override public void onBackPressed() { moveTaskToBack(true); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sign_in_button: signIn(); break; case R.id.action_sign_out: signOut(); break; // case R.id.disconnect: // revokeAccess(); // break; } } }
/* * * Copyright 2017 Skymind, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. */ package org.datavec.api.transform.serde; import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.datavec.api.io.WritableComparator; import org.datavec.api.transform.Transform; import org.datavec.api.transform.analysis.columns.ColumnAnalysis; import org.datavec.api.transform.condition.column.ColumnCondition; import org.datavec.api.transform.filter.Filter; import org.datavec.api.transform.metadata.ColumnMetaData; import org.datavec.api.transform.rank.CalculateSortedRank; import org.datavec.api.transform.schema.Schema; import org.datavec.api.transform.sequence.SequenceComparator; import org.datavec.api.transform.sequence.SequenceSplit; import org.datavec.api.transform.sequence.window.WindowFunction; import org.datavec.api.transform.serde.legacy.LegacyMappingHelper; import org.datavec.api.writable.Writable; import org.nd4j.linalg.activations.IActivation; import org.nd4j.linalg.lossfunctions.ILossFunction; import org.nd4j.linalg.primitives.Pair; import org.nd4j.serde.json.LegacyIActivationDeserializer; import org.nd4j.serde.json.LegacyILossFunctionDeserializer; import org.nd4j.shade.jackson.annotation.JsonAutoDetect; import org.nd4j.shade.jackson.annotation.JsonTypeInfo; import org.nd4j.shade.jackson.annotation.PropertyAccessor; import org.nd4j.shade.jackson.databind.*; import org.nd4j.shade.jackson.databind.cfg.MapperConfig; import org.nd4j.shade.jackson.databind.introspect.Annotated; import org.nd4j.shade.jackson.databind.introspect.AnnotatedClass; import org.nd4j.shade.jackson.databind.introspect.AnnotationMap; import org.nd4j.shade.jackson.databind.introspect.JacksonAnnotationIntrospector; import org.nd4j.shade.jackson.databind.jsontype.TypeResolverBuilder; import org.nd4j.shade.jackson.dataformat.yaml.YAMLFactory; import org.nd4j.shade.jackson.datatype.joda.JodaModule; import java.lang.annotation.Annotation; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * JSON mappers for deserializing neural net configurations, etc. * * @author Alex Black */ @Slf4j public class JsonMappers { /** * This system property is provided as an alternative to {@link #registerLegacyCustomClassesForJSON(Class[])} * Classes can be specified in comma-separated format */ public static String CUSTOM_REGISTRATION_PROPERTY = "org.datavec.config.custom.legacyclasses"; static { String p = System.getProperty(CUSTOM_REGISTRATION_PROPERTY); if(p != null && !p.isEmpty()){ String[] split = p.split(","); List<Class<?>> list = new ArrayList<>(); for(String s : split){ try{ Class<?> c = Class.forName(s); list.add(c); } catch (Throwable t){ log.warn("Error parsing {} system property: class \"{}\" could not be loaded",CUSTOM_REGISTRATION_PROPERTY, s, t); } } if(list.size() > 0){ try { registerLegacyCustomClassesForJSONList(list); } catch (Throwable t){ log.warn("Error registering custom classes for legacy JSON deserialization ({} system property)",CUSTOM_REGISTRATION_PROPERTY, t); } } } } private static ObjectMapper jsonMapper; private static ObjectMapper yamlMapper; static { jsonMapper = new ObjectMapper(); yamlMapper = new ObjectMapper(new YAMLFactory()); configureMapper(jsonMapper); configureMapper(yamlMapper); } private static Map<Class, ObjectMapper> legacyMappers = new ConcurrentHashMap<>(); /** * Register a set of classes (Transform, Filter, etc) for JSON deserialization.<br> * <br> * This is required ONLY when BOTH of the following conditions are met:<br> * 1. You want to load a serialized TransformProcess, saved in 1.0.0-alpha or before, AND<br> * 2. The serialized TransformProcess has a custom Transform, Filter, etc (i.e., one not defined in DL4J)<br> * <br> * By passing the classes of these custom classes here, DataVec should be able to deserialize them, in spite of the JSON * format change between versions. * * @param classes Classes to register */ public static void registerLegacyCustomClassesForJSON(Class<?>... classes) { registerLegacyCustomClassesForJSONList(Arrays.<Class<?>>asList(classes)); } /** * @see #registerLegacyCustomClassesForJSON(Class[]) */ public static void registerLegacyCustomClassesForJSONList(List<Class<?>> classes){ //Default names (i.e., old format for custom JSON format) List<Pair<String,Class>> list = new ArrayList<>(); for(Class<?> c : classes){ list.add(new Pair<String,Class>(c.getSimpleName(), c)); } registerLegacyCustomClassesForJSON(list); } /** * Set of classes that can be registered for legacy deserialization. */ private static List<Class<?>> REGISTERABLE_CUSTOM_CLASSES = (List<Class<?>>) Arrays.<Class<?>>asList( Transform.class, ColumnAnalysis.class, ColumnCondition.class, Filter.class, ColumnMetaData.class, CalculateSortedRank.class, Schema.class, SequenceComparator.class, SequenceSplit.class, WindowFunction.class, Writable.class, WritableComparator.class ); /** * Register a set of classes (Layer, GraphVertex, InputPreProcessor, IActivation, ILossFunction, ReconstructionDistribution * ONLY) for JSON deserialization, with custom names.<br> * Using this method directly should never be required (instead: use {@link #registerLegacyCustomClassesForJSON(Class[])} * but is added in case it is required in non-standard circumstances. */ public static void registerLegacyCustomClassesForJSON(List<Pair<String,Class>> classes){ for(Pair<String,Class> p : classes){ String s = p.getFirst(); Class c = p.getRight(); //Check if it's a valid class to register... boolean found = false; for( Class<?> c2 : REGISTERABLE_CUSTOM_CLASSES){ if(c2.isAssignableFrom(c)){ Map<String,String> map = LegacyMappingHelper.legacyMappingForClass(c2); map.put(p.getFirst(), p.getSecond().getName()); found = true; } } if(!found){ throw new IllegalArgumentException("Cannot register class for legacy JSON deserialization: class " + c.getName() + " is not a subtype of classes " + REGISTERABLE_CUSTOM_CLASSES); } } } /** * Get the legacy JSON mapper for the specified class.<br> * * <b>NOTE</b>: This is intended for internal backward-compatibility use. * * Note to developers: The following JSON mappers are for handling legacy format JSON. * Note that after 1.0.0-alpha, the JSON subtype format for Transforms, Filters, Conditions etc were changed from * a wrapper object, to an "@class" field. However, to not break all saved transforms networks, these mappers are * part of the solution.<br> * <br> * How legacy loading works (same pattern for all types - Transform, Filter, Condition etc)<br> * 1. Transforms etc JSON that has a "@class" field are deserialized as normal<br> * 2. Transforms JSON that don't have such a field are mapped (via Layer @JsonTypeInfo) to LegacyMappingHelper.TransformHelper<br> * 3. LegacyMappingHelper.TransformHelper has a @JsonDeserialize annotation - we use LegacyMappingHelper.LegacyTransformDeserializer to handle it<br> * 4. LegacyTransformDeserializer has a list of old names (present in the legacy format JSON) and the corresponding class names * 5. BaseLegacyDeserializer (that LegacyTransformDeserializer extends) does a lookup and handles the deserialization * * Now, as to why we have one ObjectMapper for each type: We can't use the default JSON mapper for the legacy format, * as it'll fail due to not having the expected "@class" annotation. * Consequently, we need to tell Jackson to ignore that specific annotation and deserialize to the specified * class anyway. The ignoring is done via an annotation introspector, defined below in this class. * However, we can't just use a single annotation introspector (and hence ObjectMapper) for loading legacy values of * all types - if we did, then any nested types would fail (i.e., an Condition in a Transform - the Transform couldn't * be deserialized correctly, as the annotation would be ignored). * */ public static synchronized ObjectMapper getLegacyMapperFor(@NonNull Class<?> clazz){ if(!legacyMappers.containsKey(clazz)){ ObjectMapper m = new ObjectMapper(); configureMapper(m); m.setAnnotationIntrospector(new IgnoreJsonTypeInfoIntrospector(Collections.<Class>singletonList(clazz))); legacyMappers.put(clazz, m); } return legacyMappers.get(clazz); } /** * @return The default/primary ObjectMapper for deserializing JSON network configurations in DL4J */ public static ObjectMapper getMapper(){ return jsonMapper; } /** * @return The default/primary ObjectMapper for deserializing network configurations in DL4J (YAML format) */ public static ObjectMapper getMapperYaml() { return yamlMapper; } private static void configureMapper(ObjectMapper ret) { ret.registerModule(new JodaModule()); ret.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); ret.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); ret.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); ret.enable(SerializationFeature.INDENT_OUTPUT); ret.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); ret.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); } /** * Custom Jackson Introspector to ignore the {@code @JsonTypeYnfo} annotations on layers etc. * This is so we can deserialize legacy format JSON without recursing infinitely, by selectively ignoring * a set of JsonTypeInfo annotations */ @AllArgsConstructor private static class IgnoreJsonTypeInfoIntrospector extends JacksonAnnotationIntrospector { private List<Class> classList; @Override protected TypeResolverBuilder<?> _findTypeResolver(MapperConfig<?> config, Annotated ann, JavaType baseType) { if(ann instanceof AnnotatedClass){ AnnotatedClass c = (AnnotatedClass)ann; Class<?> annClass = c.getAnnotated(); boolean isAssignable = false; for(Class c2 : classList){ if(c2.isAssignableFrom(annClass)){ isAssignable = true; break; } } if( isAssignable ){ AnnotationMap annotations = (AnnotationMap) ((AnnotatedClass) ann).getAnnotations(); if(annotations == null || annotations.annotations() == null){ //Probably not necessary - but here for safety return super._findTypeResolver(config, ann, baseType); } AnnotationMap newMap = null; for(Annotation a : annotations.annotations()){ Class<?> annType = a.annotationType(); if(annType == JsonTypeInfo.class){ //Ignore the JsonTypeInfo annotation on the Layer class continue; } if(newMap == null){ newMap = new AnnotationMap(); } newMap.add(a); } if(newMap == null) return null; //Pass the remaining annotations (if any) to the original introspector AnnotatedClass ann2 = c.withAnnotations(newMap); return super._findTypeResolver(config, ann2, baseType); } } return super._findTypeResolver(config, ann, baseType); } } }
package fatSecret; import gui.Utility; import fatSecret.recipeSearch.RecipeSearchResults; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.security.SignatureException; import java.sql.SQLException; import java.util.Hashtable; public class FatSecret { /** * this gets rid of exception for not using native acceleration */ private int user_count = 0; public static boolean changeKey = false; static { System.setProperty("com.sun.media.jai.disableMediaLib", "true"); } public FatSecret() {} private String callRest(Hashtable<String, String> params) throws SignatureException, IOException { String urlString = "http://platform.fatsecret.com/rest/server.api"; if (FatSecret.changeKey) { FatSecret.changeKey = false; user_count = (user_count+1) % 4; } FatParameter fp = new FatParameter(true, params, user_count); urlString += "?" + fp.GetAllParamString(); return readUrl(urlString); } private String callRest(String accessSharedSecret, Hashtable<String, String> params) throws SignatureException, IOException { String urlString = "http://platform.fatsecret.com/rest/server.api"; if (FatSecret.changeKey) { FatSecret.changeKey = false; user_count = (user_count+1) % 4; } FatParameter fp = new FatParameter(true, params, accessSharedSecret, user_count); urlString += "?" + fp.GetAllParamString(); return readUrl(urlString); } private String callRestByDefaultUser(Hashtable<String, String> params) throws SignatureException, IOException { // params.put("oauth_token", "c0d80ee3e5fb47f49f122439ee036189"); // return callRest("0f7d0dabc817415495a6d972df9389a7", params); params.put("oauth_token", "b4352e571ada43c1beb2d8787b987cee"); return callRest("911f9f4276eb4a57865d07f95033c157", params); } private String readUrl(String urlString) throws IOException { String result = ""; // Create a URL for the desired page URL url = new URL(urlString); // Read all the text returned by the server BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String str; while ((str = in.readLine()) != null) { // str is one line of text; readLine() strips the newline character(s) result += str + "\n"; } in.close(); return result; } public String getRecipe(int recipeId) throws SignatureException, IOException, SQLException { Hashtable<String, String> params = new Hashtable<String, String>(); //method String MUST be "recipe.get" params.put("method", "recipe.get"); //recipe_id Long The ID of the recipe to retrieve. params.put("recipe_id", Integer.toString(recipeId)); return callRest(params); } public String searchFood(String food) throws SignatureException, IOException, SQLException { Hashtable<String, String> params = new Hashtable<String, String>(); //method String MUST be "recipe.get" params.put("method", "foods.search"); //recipe_id Long The ID of the recipe to retrieve. params.put("search_expression", food); return callRest(params); } public String searchRecipes(String recipe,String page, String maxResult) throws SignatureException, IOException, SQLException { Hashtable<String, String> params = new Hashtable<String, String>(); //method String MUST be "recipe.get" params.put("method", "recipes.search"); //recipe_id Long The ID of the recipe to retrieve. params.put("search_expression", recipe); params.put("page_number", page); // params.put("recipe_type", "Breakfast"); params.put("max_results", maxResult); return callRest(params); } private String getFood(int foodId) throws SignatureException, IOException { Hashtable<String, String> params = new Hashtable<String, String>(); params.put("method", "food.get"); //food_id Long The ID of the food to retrieve. params.put("food_id", Integer.toString(foodId)); return callRest(params); } // user_id : nightingale // <auth_token>c0d80ee3e5fb47f49f122439ee036189</auth_token> // <auth_secret>0f7d0dabc817415495a6d972df9389a7</auth_secret> private String createProfile(String userId) throws SignatureException, IOException { Hashtable<String, String> params = new Hashtable<String, String>(); params.put("method", "profile.create"); params.put("user_id", userId); return callRest(params); } public static int crawlOneRecipe(int recipeId, FatSecret fs) throws Exception { System.out.println("Getting recipe #" + recipeId); String xml = fs.getRecipe(recipeId); // System.out.println(xml); if (xml.equals("")) { System.out.println(xml); return 0; } if (xml.indexOf("</error>") != -1) { System.out.println(xml); return -1; } Recipe r = new Recipe(xml); if (!r.getImageUrl().equals("")) { UrlDownload.fileUrl(r.getImageUrl(), r.getImageFilename(), "img/"); if (r.getImageFilename().toLowerCase().endsWith(".jpg") || r.getImageFilename().toLowerCase().endsWith(".png") || r.getImageFilename().toLowerCase().endsWith(".gif")) { String filepath = "img/\\" + r.getImageFilename(); File f = new File(filepath); byte[] imageData = Utils.getBytesFromFile(f); ImageResize ir = new ImageResize(); byte[] largeImageData = ir.resizeImageAsJPG(imageData, 300); byte[] mediumImageData = ir.resizeImageAsJPG(imageData, 200); byte[] smallImageData = ir.resizeImageAsJPG(imageData, 100); String prefixPath = "img/" + r.getRecipeId() + "_"; Utils.writeBytesToFile(prefixPath + "large.jpg", largeImageData); Utils.writeBytesToFile(prefixPath + "medium.jpg", mediumImageData); Utils.writeBytesToFile(prefixPath + "small.jpg", smallImageData); } else throw new Exception("Unsupport Image File type: " + r.getImageFilename()); } if(r.getCookingTime()>-1) { if (r.getPreparationTime() < 0) { r.setPreparationTime(0); } if (!Utility.PUBLIC_BASE.doesSolutionExist(Utility.activity, r)) { Utility.NEWRECIPES.add(r); } } return 1; } public static int searchFood(String food, FatSecret fs) throws Exception { System.out.println("Searching for: " + food); String xml = fs.searchFood(food); System.out.println(xml); if (xml.equals("")) { System.out.println(xml); return 0; } if (xml.indexOf("</error>") != -1) { System.out.println(xml); return -1; } return 1; } public static RecipeSearchResults searchRecipe(String recipe, FatSecret fs,String page, String maxResult) throws Exception { System.out.println("Searching for: " + recipe); String xml = fs.searchRecipes(recipe, page, maxResult); RecipeSearchResults recipeSearchResults = new RecipeSearchResults(xml); return recipeSearchResults; } // public static void main(String[] args) throws NamingException { // FatSecret fs = new FatSecret(); // Utility.fatSecret = fs; // Context ctx = new InitialContext(); // // FatSecretGUI fatSecretGUI = new FatSecretGUI("FatSecret"); // // } }
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.classic; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import ch.qos.logback.classic.util.LoggerNameUtil; import org.slf4j.ILoggerFactory; import org.slf4j.Marker; import ch.qos.logback.classic.spi.LoggerComparator; import ch.qos.logback.classic.spi.LoggerContextListener; import ch.qos.logback.classic.spi.LoggerContextVO; import ch.qos.logback.classic.spi.TurboFilterList; import ch.qos.logback.classic.turbo.TurboFilter; import ch.qos.logback.core.ContextBase; import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.spi.FilterReply; import ch.qos.logback.core.spi.LifeCycle; import ch.qos.logback.core.status.StatusListener; import ch.qos.logback.core.status.StatusManager; import ch.qos.logback.core.status.WarnStatus; /** * LoggerContext glues many of the logback-classic components together. In * principle, every logback-classic component instance is attached either * directly or indirectly to a LoggerContext instance. Just as importantly * LoggerContext implements the {@link ILoggerFactory} acting as the * manufacturing source of {@link Logger} instances. * * @author Ceki Gulcu */ public class LoggerContext extends ContextBase implements ILoggerFactory, LifeCycle { final Logger root; private int size; private int noAppenderWarning = 0; final private List<LoggerContextListener> loggerContextListenerList = new ArrayList<LoggerContextListener>(); private Map<String, Logger> loggerCache; private LoggerContextVO loggerContextRemoteView; private final TurboFilterList turboFilterList = new TurboFilterList(); private boolean packagingDataEnabled = true; private int maxCallerDataDepth = ClassicConstants.DEFAULT_MAX_CALLEDER_DATA_DEPTH; int resetCount = 0; private List<String> frameworkPackages; public LoggerContext() { super(); this.loggerCache = new ConcurrentHashMap<String, Logger>(); this.loggerContextRemoteView = new LoggerContextVO(this); this.root = new Logger(Logger.ROOT_LOGGER_NAME, null, this); this.root.setLevel(Level.DEBUG); loggerCache.put(Logger.ROOT_LOGGER_NAME, root); initEvaluatorMap(); size = 1; this.frameworkPackages = new ArrayList<String>(); } void initEvaluatorMap() { putObject(CoreConstants.EVALUATOR_MAP, new HashMap()); } /** * A new instance of LoggerContextRemoteView needs to be created each time the * name or propertyMap (including keys or values) changes. */ private void updateLoggerContextVO() { loggerContextRemoteView = new LoggerContextVO(this); } @Override public void putProperty(String key, String val) { super.putProperty(key, val); updateLoggerContextVO(); } @Override public void setName(String name) { super.setName(name); updateLoggerContextVO(); } public final Logger getLogger(final Class clazz) { return getLogger(clazz.getName()); } public final Logger getLogger(final String name) { if (name == null) { throw new IllegalArgumentException("name argument cannot be null"); } // if we are asking for the root logger, then let us return it without // wasting time if (Logger.ROOT_LOGGER_NAME.equalsIgnoreCase(name)) { return root; } int i = 0; Logger logger = root; // check if the desired logger exists, if it does, return it // without further ado. Logger childLogger = (Logger) loggerCache.get(name); // if we have the child, then let us return it without wasting time if (childLogger != null) { return childLogger; } // if the desired logger does not exist, them create all the loggers // in between as well (if they don't already exist) String childName; while (true) { int h = LoggerNameUtil.getSeparatorIndexOf(name, i); if (h == -1) { childName = name; } else { childName = name.substring(0, h); } // move i left of the last point i = h + 1; synchronized (logger) { childLogger = logger.getChildByName(childName); if (childLogger == null) { childLogger = logger.createChildByName(childName); loggerCache.put(childName, childLogger); incSize(); } } logger = childLogger; if (h == -1) { return childLogger; } } } private void incSize() { size++; } int size() { return size; } /** * Check if the named logger exists in the hierarchy. If so return its * reference, otherwise returns <code>null</code>. * * @param name the name of the logger to search for. */ public Logger exists(String name) { return (Logger) loggerCache.get(name); } final void noAppenderDefinedWarning(final Logger logger) { if (noAppenderWarning++ == 0) { getStatusManager().add( new WarnStatus("No appenders present in context [" + getName() + "] for logger [" + logger.getName() + "].", logger)); } } public List<Logger> getLoggerList() { Collection<Logger> collection = loggerCache.values(); List<Logger> loggerList = new ArrayList<Logger>(collection); Collections.sort(loggerList, new LoggerComparator()); return loggerList; } public LoggerContextVO getLoggerContextRemoteView() { return loggerContextRemoteView; } public void setPackagingDataEnabled(boolean packagingDataEnabled) { this.packagingDataEnabled = packagingDataEnabled; } public boolean isPackagingDataEnabled() { return packagingDataEnabled; } /** * This method clears all internal properties, except internal status messages, * closes all appenders, removes any turboFilters, fires an OnReset event, * removes all status listeners, removes all context listeners * (except those which are reset resistant). * <p/> * As mentioned above, internal status messages survive resets. */ @Override public void reset() { resetCount++; super.reset(); initEvaluatorMap(); root.recursiveReset(); resetTurboFilterList(); fireOnReset(); resetListenersExceptResetResistant(); resetStatusListeners(); } private void resetStatusListeners() { StatusManager sm = getStatusManager(); for (StatusListener sl : sm.getCopyOfStatusListenerList()) { sm.remove(sl); } } public TurboFilterList getTurboFilterList() { return turboFilterList; } public void addTurboFilter(TurboFilter newFilter) { turboFilterList.add(newFilter); } /** * First processPriorToRemoval all registered turbo filters and then clear the registration * list. */ public void resetTurboFilterList() { for (TurboFilter tf : turboFilterList) { tf.stop(); } turboFilterList.clear(); } final FilterReply getTurboFilterChainDecision_0_3OrMore(final Marker marker, final Logger logger, final Level level, final String format, final Object[] params, final Throwable t) { if (turboFilterList.size() == 0) { return FilterReply.NEUTRAL; } return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, params, t); } final FilterReply getTurboFilterChainDecision_1(final Marker marker, final Logger logger, final Level level, final String format, final Object param, final Throwable t) { if (turboFilterList.size() == 0) { return FilterReply.NEUTRAL; } return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, new Object[]{param}, t); } final FilterReply getTurboFilterChainDecision_2(final Marker marker, final Logger logger, final Level level, final String format, final Object param1, final Object param2, final Throwable t) { if (turboFilterList.size() == 0) { return FilterReply.NEUTRAL; } return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, new Object[]{param1, param2}, t); } // === start listeners ============================================== public void addListener(LoggerContextListener listener) { loggerContextListenerList.add(listener); } public void removeListener(LoggerContextListener listener) { loggerContextListenerList.remove(listener); } private void resetListenersExceptResetResistant() { List<LoggerContextListener> toRetain = new ArrayList<LoggerContextListener>(); for (LoggerContextListener lcl : loggerContextListenerList) { if (lcl.isResetResistant()) { toRetain.add(lcl); } } loggerContextListenerList.retainAll(toRetain); } private void resetAllListeners() { loggerContextListenerList.clear(); } public List<LoggerContextListener> getCopyOfListenerList() { return new ArrayList<LoggerContextListener>(loggerContextListenerList); } void fireOnLevelChange(Logger logger, Level level) { for (LoggerContextListener listener : loggerContextListenerList) { listener.onLevelChange(logger, level); } } private void fireOnReset() { for (LoggerContextListener listener : loggerContextListenerList) { listener.onReset(this); } } private void fireOnStart() { for (LoggerContextListener listener : loggerContextListenerList) { listener.onStart(this); } } private void fireOnStop() { for (LoggerContextListener listener : loggerContextListenerList) { listener.onStop(this); } } // === end listeners ============================================== public void start() { super.start(); fireOnStart(); } public void stop() { reset(); fireOnStop(); resetAllListeners(); super.stop(); } @Override public String toString() { return this.getClass().getName() + "[" + getName() + "]"; } public int getMaxCallerDataDepth() { return maxCallerDataDepth; } public void setMaxCallerDataDepth(int maxCallerDataDepth) { this.maxCallerDataDepth = maxCallerDataDepth; } /** * List of packages considered part of the logging framework such that they are never considered * as callers of the logging framework. This list used to compute the caller for logging events. * <p/> * To designate package "com.foo" as well as all its subpackages as being part of the logging framework, simply add * "com.foo" to this list. * * @return list of framework packages */ public List<String> getFrameworkPackages() { return frameworkPackages; } }
/* * Copyright 2015 Eduardo Ramos. * * 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 net.uniform.api.html; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.uniform.impl.utils.HTMLRenderer; import net.uniform.impl.utils.HTMLRenderingUtils; import net.uniform.impl.utils.UniformUtils; /** * A Simple HTML tag is able to: * <ul> * <li>Have a tag name (optional) to enclose the content or subtags. If tag name is null, only the content or subtags is rendered</li> * <li>Have a list of properties to be rendered as attributes of the enclosing tag</li> * <li>Have a text content (escaped or not) or a list of subtags</li> * </ul> * * <p><b>If any not null text content is set, subtags will be ignored</b></p> * * <p>These tags can be rendered as HTML String with the {@link HTMLRenderer} class.</p> * * <p>All property names will be converted to lower-case</p> * * @author Eduardo Ramos * @see HTMLRenderingUtils * @see HTMLRenderer */ public class SimpleHTMLTag { /** * Empty properties to avoid creating many maps where not necessary. */ private final Map<String, String> EMPTY_PROPERTIES = Collections.unmodifiableMap(new HashMap<String, String>()); /** * Empty list of tags to avoid creating many lists where not necessary. */ private final List<SimpleHTMLTag> EMPTY_TAGS = Collections.unmodifiableList(new ArrayList<SimpleHTMLTag>()); protected String name; protected Map<String, String> properties; protected List<SimpleHTMLTag> subTags; protected String content = null; private boolean escapeContent = true; public SimpleHTMLTag() { } public SimpleHTMLTag(String name) { this.name = name; } public SimpleHTMLTag(String name, Map<String, String> properties) { this.name = name; this.properties = new HashMap<>(properties); } public SimpleHTMLTag(String name, String content) { this.name = name; this.content = content; } public SimpleHTMLTag(String name, Map<String, String> properties, String content) { this.name = name; this.properties = new HashMap<>(properties); this.content = content; } /** * Copy constructor for a tag an its subtags. * * @param tag Input tag to create a copy */ public SimpleHTMLTag(SimpleHTMLTag tag) { this.name = tag.name; this.properties = tag.properties != null ? new HashMap<>(tag.properties) : null; this.content = tag.content; this.escapeContent = tag.escapeContent; if (tag.subTags != null) { this.subTags = new ArrayList<>(); for (SimpleHTMLTag subTag : tag.subTags) { this.subTags.add(new SimpleHTMLTag(subTag)); } } } /** * Sets the tag name. * * @param name Tag name * @return This tag */ public SimpleHTMLTag setName(String name) { this.name = name; return this; } /** * Sets the string content of the tag. * * @param content Content * @return This tag */ public SimpleHTMLTag setContent(String content) { this.content = content; return this; } /** * Returns the name of this tag. * * @return Tag name or null for content-only tags */ public String getName() { return name; } /** * Returns the text content of this tag. * * @return Text content of this tag or null */ public String getContent() { return content; } /** * Returns the subtags of this tag, if any * * @return List of tags, never null */ public List<SimpleHTMLTag> getSubTags() { if (subTags == null) { return EMPTY_TAGS; } return new ArrayList<>(subTags); } /** * Clears all the subtags */ public void clearSubTags() { subTags = null; } /** * Adds a subtag to this tag. * If the tag has a text content, any subtag will be ignored. * @param tag Subtag to add * @return This tag */ public SimpleHTMLTag addSubTag(SimpleHTMLTag tag) { if (tag == this) { throw new IllegalArgumentException("The tag cannot be its own parent"); } if (subTags == null) { subTags = new ArrayList<>(); } subTags.add(tag); return this; } /** * Sets a property of the tag by key. * * @param key Property key * @param value Property value * @return This tag */ public SimpleHTMLTag setProperty(String key, String value) { key = UniformUtils.checkPropertyNameAndLowerCase(key); if (properties == null) { properties = new HashMap<>(); } properties.put(key, value); return this; } /** * Removes a property of the tag by key. * * @param key Propery key * @return This tag */ public SimpleHTMLTag removeProperty(String key) { key = UniformUtils.checkPropertyNameAndLowerCase(key); if (properties != null) { properties.remove(key); } return this; } /** * Replaces all properties of the tag with a map of properties indexed by key. * * @param properties New properties * @return This tag */ public SimpleHTMLTag setProperties(Map<String, String> properties) { if (properties == null || properties.isEmpty()) { this.properties = null; } else { this.properties = new HashMap<>(); for (Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); key = UniformUtils.checkPropertyNameAndLowerCase(key); this.properties.put(key, entry.getValue()); } } return this; } /** * Returns a property of this tag by key, if present. * * @param key Property key * @return Property value or null */ public String getProperty(String key) { key = UniformUtils.checkPropertyNameAndLowerCase(key); if (properties == null) { return null; } return properties.get(key); } /** * Returns all the properties in this tag. * * @return A properties index by key, never null */ public Map<String, String> getProperties() { if (properties == null) { return EMPTY_PROPERTIES; } return new HashMap<>(properties); } /** * Sets the escape HTML flag for this tag's content. * By default escape is enabled. * @param escapeContent Escape flag * @return This tag */ public SimpleHTMLTag setEscapeContent(boolean escapeContent) { this.escapeContent = escapeContent; return this; } /** * Indicates if the escape HTML flag for this tag's content is active. * By default escape is enabled. * @return Escape HTML flag */ public boolean isEscapeContent() { return escapeContent; } @Override public String toString() { return HTMLRenderingUtils.render(this); } }
package com.mauriciotogneri.andwars.ui.renders; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.PixelFormat; import android.graphics.Point; import android.graphics.PointF; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.mauriciotogneri.andwars.objects.Cell; import com.mauriciotogneri.andwars.objects.Map; import com.mauriciotogneri.andwars.objects.Move; import java.util.ArrayList; import java.util.List; import java.util.Random; public class MapRenderer extends SurfaceView implements SurfaceHolder.Callback { @NonNull private final Paint clearPaint; @NonNull private final Paint backgroundPaint; @NonNull private final Paint adjacencyPaint; @NonNull private final List<Point> background = new ArrayList<>(); protected static int BLOCK_WIDTH = 0; protected static int BLOCK_HEIGHT = 0; private static int FONT_SIZE = 0; private static final int NUMBER_OF_STARS = 150; private final MapListener mapListener; public MapRenderer(@NonNull Context context, MapListener mapListener) { super(context); this.mapListener = mapListener; this.clearPaint = new Paint(); this.clearPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR)); this.backgroundPaint = new Paint(); this.backgroundPaint.setColor(Color.WHITE); this.adjacencyPaint = new Paint(); this.adjacencyPaint.setFlags(Paint.ANTI_ALIAS_FLAG); this.adjacencyPaint.setColor(Color.GRAY); this.adjacencyPaint.setStrokeWidth(5); SurfaceHolder surfaceHolder = getHolder(); surfaceHolder.setFormat(PixelFormat.TRANSPARENT); surfaceHolder.addCallback(this); } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { } @Override public void surfaceCreated(SurfaceHolder holder) { if (this.background.isEmpty()) { setBackgroundStars(getWidth(), getHeight()); } if (this.mapListener != null) { this.mapListener.onCreateMap(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { } private void setBackgroundStars(int width, int height) { Random random = new Random(); for (int i = 0; i < MapRenderer.NUMBER_OF_STARS; i++) { int x = random.nextInt(width); int y = random.nextInt(height); this.background.add(new Point(x, y)); } } public void update(Map map, Move move) { MapRenderer.BLOCK_WIDTH = getWidth() / map.width; MapRenderer.BLOCK_HEIGHT = getHeight() / map.height; MapRenderer.FONT_SIZE = (MapRenderer.BLOCK_WIDTH + MapRenderer.BLOCK_HEIGHT) / 6; SurfaceHolder surfaceHolder = getHolder(); Canvas canvas = null; try { canvas = surfaceHolder.lockCanvas(); if (canvas != null) { synchronized (surfaceHolder) { canvas.drawPaint(this.clearPaint); drawBackground(this.background, this.backgroundPaint, canvas); List<Cell> cells = map.getCells(); drawAdjacencies(cells, this.adjacencyPaint, canvas); if (move != null) { PointF point = move.getProgressPosition(MapRenderer.BLOCK_WIDTH, MapRenderer.BLOCK_HEIGHT); float pointSize = MapRenderer.BLOCK_WIDTH * 0.15f; drawCircle(point.x, point.y, move.source.getMainColor(), pointSize, canvas); drawText(point.x, point.y, String.valueOf(move.numberOfUnits), (int) (pointSize), Color.WHITE, canvas); } drawCells(cells, canvas); } } } finally { if (canvas != null) { surfaceHolder.unlockCanvasAndPost(canvas); } } } public void update(Map map) { update(map, null); } private void drawBackground(List<Point> background, Paint backgroundPaint, Canvas canvas) { for (Point point : background) { canvas.drawPoint(point.x, point.y, backgroundPaint); } } private void drawAdjacencies(List<Cell> cells, Paint adjacencyPaint, Canvas canvas) { for (Cell cell : cells) { drawAdjacency(cell, adjacencyPaint, canvas); } } private void drawAdjacency(Cell cell, Paint adjacencyPaint, Canvas canvas) { PointF cellCenter = cell.getCenter(MapRenderer.BLOCK_WIDTH, MapRenderer.BLOCK_HEIGHT); for (Cell adjacent : cell.getAdjacents()) { PointF adjacentCenter = adjacent.getCenter(MapRenderer.BLOCK_WIDTH, MapRenderer.BLOCK_HEIGHT); canvas.drawLine(cellCenter.x, cellCenter.y, adjacentCenter.x, adjacentCenter.y, adjacencyPaint); } } private void drawCells(List<Cell> cells, Canvas canvas) { float cellSize = MapRenderer.BLOCK_WIDTH * 0.3f; for (Cell cell : cells) { drawCell(cell, cellSize, canvas); } } private void drawCell(Cell cell, float size, Canvas canvas) { PointF cellCenter = cell.getCenter(MapRenderer.BLOCK_WIDTH, MapRenderer.BLOCK_HEIGHT); if (cell.isEmpty()) { drawCircle(cellCenter.x, cellCenter.y, Cell.COLOR_EMPTY_CELL_FILL, size, canvas); drawCircleBorder(cellCenter.x, cellCenter.y, Cell.COLOR_EMPTY_CELL_BACKGROUND, size, canvas); } else { drawCircle(cellCenter.x, cellCenter.y, cell.getMainColor(), size, canvas); drawCircleBorder(cellCenter.x, cellCenter.y, cell.getBorderColor(), size, canvas); drawText(cellCenter.x, cellCenter.y, String.valueOf(cell.getNumberOfUnits()), MapRenderer.FONT_SIZE, Color.WHITE, canvas); } int highlight = cell.getHighlight(); if (highlight > 0) { float currentHighlight = ((100f - highlight) / 100f); int color = Color.argb((int) (255 * currentHighlight), 255, 255, 255); drawCircleBorder(cellCenter.x, cellCenter.y, color, size + (size * (highlight / 100f) * 0.8f), canvas); } } private void drawCircle(float x, float y, int color, float size, Canvas canvas) { Paint paint = new Paint(); paint.setFlags(Paint.ANTI_ALIAS_FLAG); paint.setColor(color); canvas.drawCircle(x, y, size, paint); } private void drawCircleBorder(float x, float y, int color, float size, Canvas canvas) { Paint paint = new Paint(); paint.setStyle(Paint.Style.STROKE); paint.setFlags(Paint.ANTI_ALIAS_FLAG); paint.setStrokeWidth(size / 8); paint.setColor(color); canvas.drawCircle(x, y, size, paint); } private void drawText(float x, float y, String text, int size, int color, Canvas canvas) { Paint font = new Paint(); font.setColor(color); font.setTextAlign(Align.CENTER); font.setTextSize(size); font.setFlags(Paint.ANTI_ALIAS_FLAG); font.setTypeface(Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)); canvas.drawText(text, x, y + (size / 3), font); } public interface MapListener { void onCreateMap(); } }
package com.juergenrose.eclipse.scada.sample.hd2csv; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.reflect.Type; import java.net.URI; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.joda.time.DateTime; import com.google.common.reflect.TypeToken; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; public class Hd2csv { private final Options options; private static final String csvSeparator = ","; public Hd2csv(Options options) { this.options = options; } public void run() throws IOException { final List<Query> queries = makeQueries(); final SortedMap<Long, Map<String, Double>> result = new TreeMap<Long, Map<String, Double>>(); for (Query query : queries) { String json = doQuery(query); if (json != null) { Type listType = new TypeToken<List<HDEntry>>() { private static final long serialVersionUID = 1L; }.getType(); List<HDEntry> entries = new GsonBuilder() .registerTypeAdapter(DateTime.class, new DateTimeDeserializer()).create() .fromJson(json, listType); for (HDEntry entry : entries) { // // {timestamp=2015-06-20 17:44:00.000, value=9843.0, // quality=1.0, manual=0.0} if (!result.containsKey(entry.timestamp.toInstant().getMillis())) { result.put(entry.timestamp.toInstant().getMillis(), new HashMap<String, Double>(options.items.size())); } result.get(entry.timestamp.toInstant().getMillis()).put(query.item.intern(), entry.quality >= options.quality ? entry.value : null); } } } if (options.asExcel) { writeExcel(result); } else { writeCsv(result); } } private void writeCsv(SortedMap<Long, Map<String, Double>> result) throws IOException { Writer writer; if (options.file != null) { writer = new BufferedWriter(new FileWriter(options.file, options.append)); } else { writer = new BufferedWriter(new OutputStreamWriter(System.out)); } if (!(options.skipHeader || options.append)) { writer.append("sep=;" + System.lineSeparator()); writer.append(csvQuote("timestamp")); for (String item : options.items) { writer.append(csvSeparator); writer.append(csvQuote(item)); } writer.append(System.lineSeparator()); writer.flush(); } for (long millis : result.keySet()) { Map<String, Double> values = result.get(millis); writer.append(Utility.dfs.print(millis)); for (String item : options.items) { writer.append(csvSeparator); writer.append(values.get(item) == null ? "" : "" + values.get(item)); } writer.append(System.lineSeparator()); writer.flush(); } writer.close(); } private void writeExcel(SortedMap<Long, Map<String, Double>> result) throws IOException { Workbook workbook; Sheet sheet; int rowNum = 0; if (options.append && options.file.exists()) { workbook = new HSSFWorkbook(new FileInputStream(options.file)); sheet = workbook.getSheetAt(0); rowNum = sheet.getLastRowNum(); } else { workbook = new HSSFWorkbook(); sheet = workbook.createSheet(); } final CellStyle dateCellStyle = workbook.createCellStyle(); final DataFormat poiFormat = workbook.createDataFormat(); dateCellStyle.setDataFormat(poiFormat.getFormat(Utility.excelDateFormat)); if (!(options.skipHeader || (options.append && rowNum > 0))) { int colNum = 0; Row row = sheet.createRow(rowNum++); Cell cell = row.createCell(colNum++); cell.setCellValue("timestamp"); for (String item : options.items) { cell = row.createCell(colNum++); cell.setCellValue(item); } } for (long millis : result.keySet()) { int colNum = 0; Map<String, Double> values = result.get(millis); Row row = sheet.createRow(rowNum++); Cell cell = row.createCell(colNum++); cell.setCellValue(new Date(millis)); cell.setCellStyle(dateCellStyle); for (String item : options.items) { cell = row.createCell(colNum++); if (values.get(item) == null) { cell.setCellType(Cell.CELL_TYPE_BLANK); } else { cell.setCellValue(values.get(item)); } } } sheet.setDefaultColumnWidth(40); sheet.autoSizeColumn(0); workbook.write(new FileOutputStream(options.file)); workbook.close(); } private String csvQuote(String toQuote) { return "\"" + toQuote.replace("\"", "\"\"") + "\""; } private String doQuery(Query query) { try { if (options.verbose) { System.err.println(String.format("executing request to %s with query parameters from=%s, to=%s, no=%s", query.uri, query.queryParams.get("from"), query.queryParams.get("to"), query.queryParams.get("no"))); } HttpResponse<String> jsonResponse = Unirest.get(query.uri.toString()).header("accept", "application/json") .header("accept", "application/javascript").queryString("from", query.queryParams.get("from")) .queryString("to", query.queryParams.get("to")).queryString("no", query.queryParams.get("no")) .asString(); if (jsonResponse.getStatus() == 200) { return jsonResponse.getBody(); } } catch (UnirestException e) { e.printStackTrace(); } return null; } private List<Query> makeQueries() { final List<Query> queries = new ArrayList<Hd2csv.Query>(options.items.size()); for (String item : options.items) { URI uri; if (options.url != null) { uri = options.url; } else { uri = URI.create("http://" + options.host + ":" + options.port + "/org.eclipse.scada.hd/items/" + item + "/" + options.aggregation + "/"); } Query query = new Query(); query.item = item; query.uri = uri; query.queryParams = new HashMap<String, String>(3); query.queryParams.put("from", Utility.df.print(options.from.getMillis())); query.queryParams.put("to", Utility.df.print(options.to.getMillis())); query.queryParams.put("no", "" + options.no); queries.add(query); } return queries; } class Query { String item; URI uri; Map<String, String> queryParams; } class HDEntry { DateTime timestamp; Double value; Double quality; Double manual; } class DateTimeDeserializer implements JsonDeserializer<DateTime> { public DateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { return Utility.df.parseDateTime(jsonElement.getAsString()); } } }
package com.mirhoseini.diabetes.reminder.ui; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.media.AudioManager; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.mirhoseini.diabetes.reminder.AppManager; import com.mirhoseini.diabetes.reminder.MealInsulin; import com.mirhoseini.diabetes.reminder.MealInsulin.MealType; import com.mirhoseini.diabetes.reminder.R; import com.mirhoseini.diabetes.reminder.Utils; import com.mirhoseini.diabetes.reminder.util.SystemUiHider; import com.mirhoseini.diabetes.reminder.widget.InsulinSyringeView; import java.sql.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * * @see SystemUiHider */ public class AlarmActivity extends ParentActionBarActivity implements OnClickListener { /** * The flags to pass to {@link SystemUiHider#getInstance}. */ private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION; Handler mHideHandler = new Handler(); MealType mealType; MealInsulin meal; TextView tvTitle; AudioManager audioManager; CountDownTimer countDownTimer; /** * The instance of the {@link SystemUiHider} for this activity. */ private SystemUiHider mSystemUiHider; Runnable mHideRunnable = new Runnable() { @Override public void run() { mSystemUiHider.hide(); } }; private ImageView ivIcon; private TextView tvValues; private InsulinSyringeView insulinSyringeView; private int n; private int r; private Button btDone; private TextView tvTimer; private TextView tvTimerLable; private Button btAnimate; private int capacity; public void onAttachedToWindow() { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub } @Override protected void initForm(Bundle savedInstanceState) { setContentView(R.layout.activity_alarm); setupFullScreen(); mealType = (MealType) getIntent().getExtras().getSerializable("DATA"); meal = AppManager.getMeal(context, mealType); tvTitle = (TextView) findViewById(R.id.tvTitle); switch (mealType) { case BREAKFAST: tvTitle.setText(context.getResources().getString( R.string.msg_breakfast)); break; case LUNCH: tvTitle.setText(context.getResources() .getString(R.string.msg_lunch)); break; case DINNER: tvTitle.setText(context.getResources().getString( R.string.msg_dinner)); break; } ivIcon = (ImageView) findViewById(R.id.ivIcon); ivIcon.setImageBitmap(mealType.getIcon(context)); tvValues = (TextView) findViewById(R.id.tvValues); n = meal.getValues().getN(); r = meal.getValues().getR(); tvValues.setText(String.format( getResources().getString(R.string.insulin_reminder_values), r, n)); capacity = AppManager.getCapacity(context); insulinSyringeView = (InsulinSyringeView) findViewById(R.id.insulinSyringeView1); insulinSyringeView.setValues(n, r, capacity); btDone = (Button) findViewById(R.id.btDone); btDone.setOnClickListener(this); btAnimate = (Button) findViewById(R.id.btAnimate); btAnimate.setOnClickListener(this); tvTimer = (TextView) findViewById(R.id.tvTimer); tvTimerLable = (TextView) findViewById(R.id.tvTimerLable); playAlarmSound(); if (meal.isSms()) { startSmsTimer(); } else { tvTimer.setVisibility(View.GONE); tvTimerLable.setVisibility(View.GONE); } } private void playAlarmSound() { audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); AppManager.setUserVolume(audioManager .getStreamVolume(AudioManager.STREAM_MUSIC)); audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); Utils.playSound(context, R.raw.door_bell); } private void startSmsTimer() { // 30 min countdown timer countDownTimer = new CountDownTimer(1000 * 60 * 30, 1) { @SuppressLint("SimpleDateFormat") @Override public void onTick(long millisUntilFinished) { DateFormat df = new SimpleDateFormat("mm'':ss'\"'.SSS"); df.setTimeZone(TimeZone.getTimeZone("GMT+0")); tvTimer.setText(df.format(new Date(millisUntilFinished))); // Bleep every 1 minutes if (millisUntilFinished % (60 * 1000) <= 20) Utils.playSound(context, R.raw.bleep); } @Override public void onFinish() { tvTimer.setText("Reminder SMS message sent!"); tvTimer.setTextColor(Color.RED); tvTimerLable.setVisibility(View.GONE); sendSms(); } }.start(); } private void sendSms() { // TODO Auto-generated method stub } private void setupFullScreen() { // final View controlsView = // findViewById(R.id.fullscreen_content_controls); final View contentView = findViewById(R.id.fullscreen_content); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider .setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() { // Cached values. int mControlsHeight; int mShortAnimTime; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { // If the ViewPropertyAnimator API is available // (Honeycomb MR2 and later), use it to animate the // in-layout UI controls at the bottom of the // screen. if (mControlsHeight == 0) { mControlsHeight = contentView.getHeight(); } if (mShortAnimTime == 0) { mShortAnimTime = getResources().getInteger( android.R.integer.config_shortAnimTime); } contentView .animate() .translationY(visible ? 0 : mControlsHeight) .setDuration(mShortAnimTime); } else { // If the ViewPropertyAnimator APIs aren't // available, simply show or hide the in-layout UI // controls. contentView.setVisibility(visible ? View.VISIBLE : View.GONE); } } }); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. // findViewById(R.id.dummy_button).setOnTouchListener( // mDelayHideTouchListener); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btDone: if (countDownTimer != null) countDownTimer.cancel(); audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, AppManager.getUserVolume(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); finish(); break; case R.id.btSnooze: break; case R.id.btAnimate: startSyringeAnimation(); break; } } private void startSyringeAnimation() { new Thread(new Runnable() { public void run() { btAnimate.post(new Runnable() { @Override public void run() { btAnimate.setEnabled(false); } }); if (r > 0) { for (int i = 0; i <= r; i++) { final int value = i; insulinSyringeView.post(new Runnable() { @Override public void run() { insulinSyringeView .setValues(0, value, capacity); } }); try { Thread.sleep(40); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (n > 0) { for (int i = 0; i <= n; i++) { final int value = i; insulinSyringeView.post(new Runnable() { @Override public void run() { insulinSyringeView .setValues(value, r, capacity); } }); try { Thread.sleep(40); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } btAnimate.post(new Runnable() { @Override public void run() { btAnimate.setEnabled(true); } }); } }).start(); } }
/** * Copyright 2005-2015 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.devops; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import io.fabric8.utils.Maps; import io.fabric8.utils.Strings; import io.fabric8.utils.Systems; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * A helper class for loading and saving the {@link ProjectConfig} */ public class ProjectConfigs { private static final transient Logger LOG = LoggerFactory.getLogger(ProjectConfigs.class); public static final String FILE_NAME = "fabric8.yml"; public static final String LOCAL_FLOW_FILE_NAME = "flow.groovy"; public static String toYaml(Object dto) throws JsonProcessingException { ObjectMapper mapper = createObjectMapper(); return mapper.writeValueAsString(dto); } /** * Returns the configuration from the {@link #FILE_NAME} in the given folder or returns the default configuration */ public static ProjectConfig loadFromFolder(File folder) { File projectConfigFile = new File(folder, FILE_NAME); if (projectConfigFile != null && projectConfigFile.exists() && projectConfigFile.isFile()) { LOG.debug("Parsing fabric8 devops project configuration from: " + projectConfigFile.getName()); try { return ProjectConfigs.parseProjectConfig(projectConfigFile); } catch (IOException e) { LOG.warn("Failed to parse " + projectConfigFile); } } return new ProjectConfig(); } /** * Returns the project config from the given url if it exists or null */ public static ProjectConfig loadFromUrl(String url) { if (Strings.isNotBlank(url)) { try { return loadFromUrl(new URL(url)); } catch (MalformedURLException e) { LOG.warn("Failed to create URL from: " + url + ". " + e, e); } } return null; } /** * Returns the project config from the given url if it exists or null */ public static ProjectConfig loadFromUrl(URL url) { InputStream input = null; try { input = url.openStream(); } catch (FileNotFoundException e) { LOG.info("No fabric8.yml at URL: " + url); } catch (IOException e) { LOG.warn("Failed to open fabric8.yml file at URL: " + url + ". " + e, e); } if (input != null) { try { LOG.info("Parsing " + ProjectConfigs.FILE_NAME + " from " + url); return ProjectConfigs.parseProjectConfig(input); } catch (IOException e) { LOG.warn("Failed to parse " + ProjectConfigs.FILE_NAME + " from " + url + ". " + e, e); } } return null; } /** * Returns true if the given folder has a configuration file called {@link #FILE_NAME} */ public static boolean hasConfigFile(File folder) { File projectConfigFile = new File(folder, FILE_NAME); return projectConfigFile != null && projectConfigFile.exists() && projectConfigFile.isFile(); } /** * Creates a configured Jackson object mapper for parsing YAML */ public static ObjectMapper createObjectMapper() { return new ObjectMapper(new YAMLFactory()); } public static ProjectConfig parseProjectConfig(File file) throws IOException { return parseYaml(file, ProjectConfig.class); } public static ProjectConfig parseProjectConfig(InputStream input) throws IOException { return parseYaml(input, ProjectConfig.class); } public static ProjectConfig parseProjectConfig(String yaml) throws IOException { return parseYaml(yaml, ProjectConfig.class); } private static <T> T parseYaml(File file, Class<T> clazz) throws IOException { ObjectMapper mapper = createObjectMapper(); return mapper.readValue(file, clazz); } static <T> List<T> parseYamlValues(File file, Class<T> clazz) throws IOException { ObjectMapper mapper = createObjectMapper(); MappingIterator<T> iter = mapper.readerFor(clazz).readValues(file); List<T> answer = new ArrayList<>(); while (iter.hasNext()) { answer.add(iter.next()); } return answer; } private static <T> T parseYaml(InputStream inputStream, Class<T> clazz) throws IOException { ObjectMapper mapper = createObjectMapper(); return mapper.readValue(inputStream, clazz); } private static <T> T parseYaml(String yaml, Class<T> clazz) throws IOException { ObjectMapper mapper = createObjectMapper(); return mapper.readValue(yaml, clazz); } /** * Saves the fabric8.yml file to the given project directory */ public static boolean saveToFolder(File basedir, ProjectConfig config, boolean overwriteIfExists) throws IOException { File file = new File(basedir, ProjectConfigs.FILE_NAME); if (file.exists()) { if (!overwriteIfExists) { LOG.warn("Not generating " + file + " as it already exists"); return false; } } return saveConfig(config, file); } /** * Saves the configuration as YAML in the given file */ public static boolean saveConfig(ProjectConfig config, File file) throws IOException { createObjectMapper().writeValue(file, config); return true; } /** * Configures the given {@link ProjectConfig} with a map of key value pairs from * something like a JBoss Forge command */ public static void configureProperties(ProjectConfig config, Map map) { Class<? extends ProjectConfig> clazz = config.getClass(); BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(clazz); } catch (IntrospectionException e) { LOG.warn("Could not introspect " + clazz.getName() + ". " + e, e); } if (beanInfo != null) { PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor descriptor : propertyDescriptors) { Method writeMethod = descriptor.getWriteMethod(); if (writeMethod != null) { String name = descriptor.getName(); Object value = map.get(name); if (value != null) { Object safeValue = null; Class<?> propertyType = descriptor.getPropertyType(); if (propertyType.isInstance(value)) { safeValue = value; } else { PropertyEditor editor = descriptor.createPropertyEditor(config); if (editor == null) { editor = PropertyEditorManager.findEditor(propertyType); } if (editor != null) { String text = value.toString(); editor.setAsText(text); safeValue = editor.getValue(); } else { LOG.warn("Cannot update property " + name + " with value " + value + " of type " + propertyType.getName() + " on " + clazz.getName()); } } if (safeValue != null) { try { writeMethod.invoke(config, safeValue); } catch (Exception e) { LOG.warn("Failed to set property " + name + " with value " + value + " on " + clazz.getName() + " " + config + ". " + e, e); } } } } } } String flow = null; Object flowValue = map.get("flow"); if (flowValue != null) { flow = flowValue.toString(); } config.setFlow(flow); } /** * If no environments have been configured lets default them from the `FABRIC8_DEFAULT_ENVIRONMENTS` environment variable */ public static void defaultEnvironments(ProjectConfig config) { if (config != null) { String buildName = config.getBuildName(); if (Strings.isNotBlank(buildName) && Maps.isNullOrEmpty(config.getEnvironments())) { // lets default the environments from env var String defaultEnvironmentsText = Systems.getEnvVarOrSystemProperty("FABRIC8_DEFAULT_ENVIRONMENTS", "Staging=${buildName}-staging,Production=${buildName}-prod"); String text = Strings.replaceAllWithoutRegex(defaultEnvironmentsText, "${buildName}", buildName); Map<String,String> environments = Maps.parseMap(text); config.setEnvironments(environments); } } } }
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.xslt; import java.io.StringReader; import java.io.StringWriter; import java.util.Properties; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileType; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Executes a XSL Transform on the values in the input stream. * * @author Samatar * @since 15-Oct-2007 * */ public class Xslt extends BaseStep implements StepInterface { private static Class<?> PKG = XsltMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private XsltMeta meta; private XsltData data; static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; public Xslt(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(XsltMeta)smi; data=(XsltData)sdi; Object[] row = getRow(); if (row==null) // no more input to be expected... { setOutputDone(); return false; } if (first) { first=false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); // Check if The result field is given if (Const.isEmpty(meta.getResultfieldname())) { // Result Field is missing ! logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ErrorResultFieldMissing")); } // Check if The XML field is given if (Const.isEmpty(meta.getFieldname())) { // Result Field is missing ! logError(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXMLFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXMLFieldMissing")); } // Try to get XML Field index data.fieldposition = getInputRowMeta().indexOfValue(meta.getFieldname()); // Let's check the Field if (data.fieldposition<0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorFindingField")+ "[" + meta.getFieldname()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.CouldnotFindField",meta.getFieldname())); //$NON-NLS-1$ //$NON-NLS-2$ } // Check if the XSL Filename is contained in a column if (meta.useXSLField()) { if (Const.isEmpty(meta.getXSLFileField())) { // The field is missing // Result field is missing ! logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorXSLFileFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXSLFileFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ } // Try to get Field index data.fielxslfiledposition = getInputRowMeta().indexOfValue(meta.getXSLFileField()); // Let's check the Field if (data.fielxslfiledposition<0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorXSLFileFieldFinding")+ "[" + meta.getXSLFileField()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXSLFileFieldFinding",meta.getXSLFileField())); //$NON-NLS-1$ //$NON-NLS-2$ } }else { if(Const.isEmpty(meta.getXslFilename())) { logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorXSLFile")); throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXSLFile")); } // Check if XSL File exists! data.xslfilename = environmentSubstitute(meta.getXslFilename()); FileObject file=null; try { file=KettleVFS.getFileObject(data.xslfilename); if(!file.exists()) { logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorXSLFileNotExists",data.xslfilename)); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXSLFileNotExists",data.xslfilename)); //$NON-NLS-1$ //$NON-NLS-2$ } if(file.getType()!=FileType.FILE) { logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorXSLNotAFile",data.xslfilename)); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXSLNotAFile",data.xslfilename)); //$NON-NLS-1$ //$NON-NLS-2$ } }catch(Exception e) { throw new KettleStepException(e); } finally { try { if(file!=null) file.close(); }catch(Exception e){}; } } // Check output parameters int nrOutputProps= meta.getOutputPropertyName()==null?0:meta.getOutputPropertyName().length; if(nrOutputProps>0) { data.outputProperties= new Properties(); for(int i=0; i<nrOutputProps; i++) { data.outputProperties.put(meta.getOutputPropertyName()[i], environmentSubstitute(meta.getOutputPropertyValue()[i])); } data.setOutputProperties=true; } // Check parameters data.nrParams= meta.getParameterField()==null?0:meta.getParameterField().length; if(data.nrParams>0) { data.indexOfParams = new int[data.nrParams]; data.nameOfParams = new String[data.nrParams]; for(int i=0; i<data.nrParams; i++) { String name = environmentSubstitute(meta.getParameterName()[i]); String field = environmentSubstitute(meta.getParameterField()[i]); if(Const.isEmpty(field)) { throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ParameterFieldMissing", name, i)); } data.indexOfParams[i]=getInputRowMeta().indexOfValue(field); if(data.indexOfParams[i]<0) { throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ParameterFieldNotFound", name)); } data.nameOfParams[i]=name; } data.useParameters=true; } data.factory = TransformerFactory.newInstance(); if (meta.getXSLFactory().equals("SAXON")){ // Set the TransformerFactory to the SAXON implementation. data.factory = (TransformerFactory) new net.sf.saxon.TransformerFactoryImpl(); } }// end if first // Get the field value String xmlValue= getInputRowMeta().getString(row,data.fieldposition); if (meta.useXSLField()) { // Get the value data.xslfilename= getInputRowMeta().getString(row,data.fielxslfiledposition); if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "Xslt.Log.XslfileNameFromFied",data.xslfilename,meta.getXSLFileField())); } try { if(log.isDetailed()) { if(meta.isXSLFieldIsAFile()) logDetailed(BaseMessages.getString(PKG, "Xslt.Log.Filexsl") + data.xslfilename); else logDetailed(BaseMessages.getString(PKG, "Xslt.Log.XslStream", data.xslfilename)); } // Get the template from the cache Transformer transformer = data.getTemplate(data.xslfilename, meta.isXSLFieldIsAFile()); // Do we need to set output properties? if(data.setOutputProperties) { transformer.setOutputProperties(data.outputProperties); } // Do we need to pass parameters? if(data.useParameters) { for(int i=0; i<data.nrParams; i++) { transformer.setParameter(data.nameOfParams[i], row[data.indexOfParams[i]]); } } Source source = new StreamSource(new StringReader(xmlValue)); // Prepare output stream StreamResult result = new StreamResult(new StringWriter()); // transform xml source transformer.transform(source, result); String xmlString = result.getWriter().toString(); if(log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "Xslt.Log.FileResult")); logDetailed(xmlString); } Object[] outputRowData =RowDataUtil.addValueData(row, getInputRowMeta().size(),xmlString); if (log.isRowLevel()) { logRowlevel(BaseMessages.getString(PKG, "Xslt.Log.ReadRow") + " " + getInputRowMeta().getString(row)); } // add new values to the row. putRow(data.outputRowMeta, outputRowData); // copy row to output rowset(s); } catch (Exception e) { boolean sendToErrorRow=false; String errorMessage = null; if (getStepMeta().isDoingErrorHandling()) { sendToErrorRow = true; errorMessage = e.getMessage(); } if (sendToErrorRow) { // Simply add this row to the error row putError(getInputRowMeta(), row, 1, errorMessage, meta.getResultfieldname(), "XSLT01"); } else { logError(BaseMessages.getString(PKG, "Xslt.ErrorProcesing" + " : "+ e.getMessage())); throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.ErrorProcesing"), e); } } return true; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(XsltMeta)smi; data=(XsltData)sdi; if (super.init(smi, sdi)) { // Add init code here. return true; } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta = (XsltMeta)smi; data = (XsltData)sdi; data.dispose(); super.dispose(smi, sdi); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.rcfile; import com.facebook.presto.rcfile.RcFileCompressor.CompressedSliceOutput; import com.facebook.presto.rcfile.RcFileWriteValidation.RcFileWriteValidationBuilder; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.type.Type; import com.google.common.io.Closer; import io.airlift.slice.DynamicSliceOutput; import io.airlift.slice.Slice; import io.airlift.slice.SliceOutput; import io.airlift.units.DataSize; import javax.annotation.Nullable; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Consumer; import static com.facebook.presto.rcfile.PageSplitterUtil.splitPage; import static com.facebook.presto.rcfile.RcFileDecoderUtils.writeLengthPrefixedString; import static com.facebook.presto.rcfile.RcFileDecoderUtils.writeVInt; import static com.facebook.presto.rcfile.RcFileReader.validateFile; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static io.airlift.slice.Slices.utf8Slice; import static io.airlift.units.DataSize.Unit.KILOBYTE; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static java.lang.StrictMath.toIntExact; import static java.util.Objects.requireNonNull; public class RcFileWriter implements Closeable { private static final Slice RCFILE_MAGIC = utf8Slice("RCF"); private static final int CURRENT_VERSION = 1; private static final String COLUMN_COUNT_METADATA_KEY = "hive.io.rcfile.column.number"; private static final DataSize DEFAULT_TARGET_MIN_ROW_GROUP_SIZE = new DataSize(4, MEGABYTE); private static final DataSize DEFAULT_TARGET_MAX_ROW_GROUP_SIZE = new DataSize(8, MEGABYTE); private static final DataSize MIN_BUFFER_SIZE = new DataSize(4, KILOBYTE); private static final DataSize MAX_BUFFER_SIZE = new DataSize(1, MEGABYTE); static final String PRESTO_RCFILE_WRITER_VERSION_METADATA_KEY = "presto.writer.version"; static final String PRESTO_RCFILE_WRITER_VERSION; static { String version = RcFileWriter.class.getPackage().getImplementationVersion(); PRESTO_RCFILE_WRITER_VERSION = version == null ? "UNKNOWN" : version; } private final SliceOutput output; private final List<Type> types; private final RcFileEncoding encoding; private final RcFileCodecFactory codecFactory; private final long syncFirst = ThreadLocalRandom.current().nextLong(); private final long syncSecond = ThreadLocalRandom.current().nextLong(); private CompressedSliceOutput keySectionOutput; private final ColumnEncoder[] columnEncoders; private final int targetMinRowGroupSize; private final int targetMaxRowGroupSize; private int bufferedSize; private int bufferedRows; private long totalRowCount; @Nullable private final RcFileWriteValidationBuilder validationBuilder; public RcFileWriter( SliceOutput output, List<Type> types, RcFileEncoding encoding, Optional<String> codecName, RcFileCodecFactory codecFactory, Map<String, String> metadata, boolean validate) throws IOException { this( output, types, encoding, codecName, codecFactory, metadata, DEFAULT_TARGET_MIN_ROW_GROUP_SIZE, DEFAULT_TARGET_MAX_ROW_GROUP_SIZE, validate); } public RcFileWriter( SliceOutput output, List<Type> types, RcFileEncoding encoding, Optional<String> codecName, RcFileCodecFactory codecFactory, Map<String, String> metadata, DataSize targetMinRowGroupSize, DataSize targetMaxRowGroupSize, boolean validate) throws IOException { requireNonNull(output, "output is null"); requireNonNull(types, "types is null"); checkArgument(!types.isEmpty(), "types is empty"); requireNonNull(encoding, "encoding is null"); requireNonNull(codecName, "codecName is null"); requireNonNull(codecFactory, "codecFactory is null"); requireNonNull(metadata, "metadata is null"); checkArgument(!metadata.containsKey(PRESTO_RCFILE_WRITER_VERSION_METADATA_KEY), "Cannot set property %s", PRESTO_RCFILE_WRITER_VERSION_METADATA_KEY); checkArgument(!metadata.containsKey(COLUMN_COUNT_METADATA_KEY), "Cannot set property %s", COLUMN_COUNT_METADATA_KEY); requireNonNull(targetMinRowGroupSize, "targetMinRowGroupSize is null"); requireNonNull(targetMaxRowGroupSize, "targetMaxRowGroupSize is null"); checkArgument(targetMinRowGroupSize.compareTo(targetMaxRowGroupSize) <= 0, "targetMinRowGroupSize must be less than or equal to targetMaxRowGroupSize"); this.validationBuilder = validate ? new RcFileWriteValidationBuilder(types) : null; this.output = output; this.types = types; this.encoding = encoding; this.codecFactory = codecFactory; // write header output.writeBytes(RCFILE_MAGIC); output.writeByte(CURRENT_VERSION); recordValidation(validation -> validation.setVersion((byte) CURRENT_VERSION)); // write codec information output.writeBoolean(codecName.isPresent()); codecName.ifPresent(name -> writeLengthPrefixedString(output, utf8Slice(name))); recordValidation(validation -> validation.setCodecClassName(codecName)); // write metadata output.writeInt(Integer.reverseBytes(metadata.size() + 2)); writeMetadataProperty(COLUMN_COUNT_METADATA_KEY, Integer.toString(types.size())); writeMetadataProperty(PRESTO_RCFILE_WRITER_VERSION_METADATA_KEY, PRESTO_RCFILE_WRITER_VERSION); for (Entry<String, String> entry : metadata.entrySet()) { writeMetadataProperty(entry.getKey(), entry.getValue()); } // write sync sequence output.writeLong(syncFirst); recordValidation(validation -> validation.setSyncFirst(syncFirst)); output.writeLong(syncSecond); recordValidation(validation -> validation.setSyncSecond(syncSecond)); // initialize columns RcFileCompressor compressor = codecName.map(codecFactory::createCompressor).orElse(new NoneCompressor()); keySectionOutput = compressor.createCompressedSliceOutput((int) MIN_BUFFER_SIZE.toBytes(), (int) MAX_BUFFER_SIZE.toBytes()); keySectionOutput.close(); // output is recycled on first use which requires output to be closed columnEncoders = new ColumnEncoder[types.size()]; for (int columnIndex = 0; columnIndex < types.size(); columnIndex++) { Type type = types.get(columnIndex); ColumnEncoding columnEncoding = encoding.getEncoding(type); columnEncoders[columnIndex] = new ColumnEncoder(columnEncoding, compressor); } this.targetMinRowGroupSize = toIntExact(targetMinRowGroupSize.toBytes()); this.targetMaxRowGroupSize = toIntExact(targetMaxRowGroupSize.toBytes()); } private void writeMetadataProperty(String key, String value) { writeLengthPrefixedString(output, utf8Slice(key)); writeLengthPrefixedString(output, utf8Slice(value)); recordValidation(validation -> validation.addMetadataProperty(key, value)); } @Override public void close() throws IOException { try (Closer closer = Closer.create()) { closer.register(output); closer.register(keySectionOutput::destroy); for (ColumnEncoder columnEncoder : columnEncoders) { closer.register(columnEncoder::destroy); } writeRowGroup(); } } private void recordValidation(Consumer<RcFileWriteValidationBuilder> task) { if (validationBuilder != null) { task.accept(validationBuilder); } } public void validate(RcFileDataSource input) throws RcFileCorruptionException { checkState(validationBuilder != null, "validation is not enabled"); validateFile( validationBuilder.build(), input, encoding, types, codecFactory); } public long getRetainedSizeInBytes() { long retainedSize = 0; retainedSize += output.getRetainedSize(); retainedSize += keySectionOutput.getRetainedSize(); for (ColumnEncoder columnEncoder : columnEncoders) { retainedSize += columnEncoder.getRetainedSizeInBytes(); } return retainedSize; } public void write(Page page) throws IOException { if (page.getPositionCount() == 0) { return; } List<Page> pages = splitPage(page, targetMaxRowGroupSize); for (Page splitPage : pages) { bufferPage(splitPage); } } private void bufferPage(Page page) throws IOException { bufferedRows += page.getPositionCount(); bufferedSize = 0; Block[] blocks = page.getBlocks(); for (int i = 0; i < blocks.length; i++) { Block block = blocks[i]; columnEncoders[i].writeBlock(block); bufferedSize += columnEncoders[i].getBufferedSize(); } recordValidation(validation -> validation.addPage(page)); if (bufferedSize >= targetMinRowGroupSize) { writeRowGroup(); } } private void writeRowGroup() throws IOException { if (bufferedRows == 0) { return; } // write sync sequence for every row group except for the first row group if (totalRowCount != 0) { output.writeInt(-1); output.writeLong(syncFirst); output.writeLong(syncSecond); } // flush and compress each column for (ColumnEncoder columnEncoder : columnEncoders) { columnEncoder.closeColumn(); } // build key section int valueLength = 0; keySectionOutput = keySectionOutput.createRecycledCompressedSliceOutput(); try { writeVInt(keySectionOutput, bufferedRows); recordValidation(validation -> validation.addRowGroup(bufferedRows)); for (ColumnEncoder columnEncoder : columnEncoders) { valueLength += columnEncoder.getCompressedSize(); writeVInt(keySectionOutput, columnEncoder.getCompressedSize()); writeVInt(keySectionOutput, columnEncoder.getUncompressedSize()); Slice lengthData = columnEncoder.getLengthData(); writeVInt(keySectionOutput, lengthData.length()); keySectionOutput.writeBytes(lengthData); } } finally { keySectionOutput.close(); } // write the sum of the uncompressed key length and compressed value length // this number is useless to the reader output.writeInt(Integer.reverseBytes(keySectionOutput.size() + valueLength)); // write key section output.writeInt(Integer.reverseBytes(keySectionOutput.size())); output.writeInt(Integer.reverseBytes(keySectionOutput.getCompressedSize())); for (Slice slice : keySectionOutput.getCompressedSlices()) { output.writeBytes(slice); } // write value section for (ColumnEncoder columnEncoder : columnEncoders) { List<Slice> slices = columnEncoder.getCompressedData(); for (Slice slice : slices) { output.writeBytes(slice); } columnEncoder.reset(); } totalRowCount += bufferedRows; bufferedSize = 0; bufferedRows = 0; } private static class ColumnEncoder { private final ColumnEncoding columnEncoding; private ColumnEncodeOutput encodeOutput; private final SliceOutput lengthOutput = new DynamicSliceOutput(512); private CompressedSliceOutput output; private boolean columnClosed; public ColumnEncoder(ColumnEncoding columnEncoding, RcFileCompressor compressor) { this.columnEncoding = columnEncoding; this.output = compressor.createCompressedSliceOutput((int) MIN_BUFFER_SIZE.toBytes(), (int) MAX_BUFFER_SIZE.toBytes()); this.encodeOutput = new ColumnEncodeOutput(lengthOutput, output); } private void writeBlock(Block block) throws IOException { checkArgument(!columnClosed, "Column is closed"); columnEncoding.encodeColumn(block, output, encodeOutput); } public void closeColumn() throws IOException { checkArgument(!columnClosed, "Column is not open"); encodeOutput.flush(); output.close(); columnClosed = true; } public int getBufferedSize() { return lengthOutput.size() + output.size(); } public Slice getLengthData() { checkArgument(columnClosed, "Column is open"); return lengthOutput.slice(); } public int getUncompressedSize() { checkArgument(columnClosed, "Column is open"); return output.size(); } public int getCompressedSize() { checkArgument(columnClosed, "Column is open"); return output.getCompressedSize(); } public List<Slice> getCompressedData() { checkArgument(columnClosed, "Column is open"); return output.getCompressedSlices(); } public void reset() { checkArgument(columnClosed, "Column is open"); lengthOutput.reset(); output = output.createRecycledCompressedSliceOutput(); encodeOutput = new ColumnEncodeOutput(lengthOutput, output); columnClosed = false; } public void destroy() throws IOException { output.destroy(); } public long getRetainedSizeInBytes() { return lengthOutput.getRetainedSize() + output.getRetainedSize(); } private static class ColumnEncodeOutput implements EncodeOutput { private final SliceOutput lengthOutput; private final SliceOutput valueOutput; private int previousOffset; private int previousLength; private int runLength; public ColumnEncodeOutput(SliceOutput lengthOutput, SliceOutput valueOutput) { this.lengthOutput = lengthOutput; this.valueOutput = valueOutput; this.previousOffset = valueOutput.size(); this.previousLength = -1; } @Override public void closeEntry() { int offset = valueOutput.size(); int length = offset - previousOffset; previousOffset = offset; if (length == previousLength) { runLength++; } else { if (runLength > 0) { int value = ~runLength; writeVInt(lengthOutput, value); } writeVInt(lengthOutput, length); previousLength = length; runLength = 0; } } private void flush() { if (runLength > 0) { int value = ~runLength; writeVInt(lengthOutput, value); } previousLength = -1; runLength = 0; } } } }
/* * Copyright 2013-2021 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package example.springdata.jpa.simple; import static org.assertj.core.api.Assertions.*; import static org.springframework.data.domain.Sort.Direction.*; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * Integration test showing the basic usage of {@link SimpleUserRepository}. * * @author Oliver Gierke * @author Thomas Darimont * @author Christoph Strobl * @author Divya Srivastava * @author Jens Schauder */ @Transactional @SpringBootTest @Slf4j class SimpleUserRepositoryTests { @Autowired SimpleUserRepository repository; private User user; @BeforeEach void setUp() { user = new User(); user.setUsername("foobar"); user.setFirstname("firstname"); user.setLastname("lastname"); } @Test void findSavedUserById() { user = repository.save(user); assertThat(repository.findById(user.getId())).hasValue(user); } @Test void findSavedUserByLastname() { user = repository.save(user); assertThat(repository.findByLastname("lastname")).contains(user); } @Test void findByFirstnameOrLastname() { user = repository.save(user); assertThat(repository.findByFirstnameOrLastname("lastname")).contains(user); } @Test void useOptionalAsReturnAndParameterType() { assertThat(repository.findByUsername(Optional.of("foobar"))).isEmpty(); repository.save(user); assertThat(repository.findByUsername(Optional.of("foobar"))).isPresent(); } @Test void removeByLastname() { // create a 2nd user with the same lastname as user var user2 = new User(); user2.setLastname(user.getLastname()); // create a 3rd user as control group var user3 = new User(); user3.setLastname("no-positive-match"); repository.saveAll(Arrays.asList(user, user2, user3)); assertThat(repository.removeByLastname(user.getLastname())).isEqualTo(2L); assertThat(repository.existsById(user3.getId())).isTrue(); } @Test void useSliceToLoadContent() { repository.deleteAll(); // int repository with some values that can be ordered var totalNumberUsers = 11; List<User> source = new ArrayList<>(totalNumberUsers); for (var i = 1; i <= totalNumberUsers; i++) { var user = new User(); user.setLastname(this.user.getLastname()); user.setUsername(user.getLastname() + "-" + String.format("%03d", i)); source.add(user); } repository.saveAll(source); var users = repository.findByLastnameOrderByUsernameAsc(this.user.getLastname(), PageRequest.of(1, 5)); assertThat(users).containsAll(source.subList(5, 10)); } @Test void findFirst2ByOrderByLastnameAsc() { var user0 = new User(); user0.setLastname("lastname-0"); var user1 = new User(); user1.setLastname("lastname-1"); var user2 = new User(); user2.setLastname("lastname-2"); // we deliberatly save the items in reverse repository.saveAll(Arrays.asList(user2, user1, user0)); var result = repository.findFirst2ByOrderByLastnameAsc(); assertThat(result).containsExactly(user0, user1); } @Test void findTop2ByWithSort() { var user0 = new User(); user0.setLastname("lastname-0"); var user1 = new User(); user1.setLastname("lastname-1"); var user2 = new User(); user2.setLastname("lastname-2"); // we deliberately save the items in reverse repository.saveAll(Arrays.asList(user2, user1, user0)); var resultAsc = repository.findTop2By(Sort.by(ASC, "lastname")); assertThat(resultAsc).containsExactly(user0, user1); var resultDesc = repository.findTop2By(Sort.by(DESC, "lastname")); assertThat(resultDesc).containsExactly(user2, user1); } @Test void findByFirstnameOrLastnameUsingSpEL() { var first = new User(); first.setLastname("lastname"); var second = new User(); second.setFirstname("firstname"); var third = new User(); repository.saveAll(Arrays.asList(first, second, third)); var reference = new User(); reference.setFirstname("firstname"); reference.setLastname("lastname"); var users = repository.findByFirstnameOrLastname(reference); assertThat(users).containsExactly(first, second); } /** * Streaming data from the store by using a repository method that returns a {@link Stream}. Note, that since the * resulting {@link Stream} contains state it needs to be closed explicitly after use! */ @Test void useJava8StreamsWithCustomQuery() { var user1 = repository.save(new User("Customer1", "Foo")); var user2 = repository.save(new User("Customer2", "Bar")); try (var stream = repository.streamAllCustomers()) { assertThat(stream.collect(Collectors.toList())).contains(user1, user2); } } /** * Streaming data from the store by using a repository method that returns a {@link Stream} with a derived query. * Note, that since the resulting {@link Stream} contains state it needs to be closed explicitly after use! */ @Test void useJava8StreamsWithDerivedQuery() { var user1 = repository.save(new User("Customer1", "Foo")); var user2 = repository.save(new User("Customer2", "Bar")); try (var stream = repository.findAllByLastnameIsNotNull()) { assertThat(stream.collect(Collectors.toList())).contains(user1, user2); } } /** * Query methods using streaming need to be used inside a surrounding transaction to keep the connection open while * the stream is consumed. We simulate that not being the case by actively disabling the transaction here. */ @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) void rejectsStreamExecutionIfNoSurroundingTransactionActive() { Assertions.assertThrows(InvalidDataAccessApiUsageException.class, () -> { repository.findAllByLastnameIsNotNull(); }); } /** * Here we demonstrate the usage of {@link CompletableFuture} as a result wrapper for asynchronous repository query * methods. Note, that we need to disable the surrounding transaction to be able to asynchronously read the written * data from from another thread within the same test method. */ @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) void supportsCompletableFuturesAsReturnTypeWrapper() throws Exception { repository.save(new User("Customer1", "Foo")); repository.save(new User("Customer2", "Bar")); var future = repository.readAllBy().thenAccept(users -> { assertThat(users).hasSize(2); users.forEach(customer -> log.info(customer.toString())); log.info("Completed!"); }); while (!future.isDone()) { log.info("Waiting for the CompletableFuture to finish..."); TimeUnit.MILLISECONDS.sleep(500); } future.get(); log.info("Done!"); repository.deleteAll(); } }
package experiment.value.bargossipMobile; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.function.Predicate; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.core.CommonState; import peersim.core.Network; import peersim.core.Node; import seine.annotations.Collusion; import seine.annotations.Defection; import seine.annotations.Misreport; import seine.annotations.Resource; import seine.annotations.Seine; /** * This class is an implementation of the <em>BAR Gossip</em> protocol for P2P live streaming. * * In this implementation of the protocol, the time is split in rounds. Every round, a special node called * the Source creates a set of {@link Update} objects and disseminates them to a fanout of other nodes. * Also, at every round, each node i proposes its unexpired updates to two neighbours selected using a deterministic * pseudo-random number generator. With the neighbour j1, i establishes the balanced exchange protocol; with the * neighbour j2, i established the optimistic push protocol. * * @author Guido Lena Cota */ @Seine public class BarGossipMobile implements CDProtocol { /** * Protocol type. */ private enum ProtocolType { UNDEFINED, BALANCED_EXCHANGE, OPTIMISTIC_PUSH } // CONSTANTS // ------------------------------------------------------------------------------------------------ /** * The size of the HASH (SHA-1). */ private static final int HASH_SIZE = 160; /** * The size of the signature (RSA 1024), in bits. */ private static final int SIGN_SIZE = 1024; /** * The overhead of the message header, in bytes. (16 bits of UDP + 160 bits of IPv4) */ public static final int MESSAGE_HEADER_OVERHEAD = 22; /** * Maximum number of tries to select a new partner. */ private static final short MAX_NR_TRIES = 10; /** * The size of the network. */ private static final int NW_SIZE = Network.size(); /** * The size of the oldList if colluders. */ private static final int OLD_LIST_SIZE = 1; // PARAMETERS // ------------------------------------------------------------------------------------------ /** * The playback deadline, i.e., the maximum allowed time (in rounds) between the creation of a * video {@link Update} and its playback. Updates received after their playback deadline are * discarded. */ private static final String PAR_UPD_DL = "upd_dl"; /** * The maximum number of {@link Update}s that a peer is willing to disseminate in a round * through Balanced Exchange. */ private static final String PAR_BAL_SIZE = "bal_size"; /** * The maximum length of the receiver's 'want' list. */ private static final String PAR_PUSH_SIZE = "push_size"; /** * The maximum age of updates sent in the 'young' list of the sender. */ private static final String PAR_PUSH_AGE = "push_age"; /** * The relative cost of sending a junk update divided by the cost of sending the largest * update in the stream. */ private static final String PAR_C_JUNK = "c_junk"; /** * The size of an {@link Update} in average, in bytes. */ private static final String PAR_UPD_SIZE = "upd_size"; // MESSAGES // ------------------------------------------------------------------------------------------------ /** * The instance used for the BAL message. */ private Message balMessage; /** * The instance used for the BAL_RESP message. */ private Message balRespMessage; /** * The instance used for the DIVULGE message. */ private Message divulgeMessage; /** * The instance used for the BRIEF message. */ private Message briefMessage; /** * The instance used for the KEY exchange messages. */ private Message keyExchangeMessage; /** * The instance used for the PUSH message. */ private Message pushMessage; /** * The instance used for the PUSH_RESP message. */ private Message pushRespMessage; // FIELDS // ------------------------------------------------------------------------------------------ /** * The maximum number of {@link Update}s that a peer is willing to disseminate in a round * through Balanced Exchange, as specfied in {@link PAR_BAL_SIZE}. */ private final short bal_size; /** * The maximum length of the receiver's 'want' list, as specfied in {@link PAR_PUSH_SIZE}. */ private final short push_size; /** * The maximum age of updates sent in the 'young' list of the sender, as specfied in {@link PAR_PUSH_AGE}. */ private final short push_age; /** * The relative cost of sending a junk update divided by the cost of sending the largest * update in the stream, as specfied in {@link PAR_C_JUNK}. */ private final double c_junk; /* Attributes of updates */ /** * The size of an {@link Update} in average, in bytes, as specified in {@link PAR_UPD_SIZE}. */ private final short upd_size; /** * The playback deadline of media {@link Update}s, as specified in {@link PAR_UPD_DL}. */ private final short upd_dl; /* Attributes of the source node */ /** * The fraction of the network connected with the source, as specified in {@link PAR_BCAST_HR}. */ private double bcast_hr; /** * The number of {@link Update}s sent every round by the source, as specified in {@link PAR_BCAST_CNT}. */ private short bcast_cnt; /** * True if this node is the source node. */ private boolean isSource; /** * The set of communication partners. */ private Set<BarGossipMobile> partners; /* Attributes of all nodes */ /** * The size of the media stream, stored as number of {@link Update}, and set by {@link StreamingInit}. */ private TreeSet<Update> updates; /** * The set of unexpired {@link Update}s that can be exchanged by peers. */ private TreeSet<Update> transmissibleUpdates; /** * The set of {@link Update}s that are sent during the data exchange. */ private TreeSet<Update> briefcase; /** * The per-cycle upload bandwidth capacity of the local node, set by {@link StreamingInit} */ private long bandwidthCapacity; @Resource private long uploadBandwidth; /** * True if the node has been evicted; false otherwise. */ private boolean isEvicted; /** * True if it has to be evicted by the source at the next round. */ private boolean toEvict; private boolean startDataExchange; private boolean cooperateOnStartOptimisticPushProtocol; // private boolean cooperateOnDoSendPUSH; private boolean cooperateOnDoSendPUSH_RESP; private boolean cooperateOnDoSendBRIEF; /** * Trace the type of protocol running at the current moment. */ private ProtocolType runningProtocol; /* Support variables for debugging */ public long sentChunksInBE2coop = 0; public long sentChunksInBE2self = 0; public long sentChunksInOP2coop = 0; public long sentChunksInOP2self = 0; public long receivedChunksInBE = 0; public long receivedChunksInOP = 0; // INITIALIZATION // ------------------------------------------------------------------------------------------ /** * Standard constructor invoked by the simulation engine. * @param prefix: the configuration prefix for this class. */ public BarGossipMobile(String prefix) { c_junk = Configuration.getDouble(prefix + "." + PAR_C_JUNK, 2); bal_size = (short) Configuration.getInt(prefix + "." + PAR_BAL_SIZE, 1); push_size = (short) Configuration.getInt(prefix + "." + PAR_PUSH_SIZE, 1); push_age = (short) Configuration.getInt(prefix + "." + PAR_PUSH_AGE, 1); upd_dl = (short) Configuration.getInt(prefix + "." + PAR_UPD_DL, 10); /* updates parameters */ transmissibleUpdates = new TreeSet<Update>(new UpdateById()); updates = new TreeSet<Update>(new UpdateById()); briefcase = new TreeSet<Update>(new UpdateById()); upd_size = (short) Configuration.getInt(prefix + "." + PAR_UPD_SIZE, 1024); isEvicted = false; toEvict = false; } @Override public BarGossipMobile clone(){ BarGossipMobile bg = null; try { bg = (BarGossipMobile) super.clone(); bg.transmissibleUpdates = new TreeSet<Update>(new UpdateById()); bg.updates = new TreeSet<Update>(new UpdateById()); bg.briefcase = new TreeSet<Update>(new UpdateById()); } catch (CloneNotSupportedException e) {} // never happens return bg; } // METHODS implementing the BAR Gossip protocols // ------------------------------------------------------------------------------------------------ /** * Implement the BAR Gossip protocols. * * @param node: the node on which this component is run. * @param protocolID: the id of this protocol in the protocol array. */ @Override public void nextCycle(Node node, int protocolID) { /* the node is the source */ if(isSource) { selectSourcePartners(protocolID); doStreaming(); return; } /* if the node is a peer */ else if(CommonState.getTime() > 0){ // execute the Balanced Exchange protocol startBalancedExchangeProtocol(protocolID); // execute the Optimistic Pusg protocol startOptimisticPushProtocol(protocolID); } } /* SOURCE METHODS */ /** * Simulate the streaming of the {@link PAR_BCAST_CNT} updates during the current cycle. */ private void doStreaming(){ // get the set of updates to stream at this cycle TreeSet<Update> updatesToStream = getStreamableUpdates(transmissibleUpdates, (int) CommonState.getTime()); // create the message Message streamingMessage = new Message(Message.STREAMING, this, null, updatesToStream, null, 0); for(BarGossipMobile partner : partners){ // send a set of Update objects int bandwidthConsumption = MESSAGE_HEADER_OVERHEAD + bcast_cnt * upd_size; // send a message to the selected peer with the set of updates to stream partner.handleMessage(streamingMessage, bandwidthConsumption); } updatesToStream = null; } /* PEERS METHODS */ /* Balanced Exchange */ /** * Simulate the execution of the balanced exchange protocol. */ public void startBalancedExchangeProtocol(int protocolID){ if(uploadBandwidth < 0 || transmissibleUpdates.isEmpty()) return; BarGossipMobile receiver = selectPeerPartner(protocolID); // if a partner was found and there are updates to share if(receiver != null){ resetMessages(this); resetMessages(receiver); // send a BAL message to the communication partner doSendBAL(receiver); // verify if the protocol execution was successful verifySuccessProtocolExecution(ProtocolType.BALANCED_EXCHANGE, this, receiver); } } /** * [SENDER] Implement the BAL step of the History Exchange phase of the balanced exchange protocol. */ public void doSendBAL(BarGossipMobile receiver){ // create the message balMessage = new Message(Message.BAL, this, receiver, transmissibleUpdates, null, 0); // send a message to the selected peer with the hash of the description of updates to propose int bandwidthConsumption = MESSAGE_HEADER_OVERHEAD + (HASH_SIZE + SIGN_SIZE) / 8; receiver.handleMessage(balMessage, bandwidthConsumption); } /** * [RECEIVER] Implement the BAL_RESP step of the History Exchange phase of the balanced exchange protocol. */ public void doSendBAL_RESP(BarGossipMobile sender){ // create the message balRespMessage = new Message(Message.BAL_RESP, this, sender, transmissibleUpdates, null, 0); // send a message to the selected peer with the set of updates to propose int bandwidthConsumption = MESSAGE_HEADER_OVERHEAD + transmissibleUpdates.size() * (Integer.SIZE / 8) + SIGN_SIZE / 8; sender.handleMessage(balRespMessage, bandwidthConsumption); } /** * [SENDER] Implement the DIVULGE step of the History Exchange phase of the balanced exchange protocol. */ private void doSendDIVULGE(BarGossipMobile receiver){ // create the message divulgeMessage = new Message(Message.DIVULGE, this, receiver, balMessage.getContent1(), null, 0); // send a message to the selected peer with the set of updates to propose int bandwidthConsumption = MESSAGE_HEADER_OVERHEAD + balMessage.getContent1().size() * (Integer.SIZE / 8) + SIGN_SIZE / 8; receiver.handleMessage(divulgeMessage, bandwidthConsumption); } /* Optimistic Push */ /** * Simulate the execution of the optimistic push protocol. */ @Defection public void startOptimisticPushProtocol(int protocolID){ if(uploadBandwidth <= 0) return; BarGossipMobile receiver = selectPeerPartner(protocolID); // if a partner was found and there are updates to share if(receiver != null){ resetMessages(this); resetMessages(receiver); cooperateOnStartOptimisticPushProtocol = true; createPUSHMessage(receiver); // send a PUSH message to the communication partner doSendPUSH(receiver); // verify if the protocol execution was successful verifySuccessProtocolExecution(ProtocolType.OPTIMISTIC_PUSH, this, receiver); } } /** * [SENDER] Implement the PUSH step of the History Exchange phase of the optimistic push protocol. */ @Collusion ( mtd_colluder = "createPUSHMessage_colluder" , mtd_not_colluder="cooperate") public void createPUSHMessage(BarGossipMobile receiver){ // create the message pushMessage = new Message(Message.PUSH, this, receiver, getYoungList(), getOldList(1), SIGN_SIZE); } public void createPUSHMessage_notcolluder(BarGossipMobile receiver){ // create the message with an empty youngList pushMessage = new Message(Message.PUSH, this, receiver, new TreeSet<Update>(), getOldList(1), SIGN_SIZE); } public void createPUSHMessage_colluder(BarGossipMobile receiver){ // create the message pushMessage = new Message(Message.PUSH, this, receiver, new TreeSet<Update>(transmissibleUpdates), getOldList(OLD_LIST_SIZE), SIGN_SIZE); } public void doSendPUSH(BarGossipMobile receiver){ // send a message to the RECEIVER with the updates to propose (young) and to request (old) int bandwidthConsumption = MESSAGE_HEADER_OVERHEAD + (pushMessage.getContent1().size() + pushMessage.getContent2().size()) * (Integer.SIZE / 8) + SIGN_SIZE / 8; receiver.handleMessage(pushMessage, bandwidthConsumption); } /** * [RECEIVER] Implement the PUSH_RESP step of the History Exchange phase of the optimistic push protocol. */ @Misreport (ref_arg = 1) @Defection public void doSendPUSH_RESP(BarGossipMobile sender, TreeSet<Update> content){ TreeSet<Update> wantList = new TreeSet<Update>(sender.pushMessage.getContent1()); wantList.removeAll(transmissibleUpdates); cooperateOnDoSendPUSH_RESP = content.equals(wantList); // create the message pushRespMessage = new Message(Message.PUSH_RESP, this, sender, content, null, 0); // send a message to the SENDER with the updates that it wants from it (extracted from the young list) int bandwidthConsumption = MESSAGE_HEADER_OVERHEAD + content.size() * (Integer.SIZE / 8) + SIGN_SIZE / 8; sender.handleMessage(pushRespMessage, bandwidthConsumption); } /** * Create the briefcases to send to the partner during the Data Exchange phase of the balanced exchange protocol. */ public boolean createBEbriefcases(BarGossipMobile sender, BarGossipMobile receiver){ // SENDER's briefcase: the updates that RECEIVER does not have, but SENDER does // = SENDER.DIVULGE.content1 - RECEIVER.BAL_RESP.content1 sender.briefcase = new TreeSet<Update>(sender.divulgeMessage.getContent1()); sender.briefcase.removeAll(receiver.balRespMessage.getContent1()); // RECEIVER's briefcase: the updates that SENDER does not have, but RECEIVER does // = RECEIVER.BAL_RESP.content1 - SENDER.DIVULGE.content1 receiver.briefcase = new TreeSet<Update>(receiver.balRespMessage.getContent1()); receiver.briefcase.removeAll(sender.divulgeMessage.getContent1()); // if any of the briefcases are empty, then there are no preconditions to have a balanced exchange if(sender.briefcase.isEmpty() || receiver.briefcase.isEmpty()) return false; // determine the number of updates that can be exchanged, // taking also into account the max nr of updates to exchange during a balanced exchange protocol int k = Math.min( Math.min(sender.briefcase.size(), receiver.briefcase.size()) , bal_size); // shrink the SENDER and RECEIVER's briefcases to size k sender.shrinkBriefcase(k); receiver.shrinkBriefcase(k); return true; } public boolean createBEbriefcases_colluder(BarGossipMobile sender, BarGossipMobile receiver){ // SENDER's briefcase: the updates that RECEIVER does not have, but SENDER does // = SENDER.DIVULGE.content1 - RECEIVER.BAL_RESP.content1 sender.briefcase = new TreeSet<Update>(sender.divulgeMessage.getContent1()); sender.briefcase.removeAll(receiver.balRespMessage.getContent1()); // RECEIVER's briefcase: the updates that SENDER does not have, but RECEIVER does // = RECEIVER.BAL_RESP.content1 - SENDER.DIVULGE.content1 receiver.briefcase = new TreeSet<Update>(receiver.balRespMessage.getContent1()); receiver.briefcase.removeAll(sender.divulgeMessage.getContent1()); return true; } /** * Create the briefcases to send to the partner during the Data Exchange phase of the optimistic push protocol. */ @Collusion ( mtd_colluder = "createOPbriefcases_colluder" , mtd_not_colluder = "cooperate" ) public void createOPbriefcases(BarGossipMobile receiver, BarGossipMobile sender){ /* SENDER (own youngList and oldList in pushMessage) * RECEIVER (own wantList in pushRespMessage) * * They now create the briefcases. */ // SENDER's briefcase: the updates that RECEIVER requested in the WANT list sent with the PUSH_RESP message sender.briefcase = new TreeSet<Update>(receiver.pushRespMessage.getContent1()); // RECEIVER's briefcase: the updates that SENDER requested in the OLD list sent with the PUSH message, and owned by RECEIVER // = SENDER.PUSH.content2 (INTERSECTION) RECEIVER.transmissibleUpdates receiver.createOPbriefcase(sender); // determine the number of updates that can be exchanged // taking also into account the max nr of updates to exchange during an optimistic push protocol int k = Math.min( Math.max(sender.briefcase.size(), receiver.briefcase.size()) , push_size); // shrink the SENDER and RECEIVER's briefcases to size k if(!sender.briefcase.isEmpty()) sender.shrinkBriefcase(k); if(!receiver.briefcase.isEmpty()) receiver.shrinkBriefcase(k); } public void createOPbriefcases_colluder(BarGossipMobile receiver, BarGossipMobile sender){ /* SENDER and RECEIVER create and send the briefcases. */ // SENDER's briefcase: the updates that RECEIVER requested in the WANT list sent with the PUSH_RESP message sender.briefcase = new TreeSet<Update>(receiver.pushRespMessage.getContent1()); // RECEIVER's briefcase: the updates that SENDER requested in the OLD list sent with the PUSH message, and owned by RECEIVER // = SENDER.PUSH.content2 (INTERSECTION) RECEIVER.transmissibleUpdates receiver.briefcase = new TreeSet<Update>(sender.pushMessage.getContent2()); receiver.briefcase.retainAll(receiver.transmissibleUpdates); } /** * Create the briefcase to send to the partner during the Data Exchange phase of the optimistic push protocol. */ @Collusion ( mtd_not_colluder = "createOPbriefcase_selfish" ) public void createOPbriefcase(BarGossipMobile sender){ briefcase = new TreeSet<Update>(sender.pushMessage.getContent2()); briefcase.retainAll(transmissibleUpdates); } public void createOPbriefcase_selfish(BarGossipMobile sender){ briefcase = new TreeSet<Update>(); } /* Balanced Exchange and Optimistic Push */ /** * Implement the BRIEF step of the Data Exchange phase of the protocols. */ @Collusion ( mtd_colluder = "doSendBRIEF_nojunks") @Defection public void doSendBRIEF(BarGossipMobile recipient, boolean isSENDER){ cooperateOnDoSendBRIEF = true; startDataExchange = true; recipient.startDataExchange = true; // update monitors int nUsefulUpdates = briefMessage.getContent1().size(); int nJunkUpdates = briefMessage.getExtraInfo(); // send a message to the selected peer with the set of updates to serve int bandwidthConsumption = (int) (MESSAGE_HEADER_OVERHEAD + nUsefulUpdates * upd_size + (SIGN_SIZE / 8 + (c_junk * nJunkUpdates * upd_size) )); recipient.handleMessage(briefMessage, bandwidthConsumption); } public void doSendBRIEF_nojunks(BarGossipMobile recipient, boolean isSENDER){ cooperateOnDoSendBRIEF = true; startDataExchange = true; recipient.startDataExchange = true; // update monitors int nUsefulUpdates = briefMessage.getContent1().size(); // send a message to the selected peer with the set of updates to serve int bandwidthConsumption = MESSAGE_HEADER_OVERHEAD + nUsefulUpdates * upd_size + SIGN_SIZE / 8; recipient.handleMessage(briefMessage, bandwidthConsumption); } /** * Implement the KEY_RQST step of the Key Exchange phase. */ private void doSendKEY_RQST(BarGossipMobile partner){ // create the message keyExchangeMessage = new Message(Message.KEY_RQST, this, partner, null, null, 0); // send the key to decrypt the briefcase int bandwidthConsumption = MESSAGE_HEADER_OVERHEAD + SIGN_SIZE / 8; partner.handleMessage(keyExchangeMessage, bandwidthConsumption); } /** * Implement the KEY_RESP step of the Key Exchange phase of the balanced exchange protocol. */ public void doSendKEY_RESP(BarGossipMobile partner){ // create the message keyExchangeMessage = new Message(Message.KEY_RESP, this, partner, null, null, 0); // send the message with the key to decrypt the briefcase int bandwidthConsumption = MESSAGE_HEADER_OVERHEAD + 2 * (SIGN_SIZE / 8); partner.handleMessage(keyExchangeMessage, bandwidthConsumption); } /* MESSAGE HANDLING */ /** * Simulate the processing of a {@link Message}. */ private void handleMessage(Message msg, int bandwidthConsumption){ // update the bandwidth left after the message exchange msg.getSender().uploadBandwidth -= bandwidthConsumption; switch(msg.getType()){ case Message.STREAMING: { // update the set of completed updates updates.addAll(msg.getContent1()); transmissibleUpdates.addAll(msg.getContent1()); break; } case Message.BAL: // this: RECEIVER; msg.getSender: SENDER { runningProtocol = ProtocolType.BALANCED_EXCHANGE; doSendBAL_RESP(msg.getSender()); break; } case Message.BAL_RESP: // this: SENDER; msg.getSender: RECEIVER { /* SENDER: create and send the DIVULGE message */ doSendDIVULGE(msg.getSender()); break; } case Message.DIVULGE: // this: RECEIVER ; msg.getSender: SENDER { BarGossipMobile sender = msg.getSender(); /* Check whether the lists of updates sent in BAL and DIVULGE are the same, and, * if so, make both SENDER and RECEIVER creating and sending the briefcases. */ /* SENDER and RECEIVER: create and send the briefcases. */ if(!createBEbriefcases(sender,this)) break; // create the briefcases sender.briefMessage = new Message(Message.BRIEF, sender, this, sender.briefcase, null, 0); this.briefMessage = new Message(Message.BRIEF, this, sender, this.briefcase, null, 0); // send the briefcases sender.doSendBRIEF(this, true); this.doSendBRIEF(sender, false); break; } case Message.BRIEF: { doSendKEY_RQST(msg.getSender()); break; } case Message.KEY_RQST: { doSendKEY_RESP(msg.getSender()); break; } case Message.KEY_RESP: { BarGossipMobile partner = msg.getSender(); // update the updates lists and monitors of this peer Message briefcaseMsg = partner.briefMessage; transmissibleUpdates.addAll(briefcaseMsg.getContent1()); updates.addAll(briefcaseMsg.getContent1()); long nr = briefcaseMsg.getContent1().size(); if(runningProtocol == ProtocolType.OPTIMISTIC_PUSH){ if(this.isSelfish()) partner.sentChunksInOP2self += nr; else partner.sentChunksInOP2coop += nr; receivedChunksInOP += nr; } else if(runningProtocol == ProtocolType.BALANCED_EXCHANGE){ if(this.isSelfish()) partner.sentChunksInBE2self += nr; else partner.sentChunksInBE2self += nr; receivedChunksInBE += nr; } break; } case Message.PUSH: // this: RECEIVER ; msg.getSender: SENDER { runningProtocol = ProtocolType.OPTIMISTIC_PUSH; // compute the updates notified by the sender in the YOUNG list, but not available to the RECEIVER TreeSet<Update> wantList = new TreeSet<Update>(msg.getContent1()); wantList.removeAll(transmissibleUpdates); doSendPUSH_RESP(msg.getSender(), wantList); break; } case Message.PUSH_RESP: // this: SENDER ; msg.getSender: RECEIVER { BarGossipMobile sender = this; BarGossipMobile receiver = msg.getSender(); if(msg.getContent1() != null && msg.getContent1().isEmpty()) break; createOPbriefcases(receiver,sender); /* * Determine the number of junk updates that have to be sent, and who's in charge of sending them: * (A) if briefcaseSENDER > briefcaseRECEIVER : the RECEIVER will send some junks to the SENDER * (B) if briefcaseSENDER < briefcaseRECEIVER : the SENDER will send some junks to the RECEIVER */ int nrJunks = this.briefcase.size() - receiver.briefcase.size(); if(nrJunks >= 0) { // case (A) // create the briefcases briefMessage = new Message(Message.BRIEF, this, receiver, this.briefcase, null, 0); // SENDER receiver.briefMessage = new Message(Message.BRIEF, receiver, this, receiver.briefcase, null, nrJunks); // RECEIVER // if(runningProtocol == ProtocolType.OPTIMISTIC_PUSH) // System.out.println("SENDER"); // if(briefMessage.getContent1().size() > 0 && runningProtocol == ProtocolType.OPTIMISTIC_PUSH) // System.out.println("RECEIVER"); // send the briefcases doSendBRIEF(receiver, true); receiver.doSendBRIEF(this, false); } else{ // case (B) // create the briefcases briefMessage = new Message(Message.BRIEF, this, receiver, this.briefcase, null, Math.abs(nrJunks)); // SENDER receiver.briefMessage = new Message(Message.BRIEF, receiver, this, receiver.briefcase, null, 0); // RECEIVER // send the briefcases doSendBRIEF(receiver, true); receiver.doSendBRIEF(this, false); } break; } default: } } // METHODS for supporting the live streaming functionalities // ------------------------------------------------------------------------------------------------ /* INITALISE THE SOURCE AND THE PEERS */ /** * Initialise the source of the video streaming (by default, the node with ID = 0). * In particular, this method creates the video source's chunks. */ public void initialiseSource(long bandwidthCapacity, double bcast_hr, short bcast_cnt, int upd_nr){ isSource = true; this.bandwidthCapacity = bandwidthCapacity; this.bcast_hr = bcast_hr; this.bcast_cnt = bcast_cnt; this.partners = new HashSet<BarGossipMobile>(); int currentCycle = 0; // create the video chunks for(int i = 0 ; i < upd_nr ; i++) { transmissibleUpdates.add(new Update(i, currentCycle)); // update the currenyCycle value every FPS chunks if((i+1) % bcast_cnt == 0) currentCycle++; } this.updates.addAll(transmissibleUpdates); } /** * Initialise the peer (any node with ID different from 0). */ public void initialisePeer(long uploadBandwidthCapacity){ isSource = false; toEvict = false; this.bandwidthCapacity = uploadBandwidthCapacity; } /* UPDATE THE PARTNERS OF SOURCE AND PEERS */ /** * Deterministic pseudo-random selection of the interacting partner. */ private BarGossipMobile selectPeerPartner(int protocolId){ BarGossipMobile partner = null; Random generator = new Random(System.currentTimeMillis()) ; short tries = 0; while(tries < MAX_NR_TRIES && partner == null){ Node pnc = Network.get(generator.nextInt(NW_SIZE)); partner = (BarGossipMobile) pnc.getProtocol(protocolId); // check whether pn is the source, or this node, or an evicted node if(partner.isSource || partner.isEvicted || partner == this || (balMessage != null && balMessage.getRecipient() == partner) || partner.uploadBandwidth <= 0 ) { partner = null; tries++; continue; } } return partner; } /** * Randomly select a number of {@link bcast_hr} of peers for the source node. */ public void selectSourcePartners(int protocolId){ final int sourcePartnersSize = (int) (bcast_hr * (Network.size() - 1)); // reset the set of communication partners partners = new HashSet<BarGossipMobile>(sourcePartnersSize); int partnersSize = 0; int nwSize = Network.size(); for(int i = 1 ; i < nwSize ; i++) { BarGossipMobile bg = (BarGossipMobile) Network.get(i).getProtocol(protocolId); if(!bg.isEvicted && bg.toEvict) bg.isEvicted = true; } while (partnersSize < sourcePartnersSize ){ // pick a random neighbour Node n = Network.get(CommonState.r.nextInt(nwSize-1) + 1); // get the BarGossip instance BarGossipMobile bgp = (BarGossipMobile) n.getProtocol(protocolId); // check if n is evicted or if the partner was already added if(bgp.isEvicted || partners.contains(bgp) ) continue; partners.add(bgp); partnersSize++; } } /* UPDATES RETRIEVAL */ /** * Return the set of {@link Update}s that satisfy the passed condition. */ private TreeSet<Update> getStreamableUpdates(TreeSet<Update> updateSet, int value){ TreeSet<Update> result = new TreeSet<Update>(updateSet); Predicate<Update> predicate = new Predicate<Update>() { @Override public boolean test(Update u) { return u.creationTime != value; } }; result.removeIf(predicate); return result; } /** * Update the set of {@link Update}s that can be exchanged (i.e., the not expired yet). */ public void updateTransmissibleUpdates(){ /* get the set of updates to propose at this cycle, i.e., the set of completed updates * that can be still played out */ int lastValidCreationTime = Math.max(0, (int) CommonState.getTime() - upd_dl); Predicate<Update> predicate = new Predicate<Update>() { @Override public boolean test(Update u) { return u.creationTime < lastValidCreationTime; } }; transmissibleUpdates.removeIf(predicate); } /** * Return the set of {@link Update}s that have been created in the last {@link push_age} rounds. */ private TreeSet<Update> getYoungList(){ TreeSet<Update> output = new TreeSet<Update>(transmissibleUpdates); int lastValidCreationTime = Math.max(0, (int) CommonState.getTime() - push_age); Predicate<Update> predicate = new Predicate<Update>() { @Override public boolean test(Update u) { return u.creationTime < lastValidCreationTime; } }; output.removeIf(predicate); return output; } /** * Return the set of {@link Update}s that this peer is missing and that are about to expire. */ private TreeSet<Update> getOldList(int oldListTime){ TreeSet<Update> output = new TreeSet<Update>(transmissibleUpdates); int lastValidCreationTime = Math.max(0, (int) CommonState.getTime() - upd_dl + oldListTime); Predicate<Update> predicate = new Predicate<Update>() { @Override public boolean test(Update u) { return u.creationTime < lastValidCreationTime; } }; output.removeIf(predicate); return output; } public int getMonitoredUpdates(){ TreeSet<Update> result = new TreeSet<Update>(updates); Predicate<Update> predicate = new Predicate<Update>() { @Override public boolean test(Update u) { return u.creationTime < BarGossipObserver.START_MONITORING || u.creationTime >= (BarGossipObserver.START_MONITORING + BarGossipObserver.PERIOD_MONITORING); } }; result.removeIf(predicate); return result.size(); } private void shrinkBriefcase(int elementsToRemove){ int updsToRemove = briefcase.size() - elementsToRemove; Iterator<Update> iu = briefcase.descendingIterator(); while(updsToRemove > 0 && iu.hasNext()) { iu.next(); iu.remove(); updsToRemove++; } } // OTHER METHODS // ------------------------------------------------------------------------------------------------ private void verifySuccessProtocolExecution(ProtocolType pType, BarGossipMobile sender, BarGossipMobile receiver){ switch(pType){ case BALANCED_EXCHANGE: { // VERIFY THE SENDER if(sender.startDataExchange && !sender.cooperateOnDoSendBRIEF) sender.toEvict = true; // evict the sender // VERIFY THE RECEIVER if(receiver.startDataExchange && !receiver.cooperateOnDoSendBRIEF) receiver.toEvict = true; // evict the receiver } break; case OPTIMISTIC_PUSH: { boolean hasCooperatedS = false; boolean hasCooperatedR = false; // VERIFY THE SENDER if(sender.cooperateOnStartOptimisticPushProtocol){ if(receiver.pushRespMessage == null){ hasCooperatedS = true; } else{ if(sender.startDataExchange) hasCooperatedS = sender.cooperateOnDoSendBRIEF; else hasCooperatedS = true; } } // VERIFY THE RECEIVER if(sender.pushMessage == null){ hasCooperatedR = true; } else{ if(receiver.cooperateOnDoSendPUSH_RESP){ if(sender.isSelfish() && sender.getSelfishness().getName().equals("colluding_peers")){ if(receiver.startDataExchange) hasCooperatedR = receiver.cooperateOnDoSendBRIEF; else hasCooperatedR = true; } else { if(receiver.startDataExchange) hasCooperatedR = receiver.cooperateOnDoSendBRIEF; else hasCooperatedR = true; } } } if(!hasCooperatedS) sender.toEvict = true; // evict the sender if(!hasCooperatedR) receiver.toEvict = true; // evict the receiver } break; default: } } /** * Reset the per-cycle bandwidth, if needed. */ public void resetPerCycleBandwidth(){ uploadBandwidth = bandwidthCapacity; } public int getBcast_cnt() { return bcast_cnt; } public boolean isEvicted(){ return isEvicted; } private void resetMessages(BarGossipMobile bg){ bg.balMessage = null; bg.balRespMessage = null; bg.briefMessage = null; bg.divulgeMessage = null; bg.keyExchangeMessage = null; bg.pushMessage = null; bg.pushRespMessage = null; bg.briefcase = null; bg.startDataExchange = false; bg.cooperateOnStartOptimisticPushProtocol = false; // bg.cooperateOnDoSendPUSH = false; bg.cooperateOnDoSendPUSH_RESP = false; bg.cooperateOnDoSendBRIEF = false; } }
/* * Copyright 2017 StreamSets 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.streamsets.pipeline.stage.origin.spooldir; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.streamsets.pipeline.api.EventRecord; import com.streamsets.pipeline.api.OnRecordError; import com.streamsets.pipeline.api.PushSource; import com.streamsets.pipeline.api.Record; import com.streamsets.pipeline.api.Source; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.api.impl.Utils; import com.streamsets.pipeline.api.lineage.LineageEvent; import com.streamsets.pipeline.api.lineage.LineageEventType; import com.streamsets.pipeline.api.lineage.LineageSpecificAttribute; import com.streamsets.pipeline.config.Compression; import com.streamsets.pipeline.config.CsvHeader; import com.streamsets.pipeline.config.CsvParser; import com.streamsets.pipeline.config.DataFormat; import com.streamsets.pipeline.config.JsonMode; import com.streamsets.pipeline.config.OnParseError; import com.streamsets.pipeline.config.PostProcessingOptions; import com.streamsets.pipeline.lib.dirspooler.FileOrdering; import com.streamsets.pipeline.lib.dirspooler.Offset; import com.streamsets.pipeline.lib.dirspooler.PathMatcherMode; import com.streamsets.pipeline.lib.dirspooler.SpoolDirConfigBean; import com.streamsets.pipeline.sdk.DataCollectorServicesUtils; import com.streamsets.pipeline.sdk.PushSourceRunner; import com.streamsets.pipeline.stage.common.HeaderAttributeConstants; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; public class TestSpoolDirSource { /* * Don't use the constant defined in SpoolDirSource in order to regression test the source. */ private static final String NULL_FILE_OFFSET = "NULL_FILE_ID-48496481-5dc5-46ce-9c31-3ab3e034730c::0"; private static final String NULL_FILE = "NULL_FILE_ID-48496481-5dc5-46ce-9c31-3ab3e034730c"; private static final String OFFSET_VERSION_ONE = "1"; private String createTestDir() { File f = new File("target", UUID.randomUUID().toString()); Assert.assertTrue(f.mkdirs()); return f.getAbsolutePath(); } private TSpoolDirSource createSource(String initialFile) { SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.TEXT; // add trailing slash to ensure that works properly conf.spoolDir = createTestDir() + "/"; conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 10; conf.filePattern = "file-[0-9].log"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.initialFileToProcess = initialFile; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.errorArchiveDir = null; conf.postProcessing = PostProcessingOptions.ARCHIVE; conf.archiveDir = createTestDir(); conf.retentionTimeMins = 10; conf.dataFormatConfig.textMaxLineLen = 10; conf.dataFormatConfig.onParseError = OnParseError.ERROR; conf.dataFormatConfig.maxStackTraceLines = 0; return new TSpoolDirSource(conf); } @BeforeClass public static void setup() { DataCollectorServicesUtils.loadDefaultServices(); } @Test public void testInitDestroy() throws Exception { TSpoolDirSource source = createSource("file-0.log"); PushSourceRunner runner = new PushSourceRunner.Builder(TSpoolDirSource.class, source).addOutputLane("lane").build(); runner.runInit(); try { Assert.assertTrue(source.getSpooler().isRunning()); Assert.assertEquals(runner.getContext(), source.getSpooler().getContext()); } finally { source.destroy(); runner.runDestroy(); } } @Test public void testAllowLateDirectory() throws Exception { File f = new File("target", UUID.randomUUID().toString()); SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.TEXT; conf.spoolDir = f.getAbsolutePath(); conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 10; conf.filePattern = "file-[0-9].log"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.initialFileToProcess = null; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.errorArchiveDir = null; conf.postProcessing = PostProcessingOptions.ARCHIVE; conf.archiveDir = createTestDir(); conf.retentionTimeMins = 10; conf.dataFormatConfig.textMaxLineLen = 10; conf.dataFormatConfig.onParseError = OnParseError.ERROR; conf.dataFormatConfig.maxStackTraceLines = 0; TSpoolDirSource source = new TSpoolDirSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(TSpoolDirSource.class, source).addOutputLane("lane").build(); //Late Directories not allowed, init should fail. conf.allowLateDirectory = false; try { runner.runInit(); Assert.fail("Should throw an exception if the directory does not exist"); } catch (StageException e) { //Expected } //Late Directories allowed, wait and should be able to detect the file and read. conf.allowLateDirectory = true; TSpoolDirSource sourceWithLateDirectory = new TSpoolDirSource(conf); PushSourceRunner runner2 = new PushSourceRunner.Builder(TSpoolDirSource.class, sourceWithLateDirectory).addOutputLane("lane").build(); AtomicInteger batchCount = new AtomicInteger(0); runner2.runInit(); try { runner2.runProduce(new HashMap<>(), 10, output -> { batchCount.incrementAndGet(); if (batchCount.get() == 1) { runner2.setStop(); } }); runner2.waitOnProduce(); TestOffsetUtil.compare(NULL_FILE_OFFSET, runner2.getOffsets()); Assert.assertEquals(1, runner2.getEventRecords().size()); Assert.assertEquals("no-more-data", runner2.getEventRecords().get(0).getEventType()); Assert.assertTrue(f.mkdirs()); File file = new File(source.spoolDir, "file-0.log").getAbsoluteFile(); Files.createFile(file.toPath()); source.file = file; source.offset = 1; source.maxBatchSize = 10; Thread.sleep(5000L); PushSourceRunner runner3 = new PushSourceRunner.Builder(TSpoolDirSource.class, source).addOutputLane("lane").build(); runner3.runInit(); runner3.runProduce(ImmutableMap.of(Source.POLL_SOURCE_OFFSET_KEY, "file-0.log::1"), 10, output -> { batchCount.incrementAndGet(); if (batchCount.get() > 1) { runner3.setStop(); } }); runner3.waitOnProduce(); TestOffsetUtil.compare("file-0.log::1", runner3.getOffsets()); Assert.assertEquals(1, runner3.getEventRecords().size()); Assert.assertEquals("new-file", runner3.getEventRecords().get(0).getEventType()); runner3.runDestroy(); } finally { source.destroy(); runner2.runDestroy(); } } @Test public void testProduceNoInitialFileNoFileInSpoolDirNullOffset() throws Exception { TSpoolDirSource source = createSource(null); PushSourceRunner runner = new PushSourceRunner.Builder(TSpoolDirSource.class, source).addOutputLane("lane").build(); runner.runInit(); try { runner.runProduce(new HashMap<>(), 10, output -> { runner.setStop(); }); runner.waitOnProduce(); TestOffsetUtil.compare(NULL_FILE_OFFSET, runner.getOffsets()); Assert.assertFalse(source.produceCalled); Assert.assertEquals(1, runner.getEventRecords().size()); Assert.assertEquals("no-more-data", runner.getEventRecords().get(0).getEventType()); } finally { source.destroy(); runner.runDestroy(); } } @Test public void testProduceNoInitialFileWithFileInSpoolDirNullOffset() throws Exception { TSpoolDirSource source = createSource("file-0.log"); PushSourceRunner runner = new PushSourceRunner.Builder(TSpoolDirSource.class, source).addOutputLane("lane").build(); File file = new File(source.spoolDir, "file-0.log").getAbsoluteFile(); Files.createFile(file.toPath()); runner.runInit(); source.file = file; source.offset = 0; source.maxBatchSize = 10; try { runner.runProduce(new HashMap<>(), 10, output -> { runner.setStop(); }); runner.waitOnProduce(); TSpoolDirRunnable runnable = source.getTSpoolDirRunnable(); TestOffsetUtil.compare("file-0.log::0", runner.getOffsets()); Assert.assertTrue(runnable.produceCalled); } finally { source.destroy(); runner.runDestroy(); } } @Test public void testProduceNoInitialFileNoFileInSpoolDirNotNullOffset() throws Exception { TSpoolDirSource source = createSource(null); PushSourceRunner runner = new PushSourceRunner.Builder(TSpoolDirSource.class, source).addOutputLane("lane").build(); runner.runInit(); try { runner.runProduce(ImmutableMap.of(Source.POLL_SOURCE_OFFSET_KEY, "file-0.log"), 10, output -> { runner.setStop(); }); runner.waitOnProduce(); TestOffsetUtil.compare("file-0.log::0", runner.getOffsets()); } finally { source.destroy(); runner.runDestroy(); } } @Test public void testProduceNoInitialFileWithFileInSpoolDirNotNullOffset() throws Exception { TSpoolDirSource source = createSource("file-0.log"); PushSourceRunner runner = new PushSourceRunner.Builder(TSpoolDirSource.class, source).addOutputLane("lane").build(); File file = new File(source.spoolDir, "file-0.log").getAbsoluteFile(); Files.createFile(file.toPath()); runner.runInit(); source.file = file; source.offset = 0; source.maxBatchSize = 10; try { runner.runProduce(ImmutableMap.of(Source.POLL_SOURCE_OFFSET_KEY, "file-0.log"), 10, output -> { runner.setStop(); }); runner.waitOnProduce(); TSpoolDirRunnable runnable = source.getTSpoolDirRunnable(); TestOffsetUtil.compare("file-0.log::0", runner.getOffsets()); Assert.assertTrue(runnable.produceCalled); } finally { source.destroy(); runner.runDestroy(); } } @Test public void testProduceNoInitialFileWithFileInSpoolDirNonZeroOffset() throws Exception { TSpoolDirSource source = createSource(null); PushSourceRunner runner = new PushSourceRunner.Builder(TSpoolDirSource.class, source).addOutputLane("lane").build(); File file = new File(source.spoolDir, "file-0.log").getAbsoluteFile(); Files.createFile(file.toPath()); runner.runInit(); source.file = file; source.offset = 1; source.maxBatchSize = 10; try { runner.runProduce(ImmutableMap.of(Source.POLL_SOURCE_OFFSET_KEY, "file-0.log::1"), 10, output -> { runner.setStop(); }); runner.waitOnProduce(); TSpoolDirRunnable runnable = source.getTSpoolDirRunnable(); TestOffsetUtil.compare("file-0.log::1", runner.getOffsets()); Assert.assertTrue(runnable.produceCalled); } finally { source.destroy(); runner.runDestroy(); } } @Test public void testNoMoreFilesEmptyBatch() throws Exception { TSpoolDirSource source = createSource(null); PushSourceRunner runner = new PushSourceRunner.Builder(TSpoolDirSource.class, source).addOutputLane("lane").build(); File file = new File(source.spoolDir, "file-0.log").getAbsoluteFile(); Files.createFile(file.toPath()); AtomicInteger batchCount = new AtomicInteger(0); runner.runInit(); try { source.file = file; source.offset = 0; source.maxBatchSize = 10; source.offsetIncrement = -1; runner.runProduce(new HashMap<>(), 1000, output -> { TSpoolDirRunnable runnable = source.getTSpoolDirRunnable(); batchCount.incrementAndGet(); if (batchCount.get() == 1) { Assert.assertTrue(output.getOffsetEntity().contains("file-0.log")); Assert.assertEquals("{\"POS\":\"-1\"}", output.getNewOffset()); Assert.assertTrue(runnable.produceCalled); runnable.produceCalled = false; } else if (batchCount.get() == 2) { Assert.assertTrue(output.getOffsetEntity().contains("file-0.log")); Assert.assertEquals("{\"POS\":\"-1\"}", output.getNewOffset()); //Produce will not be called as this file-0.log will not be eligible for produce Assert.assertFalse(runnable.produceCalled); } else if (batchCount.get() > 2){ runner.setStop(); } }); runner.waitOnProduce(); Assert.assertEquals(3, batchCount.get()); } finally { source.destroy(); runner.runDestroy(); } } @Test public void testAdvanceToNextSpoolFile() throws Exception { TSpoolDirSource source = createSource(null); PushSourceRunner runner = new PushSourceRunner.Builder(TSpoolDirSource.class, source).addOutputLane("lane").build(); File file1 = new File(source.spoolDir, "file-0.log").getAbsoluteFile(); Files.createFile(file1.toPath()); File file2 = new File(source.spoolDir, "file-1.log").getAbsoluteFile(); Files.createFile(file2.toPath()); source.file = file1; source.offset = 0; source.maxBatchSize = 10; AtomicInteger batchCount = new AtomicInteger(0); runner.runInit(); try { runner.runProduce(ImmutableMap.of(Source.POLL_SOURCE_OFFSET_KEY, "file-0.log::0"), 10, output -> { batchCount.incrementAndGet(); TSpoolDirRunnable runnable = source.getTSpoolDirRunnable(); if (batchCount.get() == 1) { Assert.assertEquals("file-0.log", output.getOffsetEntity()); Assert.assertEquals("{\"POS\":\"0\"}", output.getNewOffset()); Assert.assertTrue(runnable.produceCalled); Assert.assertEquals(1, runner.getEventRecords().size()); Assert.assertEquals("new-file", runner.getEventRecords().get(0).getEventType()); runnable.produceCalled = false; runnable.offsetIncrement = -1; } else if (batchCount.get() == 2) { Assert.assertEquals("file-0.log", output.getOffsetEntity()); Assert.assertEquals("{\"POS\":\"-1\"}", output.getNewOffset()); Assert.assertTrue(runnable.produceCalled); Assert.assertEquals(2, runner.getEventRecords().size()); Assert.assertEquals("new-file", runner.getEventRecords().get(0).getEventType()); Assert.assertEquals("finished-file", runner.getEventRecords().get(1).getEventType()); Assert.assertEquals(0, runner.getEventRecords().get(1).get("/error-count").getValueAsInteger()); Assert.assertEquals(0, runner.getEventRecords().get(1).get("/record-count").getValueAsInteger()); runnable.file = file2; } else if (batchCount.get() == 4) { runnable.produceCalled = false; runnable.offset = 0; runnable.offsetIncrement = 0; runner.setStop(); } else if (batchCount.get() > 4) { runner.setStop(); } }); runner.waitOnProduce(); Assert.assertEquals(4, batchCount.get()); TestOffsetUtil.compare("file-1.log::-1", runner.getOffsets()); Assert.assertFalse(source.produceCalled); // 2 each of new-file and finished-file and 1 no-more-data Assert.assertEquals(5, runner.getEventRecords().size()); // check for LineageEvents. List<LineageEvent> events = runner.getLineageEvents(); Assert.assertEquals(2, events.size()); Assert.assertEquals(LineageEventType.ENTITY_READ, events.get(0).getEventType()); Assert.assertEquals(LineageEventType.ENTITY_READ, events.get(1).getEventType()); Assert.assertTrue(events.get(0).getSpecificAttribute(LineageSpecificAttribute.ENTITY_NAME).contains("file-0.log")); Assert.assertTrue(events.get(1).getSpecificAttribute(LineageSpecificAttribute.ENTITY_NAME).contains("file-1.log")); } finally { source.destroy(); runner.runDestroy(); } } @Test public void testRecoverableDataParserError() throws Exception { File f = new File("target", UUID.randomUUID().toString()); f.mkdir(); SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.DELIMITED; conf.spoolDir = f.getAbsolutePath(); conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 10; conf.filePattern = "file-[0-9].log"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.initialFileToProcess = "file-0.log"; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.dataFormatConfig.csvHeader = CsvHeader.WITH_HEADER; conf.errorArchiveDir = null; conf.postProcessing = PostProcessingOptions.NONE; conf.retentionTimeMins = 10; conf.allowLateDirectory = false; conf.dataFormatConfig.csvParser = CsvParser.LEGACY_PARSER; conf.dataFormatConfig.textMaxLineLen = 10; conf.dataFormatConfig.onParseError = OnParseError.ERROR; conf.dataFormatConfig.maxStackTraceLines = 0; FileOutputStream outputStream = new FileOutputStream(new File(conf.spoolDir, "file-0.log")); IOUtils.writeLines(ImmutableList.of("A,B", "a,b,c", "a,b"), "\n", outputStream); outputStream.close(); SpoolDirSource source = new SpoolDirSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source) .setOnRecordError(OnRecordError.TO_ERROR) .addOutputLane("lane") .build(); final List<Record> records = Collections.synchronizedList(new ArrayList<>(10)); runner.runInit(); try { runner.runProduce(new HashMap<>(), 10, output -> { synchronized (records) { records.addAll(output.getRecords().get("lane")); } runner.setStop(); }); runner.waitOnProduce(); // Verify proper record Assert.assertNotNull(records); Assert.assertEquals(1, records.size()); // And error record List<Record> errorRecords = runner.getErrorRecords(); Assert.assertEquals(1, errorRecords.size()); } finally { source.destroy(); runner.runDestroy(); } } @Test public void testMultipleFilesSameTimeStamp() throws Exception { File f = new File("target", UUID.randomUUID().toString()); f.mkdir(); SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.DELIMITED; conf.useLastModified = FileOrdering.TIMESTAMP; conf.spoolDir = f.getAbsolutePath(); conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 10; conf.filePattern = "*"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.dataFormatConfig.csvHeader = CsvHeader.WITH_HEADER; conf.errorArchiveDir = null; conf.postProcessing = PostProcessingOptions.NONE; conf.retentionTimeMins = 10; conf.allowLateDirectory = false; conf.dataFormatConfig.csvParser = CsvParser.LEGACY_PARSER; conf.dataFormatConfig.textMaxLineLen = 10; conf.dataFormatConfig.onParseError = OnParseError.ERROR; conf.dataFormatConfig.maxStackTraceLines = 0; long timestamp = System.currentTimeMillis() - 100000; for (int i = 0; i < 8; i++) { File current = new File(conf.spoolDir, Utils.format("file-{}.log", i)); try (FileOutputStream outputStream = new FileOutputStream(current)) { IOUtils.writeLines(ImmutableList.of("A,B", Utils.format("a-{},b-{}", i, i), "a,b"), "\n", outputStream); } Assert.assertTrue(current.setLastModified(timestamp)); } // for ctime delays, there's no way to set ctime (change timestamp) explicitly by rule Thread.sleep(5000L); File current = new File(conf.spoolDir,"a.log"); try(FileOutputStream outputStream = new FileOutputStream(current)) { IOUtils.writeLines(ImmutableList.of("A,B", "Gollum,Sauron", "Aragorn,Boromir"), "\n", outputStream); } Assert.assertTrue(current.setLastModified(System.currentTimeMillis())); SpoolDirSource source = new SpoolDirSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source) .setOnRecordError(OnRecordError.TO_ERROR) .addOutputLane("lane") .build(); AtomicInteger batchCount = new AtomicInteger(0); runner.runInit(); Assert.assertEquals(0, runner.getErrors().size()); try { runner.runProduce(new HashMap<>(), 10, output -> { int i = batchCount.getAndIncrement(); if (i < 8) { List<Record> records = output.getRecords().get("lane"); Assert.assertNotNull(records); Assert.assertTrue(!records.isEmpty()); Assert.assertEquals(2, records.size()); Assert.assertEquals(Utils.format("file-{}.log", i), records.get(0).getHeader().getAttribute(HeaderAttributeConstants.FILE_NAME) ); try { Assert.assertEquals( String.valueOf(Files.getLastModifiedTime(Paths.get(f.getAbsolutePath(), Utils.format("file-{}.log", i))).toMillis()), records.get(0).getHeader().getAttribute(HeaderAttributeConstants.LAST_MODIFIED_TIME) ); } catch (IOException ex) { Assert.fail(ex.toString()); } Assert.assertEquals("a-" + i, records.get(0).get("/A").getValueAsString()); Assert.assertEquals("b-" + i, records.get(0).get("/B").getValueAsString()); Assert.assertEquals("a", records.get(1).get("/A").getValueAsString()); Assert.assertEquals("b", records.get(1).get("/B").getValueAsString()); // And error record List<Record> errorRecords = runner.getErrorRecords(); Assert.assertEquals(0, errorRecords.size()); } else if (i < 9) { List<Record> records = output.getRecords().get("lane"); Assert.assertNotNull(records); Assert.assertTrue(!records.isEmpty()); Assert.assertEquals(2, records.size()); Assert.assertEquals("a.log", records.get(0).getHeader().getAttribute(HeaderAttributeConstants.FILE_NAME)); Assert.assertEquals("Gollum", records.get(0).get("/A").getValueAsString()); Assert.assertEquals("Sauron", records.get(0).get("/B").getValueAsString()); Assert.assertEquals("Aragorn", records.get(1).get("/A").getValueAsString()); Assert.assertEquals("Boromir", records.get(1).get("/B").getValueAsString()); } else if (i < 10) { List<Record> records = output.getRecords().get("lane"); Assert.assertTrue(records.isEmpty()); // And error record records = runner.getErrorRecords(); Assert.assertEquals(0, records.size()); } else if (i < 11) { // And a bunch of event records... // new-file event, finished-file event for each file. // file-0.log through file-7.log and a.log (9 files) // two no-more-data events. Assert.assertEquals(19, runner.getEventRecords().size()); Map<String, Integer> map = new HashMap<>(); for(EventRecord rec : runner.getEventRecords()) { if(map.get(rec.getEventType()) != null) { map.put(rec.getEventType(), map.get(rec.getEventType()) + 1); } else { map.put(rec.getEventType(), 1); } } Assert.assertNotNull(map.get("new-file")); Assert.assertNotNull(map.get("finished-file")); Assert.assertNotNull(map.get("no-more-data")); int numEvents = map.get("new-file"); Assert.assertEquals(9, numEvents); numEvents = map.get("finished-file"); Assert.assertEquals(9, numEvents); numEvents = map.get("no-more-data"); Assert.assertEquals(1, numEvents); } else { runner.setStop(); } }); runner.waitOnProduce(); Assert.assertEquals(12, batchCount.get()); } finally { source.destroy(); runner.runDestroy(); } } private static PushSource.Context createTestContext() { return Mockito.mock(PushSource.Context.class); } @Test public void testHandleLastSourceOffsetWithEmptyOffset() throws Exception { SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.TEXT; conf.spoolDir = "/"; conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 10; conf.filePattern = "file-[0-9].log"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.initialFileToProcess = null; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.errorArchiveDir = null; conf.postProcessing = PostProcessingOptions.NONE; conf.retentionTimeMins = 10; conf.dataFormatConfig.textMaxLineLen = 10; conf.dataFormatConfig.onParseError = OnParseError.ERROR; conf.dataFormatConfig.maxStackTraceLines = 0; conf.allowLateDirectory = false; conf.numberOfThreads = 1; SpoolDirSource source = new SpoolDirSource(conf); Map<String, String> lastSourceOffset = null; Map<String, Offset> offsetMap = source.handleLastSourceOffset(lastSourceOffset, createTestContext()); Assert.assertEquals(1, offsetMap.size()); Assert.assertTrue(offsetMap.containsKey(NULL_FILE)); Assert.assertEquals("0", offsetMap.get(NULL_FILE).getOffset()); source.destroy(); } @Test public void testHandleLastSourceOffsetFromV0() throws Exception { SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.TEXT; conf.spoolDir = "/"; conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 10; conf.filePattern = "file-[0-9].log"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.initialFileToProcess = null; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.errorArchiveDir = null; conf.postProcessing = PostProcessingOptions.NONE; conf.retentionTimeMins = 10; conf.dataFormatConfig.textMaxLineLen = 10; conf.dataFormatConfig.onParseError = OnParseError.ERROR; conf.dataFormatConfig.maxStackTraceLines = 0; conf.allowLateDirectory = false; conf.numberOfThreads = 1; SpoolDirSource source = new SpoolDirSource(conf); Map<String, String> lastSourceOffset = ImmutableMap.of(Source.POLL_SOURCE_OFFSET_KEY, "file-1.log::0"); Map<String, Offset> offsetMap = source.handleLastSourceOffset(lastSourceOffset, createTestContext()); Assert.assertEquals(1, offsetMap.size()); Assert.assertEquals("0", offsetMap.get("file-1.log").getOffset()); source.destroy(); } @Test public void testHandleLastSourceOffsets() throws Exception { SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.TEXT; conf.spoolDir = "/"; conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 10; conf.filePattern = "file-[0-9].log"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.initialFileToProcess = null; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.errorArchiveDir = null; conf.postProcessing = PostProcessingOptions.NONE; conf.retentionTimeMins = 10; conf.dataFormatConfig.textMaxLineLen = 10; conf.dataFormatConfig.onParseError = OnParseError.ERROR; conf.dataFormatConfig.maxStackTraceLines = 0; conf.allowLateDirectory = false; conf.numberOfThreads = 1; SpoolDirSource source = new SpoolDirSource(conf); final int numOffset = 5; Map<String, String> lastSourceOffsets = new HashMap<>(numOffset); IntStream.range(0, numOffset).forEach( threadNumber -> lastSourceOffsets.put("file-" + threadNumber + ".log", Integer.toString(threadNumber)) ); Map<String, String> lastSourceOffset = new HashMap<>(); lastSourceOffset.put(source.OFFSET_VERSION, OFFSET_VERSION_ONE); for (String fileName : lastSourceOffsets.keySet()) { Offset offset = new Offset(OFFSET_VERSION_ONE, fileName + "::" + lastSourceOffsets.get(fileName)); lastSourceOffset.put(fileName, offset.getOffsetString()); } Map<String, Offset> offsetMap = source.handleLastSourceOffset(lastSourceOffset, createTestContext()); Assert.assertEquals(numOffset, offsetMap.size()); for (String fileName : lastSourceOffsets.keySet()) { Assert.assertEquals(lastSourceOffsets.get(fileName), offsetMap.get(fileName).getOffset()); } // get the very last file from the last source offset Assert.assertEquals("file-0.log", source.getLastSourceFileName()); source.destroy(); } @Test public void testWithMultipleThreads() throws Exception { // set up multiple test files File f = new File("target", UUID.randomUUID().toString()); Assert.assertTrue(f.mkdirs()); final int numFiles = 10; for (int i = 0; i < numFiles; i++) { FileOutputStream outputStream = new FileOutputStream(new File(f.getAbsolutePath(), "-file-" + i + ".log")); // each file has 5 lines IOUtils.writeLines(ImmutableList.of("1", "2", "3", "4", "5"), "\n", outputStream); outputStream.close(); } readFilesMultipleThreads(f.getAbsolutePath(), 1); readFilesMultipleThreads(f.getAbsolutePath(), 2); readFilesMultipleThreads(f.getAbsolutePath(), 5); readFilesMultipleThreads(f.getAbsolutePath(), 10); } private void readFilesMultipleThreads(String spoolDir, int numberOfThreads) throws Exception { SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.TEXT; conf.spoolDir = spoolDir; conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 10; conf.filePattern = "*file-[0-9].log"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.initialFileToProcess = null; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.errorArchiveDir = null; conf.postProcessing = PostProcessingOptions.NONE; conf.retentionTimeMins = 10; conf.dataFormatConfig.textMaxLineLen = 10; conf.dataFormatConfig.onParseError = OnParseError.ERROR; conf.dataFormatConfig.maxStackTraceLines = 0; conf.allowLateDirectory = false; conf.numberOfThreads = numberOfThreads; SpoolDirSource source = new SpoolDirSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source).addOutputLane("lane").build(); AtomicInteger batchCount = new AtomicInteger(0); final List<Record> records = Collections.synchronizedList(new ArrayList<>(10)); runner.runInit(); final int maxBatchSize = 10; try { runner.runProduce(new HashMap<>(), maxBatchSize, output -> { batchCount.incrementAndGet(); synchronized (records) { records.addAll(output.getRecords().get("lane")); } if (records.size() == 50 || batchCount.get() > 10) { runner.setStop(); } }); runner.waitOnProduce(); Assert.assertTrue(batchCount.get() > 1); TestOffsetUtil.compare("-file-9.log::-1", runner.getOffsets()); Assert.assertEquals(50, records.size()); } finally { source.destroy(); runner.runDestroy(); } } @Test public void testWithMultipleThreadsInitialOffsets() throws Exception { // set up multiple test files File f = new File("target", UUID.randomUUID().toString()); Assert.assertTrue(f.mkdirs()); final int numFiles = 10; for (int i = 0; i < numFiles; i++) { FileOutputStream outputStream = new FileOutputStream(new File(f.getAbsolutePath(), "file-" + i + ".log")); // each file has 5 lines IOUtils.writeLines(ImmutableList.of("1", "2", "3", "4", "5"), "\n", outputStream); outputStream.close(); } // let the first 2 files, file-0.log and file-3.log, were processed and // file-2.log was processed 1 line/record // file-1.log will be skipped since is less then file-3.log Map<String, String> lastSourceOffsetMap = ImmutableMap.of( SpoolDirSource.OFFSET_VERSION, OFFSET_VERSION_ONE, "file-0.log", "{\"POS\":\"-1\"}", "file-2.log", "{\"POS\":\"2\"}", "file-3.log", "{\"POS\":\"-1\"}" ); SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.TEXT; conf.spoolDir = f.getAbsolutePath(); conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 10; conf.filePattern = "file-[0-9].log"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.initialFileToProcess = null; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.errorArchiveDir = null; conf.postProcessing = PostProcessingOptions.NONE; conf.retentionTimeMins = 10; conf.dataFormatConfig.textMaxLineLen = 10; conf.dataFormatConfig.onParseError = OnParseError.ERROR; conf.dataFormatConfig.maxStackTraceLines = 0; conf.allowLateDirectory = false; conf.numberOfThreads = 10; SpoolDirSource source = new SpoolDirSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source).addOutputLane("lane").build(); AtomicInteger batchCount = new AtomicInteger(0); final List<Record> records = Collections.synchronizedList(new ArrayList<>(10)); runner.runInit(); final int maxBatchSize = 10; try { runner.runProduce(lastSourceOffsetMap, maxBatchSize, output -> { batchCount.incrementAndGet(); synchronized (records) { records.addAll(output.getRecords().get("lane")); } if (records.size() == 34 || batchCount.get() > 10) { runner.setStop(); } }); runner.waitOnProduce(); Assert.assertTrue(batchCount.get() > 1); TestOffsetUtil.compare("file-9.log::-1", runner.getOffsets()); Assert.assertTrue(records.size() == 34 || batchCount.get() > 10); } finally { source.destroy(); runner.runDestroy(); } } @Test public void testErrorFileWithoutPreview() throws Exception { errorFile(false); } @Test public void testErrorFileInPreview() throws Exception { errorFile(true); } public void errorFile(boolean preview) throws Exception { File spoolDir = new File("target", UUID.randomUUID().toString()); spoolDir.mkdir(); File errorDir = new File("target", UUID.randomUUID().toString()); errorDir.mkdir(); SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.JSON; conf.spoolDir = spoolDir.getAbsolutePath(); conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 10; conf.filePattern = "file-[0-9].log"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.initialFileToProcess = "file-0.log"; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.dataFormatConfig.csvHeader = CsvHeader.WITH_HEADER; conf.errorArchiveDir = errorDir.getAbsolutePath(); conf.postProcessing = PostProcessingOptions.NONE; conf.retentionTimeMins = 10; conf.allowLateDirectory = false; conf.dataFormatConfig.jsonContent = JsonMode.MULTIPLE_OBJECTS; conf.dataFormatConfig.onParseError = OnParseError.ERROR; FileOutputStream outputStream = new FileOutputStream(new File(conf.spoolDir, "file-0.log")); // Incorrect JSON IOUtils.writeLines(ImmutableList.of("{a"), "\n", outputStream); outputStream.close(); SpoolDirSource source = new SpoolDirSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source) .setPreview(preview) .setOnRecordError(OnRecordError.TO_ERROR) .addOutputLane("lane") .build(); final List<Record> records = Collections.synchronizedList(new ArrayList<>(10)); runner.runInit(); try { runner.runProduce(new HashMap<>(), 10, output -> { synchronized (records) { records.addAll(output.getRecords().get("lane")); } runner.setStop(); }); runner.waitOnProduce(); // Verify proper record Assert.assertNotNull(records); Assert.assertEquals(0, records.size()); // Depending on the preview flag, we should see the file in one directory or the other if(preview) { Assert.assertEquals(0, errorDir.list().length); Assert.assertEquals(1, spoolDir.list().length); } else { Assert.assertEquals(1, errorDir.list().length); Assert.assertEquals(0, spoolDir.list().length); } } finally { source.destroy(); runner.runDestroy(); } } @Test public void testBatchSizeLargerThanMax() throws Exception { final int maxBatchSize = 5; final String MINUS_ONE_JSON = "-1\"}"; final String EXPECTED_ERROR = "SPOOLDIR_37 - " + "Batch size greater than maximal batch size allowed in sdc.properties, maxBatchSize: 5"; File spoolDir = new File("target", UUID.randomUUID().toString()); spoolDir.mkdir(); SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.TEXT; conf.spoolDir = spoolDir.getAbsolutePath(); conf.batchSize = maxBatchSize + 1; // use a batch size greater than maxBatchSize conf.overrunLimit = 100; conf.poolingTimeoutSecs = 10; conf.filePattern = "file-[0-9].log"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.initialFileToProcess = "file-0.log"; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.dataFormatConfig.csvHeader = CsvHeader.WITH_HEADER; conf.postProcessing = PostProcessingOptions.NONE; conf.retentionTimeMins = 10; conf.allowLateDirectory = false; conf.dataFormatConfig.jsonContent = JsonMode.MULTIPLE_OBJECTS; conf.dataFormatConfig.onParseError = OnParseError.ERROR; List<String> messages = new ArrayList<>(); for (int i = 0; i < 10; i++) messages. add("MESSAGE " + i); FileOutputStream outputStream = new FileOutputStream(new File(conf.spoolDir, "file-0.log")); IOUtils.writeLines(messages, "\n", outputStream); outputStream.close(); SpoolDirSource source = new SpoolDirSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source) .setOnRecordError(OnRecordError.TO_ERROR) .addOutputLane("lane") .build(); AtomicInteger batchCount = new AtomicInteger(); runner.runInit(); try { runner.runProduce(new HashMap<>(), maxBatchSize, output -> { List<Record> records = output.getRecords().get("lane"); int produceNum = batchCount.getAndIncrement(); // expect 3rd batch to be offset -1, otherwise check max 5 batches to make sure we stop the runner if (!output.getNewOffset().endsWith(MINUS_ONE_JSON) && produceNum < 5) { Assert.assertNotNull(records); Assert.assertEquals(maxBatchSize, records.size()); Assert.assertEquals(1, runner.getErrors().size()); Assert.assertEquals(EXPECTED_ERROR, runner.getErrors().get(0)); } else { runner.setStop(); } }); runner.waitOnProduce(); Assert.assertEquals(3, batchCount.get()); } finally { source.destroy(); runner.runDestroy(); } } }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. /* * @author max */ package io.flutter.editor; import com.intellij.codeHighlighting.TextEditorHighlightingPass; import com.intellij.codeInsight.highlighting.BraceMatcher; import com.intellij.codeInsight.highlighting.BraceMatchingUtil; import com.intellij.lang.Language; import com.intellij.lang.LanguageParserDefinitions; import com.intellij.lang.ParserDefinition; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.editor.highlighter.HighlighterIterator; import com.intellij.openapi.editor.markup.CustomHighlighterRenderer; import com.intellij.openapi.editor.markup.HighlighterTargetArea; import com.intellij.openapi.editor.markup.MarkupModel; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Segment; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.util.PsiUtilBase; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.paint.LinePainter2D; import com.intellij.util.DocumentUtil; import com.intellij.util.containers.IntStack; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.util.List; import java.util.*; import static java.lang.Math.min; /** * This is an FilteredIndentsHighlightingPass class forked from com.intellij.codeInsight.daemon.impl.FilteredIndentsHighlightingPass * that supports filtering out indent guides that conflict with widget indent * guides as determined by calling WidgetIndentsHighlightingPass.isIndentGuideHidden. */ @SuppressWarnings("ALL") public class FilteredIndentsHighlightingPass extends TextEditorHighlightingPass implements DumbAware { private static final Key<List<RangeHighlighter>> INDENT_HIGHLIGHTERS_IN_EDITOR_KEY = Key.create("INDENT_HIGHLIGHTERS_IN_EDITOR_KEY"); private static final Key<Long> LAST_TIME_INDENTS_BUILT = Key.create("LAST_TIME_INDENTS_BUILT"); private final EditorEx myEditor; private final PsiFile myFile; private volatile List<TextRange> myRanges = Collections.emptyList(); private volatile List<IndentGuideDescriptor> myDescriptors = Collections.emptyList(); private static final CustomHighlighterRenderer RENDERER = (editor, highlighter, g) -> { int startOffset = highlighter.getStartOffset(); final Document doc = highlighter.getDocument(); final int textLength = doc.getTextLength(); if (startOffset >= textLength) return; final int endOffset = min(highlighter.getEndOffset(), textLength); final int endLine = doc.getLineNumber(endOffset); int off; int startLine = doc.getLineNumber(startOffset); IndentGuideDescriptor descriptor = editor.getIndentsModel().getDescriptor(startLine, endLine); final CharSequence chars = doc.getCharsSequence(); do { int start = doc.getLineStartOffset(startLine); int end = doc.getLineEndOffset(startLine); off = CharArrayUtil.shiftForward(chars, start, end, " \t"); startLine--; } while (startLine > 1 && off < doc.getTextLength() && chars.charAt(off) == '\n'); final VisualPosition startPosition = editor.offsetToVisualPosition(off); int indentColumn = startPosition.column; // It's considered that indent guide can cross not only white space but comments, javadoc etc. Hence, there is a possible // case that the first indent guide line is, say, single-line comment where comment symbols ('//') are located at the first // visual column. We need to calculate correct indent guide column then. int lineShift = 1; if (indentColumn <= 0 && descriptor != null) { indentColumn = descriptor.indentLevel; lineShift = 0; } if (indentColumn <= 0) return; final FoldingModel foldingModel = editor.getFoldingModel(); if (foldingModel.isOffsetCollapsed(off)) return; final FoldRegion headerRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineEndOffset(doc.getLineNumber(off))); final FoldRegion tailRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineStartOffset(doc.getLineNumber(endOffset))); if (tailRegion != null && tailRegion == headerRegion) return; final boolean selected; final IndentGuideDescriptor guide = editor.getIndentsModel().getCaretIndentGuide(); if (guide != null) { final CaretModel caretModel = editor.getCaretModel(); final int caretOffset = caretModel.getOffset(); selected = caretOffset >= off && caretOffset < endOffset && caretModel.getLogicalPosition().column == indentColumn; } else { selected = false; } Point start = editor.visualPositionToXY(new VisualPosition(startPosition.line + lineShift, indentColumn)); final VisualPosition endPosition = editor.offsetToVisualPosition(endOffset); Point end = editor.visualPositionToXY(new VisualPosition(endPosition.line, endPosition.column)); int maxY = end.y; if (endPosition.line == editor.offsetToVisualPosition(doc.getTextLength()).line) { maxY += editor.getLineHeight(); } Rectangle clip = g.getClipBounds(); if (clip != null) { if (clip.y >= maxY || clip.y + clip.height <= start.y) { return; } maxY = min(maxY, clip.y + clip.height); } if (WidgetIndentsHighlightingPass.isIndentGuideHidden(editor, new LineRange(startLine, endPosition.line))) { // Avoid rendering this guide as it overlaps with the Widget indent guides. return; } final EditorColorsScheme scheme = editor.getColorsScheme(); g.setColor(scheme.getColor(selected ? EditorColors.SELECTED_INDENT_GUIDE_COLOR : EditorColors.INDENT_GUIDE_COLOR)); // There is a possible case that indent line intersects soft wrap-introduced text. Example: // this is a long line <soft-wrap> // that| is soft-wrapped // | // | <- vertical indent // // Also it's possible that no additional intersections are added because of soft wrap: // this is a long line <soft-wrap> // | that is soft-wrapped // | // | <- vertical indent // We want to use the following approach then: // 1. Show only active indent if it crosses soft wrap-introduced text; // 2. Show indent as is if it doesn't intersect with soft wrap-introduced text; if (selected) { LinePainter2D.paint((Graphics2D)g, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, start.y, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, maxY - 1); } else { int y = start.y; int newY = start.y; SoftWrapModel softWrapModel = editor.getSoftWrapModel(); int lineHeight = editor.getLineHeight(); for (int i = Math.max(0, startLine + lineShift); i < endLine && newY < maxY; i++) { List<? extends SoftWrap> softWraps = softWrapModel.getSoftWrapsForLine(i); int logicalLineHeight = softWraps.size() * lineHeight; if (i > startLine + lineShift) { logicalLineHeight += lineHeight; // We assume that initial 'y' value points just below the target line. } if (!softWraps.isEmpty() && softWraps.get(0).getIndentInColumns() < indentColumn) { if (y < newY || i > startLine + lineShift) { // There is a possible case that soft wrap is located on indent start line. LinePainter2D.paint((Graphics2D)g, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, y, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, newY + lineHeight - 1); } newY += logicalLineHeight; y = newY; } else { newY += logicalLineHeight; } FoldRegion foldRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineEndOffset(i)); if (foldRegion != null && foldRegion.getEndOffset() < doc.getTextLength()) { i = doc.getLineNumber(foldRegion.getEndOffset()); } } if (y < maxY) { LinePainter2D.paint((Graphics2D)g, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, y, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, maxY - 1); } } }; // TODO(jacobr): some of this logic to compute what portion of the guide to // render is duplicated from RENDERER. static io.flutter.editor.LineRange getGuideLineRange(Editor editor, RangeHighlighter highlighter) { final int startOffset = highlighter.getStartOffset(); final Document doc = highlighter.getDocument(); final int textLength = doc.getTextLength(); if (startOffset >= textLength || !highlighter.isValid()) return null; final int endOffset = min(highlighter.getEndOffset(), textLength); final int endLine = doc.getLineNumber(endOffset); int off; int startLine = doc.getLineNumber(startOffset); final IndentGuideDescriptor descriptor = editor.getIndentsModel().getDescriptor(startLine, endLine); final CharSequence chars = doc.getCharsSequence(); do { final int start = doc.getLineStartOffset(startLine); final int end = doc.getLineEndOffset(startLine); off = CharArrayUtil.shiftForward(chars, start, end, " \t"); startLine--; } while (startLine > 1 && off < textLength && chars.charAt(off) == '\n'); final VisualPosition startPosition = editor.offsetToVisualPosition(off); int indentColumn = startPosition.column; // It's considered that indent guide can cross not only white space but comments, javadoc etc. Hence, there is a possible // case that the first indent guide line is, say, single-line comment where comment symbols ('//') are located at the first // visual column. We need to calculate correct indent guide column then. int lineShift = 1; if (indentColumn <= 0 && descriptor != null) { indentColumn = descriptor.indentLevel; lineShift = 0; } if (indentColumn <= 0) return null; final FoldingModel foldingModel = editor.getFoldingModel(); if (foldingModel.isOffsetCollapsed(off)) return null; final FoldRegion headerRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineEndOffset(doc.getLineNumber(off))); final FoldRegion tailRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineStartOffset(doc.getLineNumber(endOffset))); if (tailRegion != null && tailRegion == headerRegion) return null; final VisualPosition endPosition = editor.offsetToVisualPosition(endOffset); return new io.flutter.editor.LineRange(startLine, endPosition.line); } FilteredIndentsHighlightingPass(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { super(project, editor.getDocument(), false); myEditor = (EditorEx)editor; myFile = file; } public static void onWidgetIndentsChanged(EditorEx editor, WidgetIndentHitTester oldHitTester, WidgetIndentHitTester newHitTester) { final List<RangeHighlighter> highlighters = editor.getUserData(INDENT_HIGHLIGHTERS_IN_EDITOR_KEY); if (highlighters != null) { final Document doc = editor.getDocument(); final int textLength = doc.getTextLength(); for (RangeHighlighter highlighter : highlighters) { if (!highlighter.isValid()) { continue; } final LineRange range = getGuideLineRange(editor, highlighter); if (range != null) { final boolean before = WidgetIndentsHighlightingPass.isIndentGuideHidden(oldHitTester, range); final boolean after = WidgetIndentsHighlightingPass.isIndentGuideHidden(newHitTester, range); if (before != after) { int safeStart = min(highlighter.getStartOffset(), textLength); int safeEnd = min(highlighter.getEndOffset(), textLength); if (safeEnd > safeStart) { editor.repaint(safeStart, safeEnd); } } } } } } @Override public void doCollectInformation(@NotNull ProgressIndicator progress) { assert myDocument != null; final Long stamp = myEditor.getUserData(LAST_TIME_INDENTS_BUILT); if (stamp != null && stamp.longValue() == nowStamp()) return; myDescriptors = buildDescriptors(); final ArrayList<TextRange> ranges = new ArrayList<>(); for (IndentGuideDescriptor descriptor : myDescriptors) { ProgressManager.checkCanceled(); final int endOffset = descriptor.endLine < myDocument.getLineCount() ? myDocument.getLineStartOffset(descriptor.endLine) : myDocument.getTextLength(); ranges.add(new TextRange(myDocument.getLineStartOffset(descriptor.startLine), endOffset)); } Collections.sort(ranges, Segment.BY_START_OFFSET_THEN_END_OFFSET); myRanges = ranges; } private long nowStamp() { // If regular indent guides are being shown then the user has disabled // the custom WidgetIndentGuides and we should skip this pass in favor // of the regular indent guides instead of our fork. if (myEditor.getSettings().isIndentGuidesShown()) return -1; assert myDocument != null; return myDocument.getModificationStamp(); } public static void cleanupHighlighters(Editor editor) { final List<RangeHighlighter> highlighters = editor.getUserData(INDENT_HIGHLIGHTERS_IN_EDITOR_KEY); if (highlighters == null) return; for (RangeHighlighter highlighter : highlighters) { highlighter.dispose(); } editor.putUserData(INDENT_HIGHLIGHTERS_IN_EDITOR_KEY, null); editor.putUserData(LAST_TIME_INDENTS_BUILT, null); } @Override public void doApplyInformationToEditor() { final Long stamp = myEditor.getUserData(LAST_TIME_INDENTS_BUILT); if (stamp != null && stamp.longValue() == nowStamp()) return; List<RangeHighlighter> oldHighlighters = myEditor.getUserData(INDENT_HIGHLIGHTERS_IN_EDITOR_KEY); final List<RangeHighlighter> newHighlighters = new ArrayList<>(); final MarkupModel mm = myEditor.getMarkupModel(); int curRange = 0; if (oldHighlighters != null) { // after document change some range highlighters could have become invalid, or the order could have been broken oldHighlighters.sort(Comparator.comparing((RangeHighlighter h) -> !h.isValid()) .thenComparing(Segment.BY_START_OFFSET_THEN_END_OFFSET)); int curHighlight = 0; while (curRange < myRanges.size() && curHighlight < oldHighlighters.size()) { TextRange range = myRanges.get(curRange); RangeHighlighter highlighter = oldHighlighters.get(curHighlight); if (!highlighter.isValid()) break; int cmp = compare(range, highlighter); if (cmp < 0) { newHighlighters.add(createHighlighter(mm, range)); curRange++; } else if (cmp > 0) { highlighter.dispose(); curHighlight++; } else { newHighlighters.add(highlighter); curHighlight++; curRange++; } } for (; curHighlight < oldHighlighters.size(); curHighlight++) { RangeHighlighter highlighter = oldHighlighters.get(curHighlight); if (!highlighter.isValid()) break; highlighter.dispose(); } } final int startRangeIndex = curRange; assert myDocument != null; DocumentUtil.executeInBulk(myDocument, myRanges.size() > 10000, () -> { for (int i = startRangeIndex; i < myRanges.size(); i++) { newHighlighters.add(createHighlighter(mm, myRanges.get(i))); } }); myEditor.putUserData(INDENT_HIGHLIGHTERS_IN_EDITOR_KEY, newHighlighters); myEditor.putUserData(LAST_TIME_INDENTS_BUILT, nowStamp()); myEditor.getIndentsModel().assumeIndents(myDescriptors); } private List<IndentGuideDescriptor> buildDescriptors() { // If regular indent guides are being shown then the user has disabled // the custom WidgetIndentGuides and we should skip this pass in favor // of the regular indent guides instead of our fork. if (myEditor.getSettings().isIndentGuidesShown()) return Collections.emptyList(); IndentsCalculator calculator = new IndentsCalculator(); calculator.calculate(); int[] lineIndents = calculator.lineIndents; IntStack lines = new IntStack(); IntStack indents = new IntStack(); lines.push(0); indents.push(0); assert myDocument != null; List<IndentGuideDescriptor> descriptors = new ArrayList<>(); for (int line = 1; line < lineIndents.length; line++) { ProgressManager.checkCanceled(); int curIndent = Math.abs(lineIndents[line]); while (!indents.empty() && curIndent <= indents.peek()) { ProgressManager.checkCanceled(); final int level = indents.pop(); int startLine = lines.pop(); if (level > 0) { for (int i = startLine; i < line; i++) { if (level != Math.abs(lineIndents[i])) { descriptors.add(createDescriptor(level, startLine, line, lineIndents)); break; } } } } int prevLine = line - 1; int prevIndent = Math.abs(lineIndents[prevLine]); if (curIndent - prevIndent > 1) { lines.push(prevLine); indents.push(prevIndent); } } while (!indents.empty()) { ProgressManager.checkCanceled(); final int level = indents.pop(); int startLine = lines.pop(); if (level > 0) { descriptors.add(createDescriptor(level, startLine, myDocument.getLineCount(), lineIndents)); } } return descriptors; } private IndentGuideDescriptor createDescriptor(int level, int startLine, int endLine, int[] lineIndents) { while (startLine > 0 && lineIndents[startLine] < 0) startLine--; int codeConstructStartLine = findCodeConstructStartLine(startLine); return new IndentGuideDescriptor(level, codeConstructStartLine, startLine, endLine); } private int findCodeConstructStartLine(int startLine) { DocumentEx document = myEditor.getDocument(); CharSequence text = document.getImmutableCharSequence(); int lineStartOffset = document.getLineStartOffset(startLine); int firstNonWsOffset = CharArrayUtil.shiftForward(text, lineStartOffset, " \t"); FileType type = PsiUtilBase.getPsiFileAtOffset(myFile, firstNonWsOffset).getFileType(); Language language = PsiUtilCore.getLanguageAtOffset(myFile, firstNonWsOffset); BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(type, language); HighlighterIterator iterator = myEditor.getHighlighter().createIterator(firstNonWsOffset); if (braceMatcher.isLBraceToken(iterator, text, type)) { int codeConstructStart = braceMatcher.getCodeConstructStart(myFile, firstNonWsOffset); return document.getLineNumber(codeConstructStart); } else { return startLine; } } @NotNull private static RangeHighlighter createHighlighter(MarkupModel mm, TextRange range) { final RangeHighlighter highlighter = mm.addRangeHighlighter(range.getStartOffset(), range.getEndOffset(), 0, null, HighlighterTargetArea.EXACT_RANGE); highlighter.setCustomRenderer(RENDERER); return highlighter; } private static int compare(@NotNull TextRange r, @NotNull RangeHighlighter h) { int answer = r.getStartOffset() - h.getStartOffset(); return answer != 0 ? answer : r.getEndOffset() - h.getEndOffset(); } private class IndentsCalculator { @NotNull final Map<Language, TokenSet> myComments = new HashMap<>(); @NotNull final int[] lineIndents; // negative value means the line is empty (or contains a comment) and indent // (denoted by absolute value) was deduced from enclosing non-empty lines @NotNull final CharSequence myChars; IndentsCalculator() { assert myDocument != null; lineIndents = new int[myDocument.getLineCount()]; myChars = myDocument.getCharsSequence(); } /** * Calculates line indents for the {@link #myDocument target document}. */ void calculate() { assert myDocument != null; final FileType fileType = myFile.getFileType(); int tabSize = EditorUtil.getTabSize(myEditor); for (int line = 0; line < lineIndents.length; line++) { ProgressManager.checkCanceled(); int lineStart = myDocument.getLineStartOffset(line); int lineEnd = myDocument.getLineEndOffset(line); int offset = lineStart; int column = 0; outer: while (offset < lineEnd) { switch (myChars.charAt(offset)) { case ' ': column++; break; case '\t': column = (column / tabSize + 1) * tabSize; break; default: break outer; } offset++; } // treating commented lines in the same way as empty lines // Blank line marker lineIndents[line] = offset == lineEnd || isComment(offset) ? -1 : column; } int topIndent = 0; for (int line = 0; line < lineIndents.length; line++) { ProgressManager.checkCanceled(); if (lineIndents[line] >= 0) { topIndent = lineIndents[line]; } else { int startLine = line; while (line < lineIndents.length && lineIndents[line] < 0) { //noinspection AssignmentToForLoopParameter line++; } int bottomIndent = line < lineIndents.length ? lineIndents[line] : topIndent; int indent = min(topIndent, bottomIndent); if (bottomIndent < topIndent) { int lineStart = myDocument.getLineStartOffset(line); int lineEnd = myDocument.getLineEndOffset(line); int nonWhitespaceOffset = CharArrayUtil.shiftForward(myChars, lineStart, lineEnd, " \t"); HighlighterIterator iterator = myEditor.getHighlighter().createIterator(nonWhitespaceOffset); if (BraceMatchingUtil.isRBraceToken(iterator, myChars, fileType)) { indent = topIndent; } } for (int blankLine = startLine; blankLine < line; blankLine++) { assert lineIndents[blankLine] == -1; lineIndents[blankLine] = -min(topIndent, indent); } //noinspection AssignmentToForLoopParameter line--; // will be incremented back at the end of the loop; } } } private boolean isComment(int offset) { final HighlighterIterator it = myEditor.getHighlighter().createIterator(offset); IElementType tokenType = it.getTokenType(); Language language = tokenType.getLanguage(); TokenSet comments = myComments.get(language); if (comments == null) { ParserDefinition definition = LanguageParserDefinitions.INSTANCE.forLanguage(language); if (definition != null) { comments = definition.getCommentTokens(); } if (comments == null) { return false; } else { myComments.put(language, comments); } } return comments.contains(tokenType); } } }
/* * * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.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. * * * * For more information: http://www.orientechnologies.com * */ package com.orientechnologies.orient.server.hazelcast; import com.hazelcast.config.QueueConfig; import com.hazelcast.core.HazelcastException; import com.hazelcast.core.HazelcastInstanceNotActiveException; import com.hazelcast.core.IAtomicLong; import com.hazelcast.core.IQueue; import com.hazelcast.monitor.LocalQueueStats; import com.hazelcast.spi.exception.DistributedObjectDestroyedException; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.server.distributed.ODistributedMessageService; import com.orientechnologies.orient.server.distributed.ODistributedRequest; import com.orientechnologies.orient.server.distributed.ODistributedResponse; import com.orientechnologies.orient.server.distributed.ODistributedResponseManager; import com.orientechnologies.orient.server.distributed.ODistributedServerLog; import com.orientechnologies.orient.server.distributed.ODistributedServerLog.DIRECTION; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; /** * Hazelcast implementation of distributed peer. There is one instance per database. Each node creates own instance to talk with * each others. * * @author Luca Garulli (l.garulli--at--orientechnologies.com) * */ public class OHazelcastDistributedMessageService implements ODistributedMessageService { public static final int STATS_MAX_MESSAGES = 20; public static final String NODE_QUEUE_PREFIX = "orientdb.node."; public static final String NODE_QUEUE_REQUEST_POSTFIX = ".request"; public static final String NODE_QUEUE_RESPONSE_POSTFIX = ".response"; protected final OHazelcastPlugin manager; protected final IQueue<ODistributedResponse> nodeResponseQueue; protected final ConcurrentHashMap<Long, ODistributedResponseManager> responsesByRequestIds; protected final TimerTask asynchMessageManager; protected Map<String, OHazelcastDistributedDatabase> databases = new ConcurrentHashMap<String, OHazelcastDistributedDatabase>(); protected Thread responseThread; protected long[] responseTimeMetrics = new long[10]; protected int responseTimeMetricIndex = 0; protected volatile boolean running = true; public OHazelcastDistributedMessageService(final OHazelcastPlugin manager) { this.manager = manager; this.responsesByRequestIds = new ConcurrentHashMap<Long, ODistributedResponseManager>(); // RESET ALL THE METRICS for (int i = 0; i < responseTimeMetrics.length; ++i) responseTimeMetrics[i] = -1; // CREAT THE QUEUE final String queueName = getResponseQueueName(manager.getLocalNodeName()); nodeResponseQueue = getQueue(queueName); if (ODistributedServerLog.isDebugEnabled()) ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), null, DIRECTION.NONE, "listening for incoming responses on queue: %s", queueName); // TODO: CHECK IF SET TO TRUE (UNQUEUE MSG) WHEN HOT-ALIGNMENT = TRUE checkForPendingMessages(nodeResponseQueue, queueName, false); // CREATE TASK THAT CHECK ASYNCHRONOUS MESSAGE RECEIVED asynchMessageManager = new TimerTask() { @Override public void run() { purgePendingMessages(); } }; // CREATE THREAD LISTENER AGAINST orientdb.node.<node>.response, ONE PER NODE, THEN DISPATCH THE MESSAGE INTERNALLY USING THE // THREAD ID responseThread = new Thread(new Runnable() { @Override public void run() { Thread.currentThread().setName("OrientDB Node Response " + queueName); while (running) { String senderNode = null; ODistributedResponse message = null; try { message = nodeResponseQueue.take(); if (message != null) { senderNode = message.getSenderNodeName(); final long responseTime = dispatchResponseToThread(message); if (responseTime > -1) collectMetric(responseTime); } } catch (InterruptedException e) { // EXIT CURRENT THREAD Thread.interrupted(); break; } catch (DistributedObjectDestroyedException e) { Thread.interrupted(); break; } catch (HazelcastInstanceNotActiveException e) { Thread.interrupted(); break; } catch (HazelcastException e) { if (e.getCause() instanceof InterruptedException) Thread.interrupted(); else ODistributedServerLog.error(this, manager.getLocalNodeName(), senderNode, DIRECTION.IN, "error on reading distributed response", e, message != null ? message.getPayload() : "-"); } catch (Throwable e) { ODistributedServerLog.error(this, manager.getLocalNodeName(), senderNode, DIRECTION.IN, "error on reading distributed response", e, message != null ? message.getPayload() : "-"); } } ODistributedServerLog.debug(this, manager.getLocalNodeName(), null, DIRECTION.NONE, "end of reading responses"); } }); responseThread.setDaemon(true); responseThread.start(); } /** * Composes the request queue name based on node name and database. */ public static String getRequestQueueName(final String iNodeName, final String iDatabaseName) { final StringBuilder buffer = new StringBuilder(128); buffer.append(NODE_QUEUE_PREFIX); buffer.append(iNodeName); if (iDatabaseName != null) { buffer.append('.'); buffer.append(iDatabaseName); } buffer.append(NODE_QUEUE_REQUEST_POSTFIX); return buffer.toString(); } /** * Composes the response queue name based on node name. */ protected static String getResponseQueueName(final String iNodeName) { final StringBuilder buffer = new StringBuilder(128); buffer.append(NODE_QUEUE_PREFIX); buffer.append(iNodeName); buffer.append(NODE_QUEUE_RESPONSE_POSTFIX); return buffer.toString(); } public OHazelcastDistributedDatabase getDatabase(final String iDatabaseName) { return databases.get(iDatabaseName); } @Override public ODistributedRequest createRequest() { return new OHazelcastDistributedRequest(); } public void shutdown() { running = false; if (responseThread != null) { responseThread.interrupt(); if (!nodeResponseQueue.isEmpty()) try { responseThread.join(); } catch (InterruptedException e) { } responseThread = null; } for (Entry<String, OHazelcastDistributedDatabase> m : databases.entrySet()) m.getValue().shutdown(); asynchMessageManager.cancel(); responsesByRequestIds.clear(); if (nodeResponseQueue != null) { nodeResponseQueue.clear(); nodeResponseQueue.destroy(); } } public void registerRequest(final long id, final ODistributedResponseManager currentResponseMgr) { responsesByRequestIds.put(id, currentResponseMgr); } public void handleUnreachableNode(final String nodeName) { final Set<String> dbs = getDatabases(); if (dbs != null) for (String dbName : dbs) getDatabase(dbName).removeNodeInConfiguration(nodeName, false); // REMOVE THE SERVER'S RESPONSE QUEUE // removeQueue(OHazelcastDistributedMessageService.getResponseQueueName(nodeName)); for (ODistributedResponseManager r : responsesByRequestIds.values()) r.notifyWaiters(); } @Override public List<String> getManagedQueueNames() { List<String> queueNames = new ArrayList<String>(); for (String q : manager.getHazelcastInstance().getConfig().getQueueConfigs().keySet()) { if (q.startsWith(NODE_QUEUE_PREFIX)) queueNames.add(q); } return queueNames; } @Override public long getLastMessageId() { return getMessageIdCounter().get(); } public IAtomicLong getMessageIdCounter() { return manager.getHazelcastInstance().getAtomicLong("orientdb.requestId"); } @Override public ODocument getQueueStats(final String iQueueName) { final IQueue<Object> queue = manager.getHazelcastInstance().getQueue(iQueueName); if (queue == null) throw new IllegalArgumentException("Queue '" + iQueueName + "' not found"); final ODocument doc = new ODocument(); doc.field("name", queue.getName()); doc.field("partitionKey", queue.getPartitionKey()); doc.field("serviceName", queue.getServiceName()); doc.field("size", queue.size()); // doc.field("nextElement", queue.peek()); final LocalQueueStats stats = queue.getLocalQueueStats(); doc.field("minAge", stats.getMinAge()); doc.field("maxAge", stats.getMaxAge()); doc.field("avgAge", stats.getAvgAge()); doc.field("backupItemCount", stats.getBackupItemCount()); doc.field("emptyPollOperationCount", stats.getEmptyPollOperationCount()); doc.field("offerOperationCount", stats.getOfferOperationCount()); doc.field("eventOperationCount", stats.getEventOperationCount()); doc.field("otherOperationsCount", stats.getOtherOperationsCount()); doc.field("pollOperationCount", stats.getPollOperationCount()); doc.field("emptyPollOperationCount", stats.getEmptyPollOperationCount()); doc.field("ownedItemCount", stats.getOwnedItemCount()); doc.field("rejectedOfferOperationCount", stats.getRejectedOfferOperationCount()); List<Object> nextMessages = new ArrayList<Object>(STATS_MAX_MESSAGES); for (Iterator<Object> it = queue.iterator(); it.hasNext();) { Object next = it.next(); if (next != null) nextMessages.add(next.toString()); if (nextMessages.size() >= STATS_MAX_MESSAGES) break; } doc.field("nextMessages", nextMessages); return doc; } public long getAverageResponseTime() { long total = 0; int involved = 0; for (long metric : responseTimeMetrics) { if (metric > -1) { total += metric; involved++; } } return total > 0 ? total / involved : 0; } public OHazelcastDistributedDatabase registerDatabase(final String iDatabaseName) { final OHazelcastDistributedDatabase db = new OHazelcastDistributedDatabase(manager, this, iDatabaseName); databases.put(iDatabaseName, db); return db; } public Set<String> getDatabases() { return databases.keySet(); } /** * Not synchronized, it's called when a message arrives * * @param response */ protected long dispatchResponseToThread(final ODistributedResponse response) { final long chrono = Orient.instance().getProfiler().startChrono(); try { final long reqId = response.getRequestId(); // GET ASYNCHRONOUS MSG MANAGER IF ANY final ODistributedResponseManager asynchMgr = responsesByRequestIds.get(reqId); if (asynchMgr == null) { if (ODistributedServerLog.isDebugEnabled()) ODistributedServerLog.debug(this, manager.getLocalNodeName(), response.getExecutorNodeName(), DIRECTION.IN, "received response for message %d after the timeout (%dms)", reqId, OGlobalConfiguration.DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT.getValueAsLong()); } else if (asynchMgr.collectResponse(response)) { // ALL RESPONSE RECEIVED, REMOVE THE RESPONSE MANAGER WITHOUT WAITING THE PURGE THREAD REMOVE THEM FOR TIMEOUT responsesByRequestIds.remove(reqId); // RETURN THE ASYNCH RESPONSE TIME return System.currentTimeMillis() - asynchMgr.getSentOn(); } } finally { Orient.instance().getProfiler() .stopChrono("distributed.node." + response.getExecutorNodeName() + ".latency", "Latency in ms from current node", chrono); Orient .instance() .getProfiler() .updateCounter("distributed.node.msgReceived", "Number of replication messages received in current node", +1, "distributed.node.msgReceived"); Orient .instance() .getProfiler() .updateCounter("distributed.node." + response.getExecutorNodeName() + ".msgReceived", "Number of replication messages received in current node from a node", +1, "distributed.node.*.msgReceived"); } return -1; } protected String getLocalNodeNameAndThread() { return manager.getLocalNodeName() + ":" + Thread.currentThread().getId(); } protected void purgePendingMessages() { final long now = System.currentTimeMillis(); final long timeout = OGlobalConfiguration.DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT.getValueAsLong(); for (Iterator<Entry<Long, ODistributedResponseManager>> it = responsesByRequestIds.entrySet().iterator(); it.hasNext();) { final Entry<Long, ODistributedResponseManager> item = it.next(); final ODistributedResponseManager resp = item.getValue(); final long timeElapsed = now - resp.getSentOn(); if (timeElapsed > timeout) { // EXPIRED REQUEST, FREE IT! final List<String> missingNodes = resp.getMissingNodes(); ODistributedServerLog.warn(this, manager.getLocalNodeName(), missingNodes.toString(), DIRECTION.IN, "%d missed response(s) for message %d by nodes %s after %dms when timeout is %dms", missingNodes.size(), resp.getMessageId(), missingNodes, timeElapsed, timeout); Orient .instance() .getProfiler() .updateCounter("distributed.db." + resp.getDatabaseName() + ".timeouts", "Number of messages in timeouts", +1, "distributed.db.*.timeouts"); Orient.instance().getProfiler() .updateCounter("distributed.node.timeouts", "Number of messages in timeouts", +1, "distributed.node.timeouts"); resp.timeout(); it.remove(); } } } protected boolean checkForPendingMessages(final IQueue<?> iQueue, final String iQueueName, final boolean iUnqueuePendingMessages) { final int queueSize = iQueue.size(); if (queueSize > 0) { if (!iUnqueuePendingMessages) { ODistributedServerLog.warn(this, manager.getLocalNodeName(), null, DIRECTION.NONE, "found %d messages in queue %s, clearing them...", queueSize, iQueueName); iQueue.clear(); } else { ODistributedServerLog.warn(this, manager.getLocalNodeName(), null, DIRECTION.NONE, "found %d messages in queue %s, aligning the database...", queueSize, iQueueName); return true; } } else ODistributedServerLog.info(this, manager.getLocalNodeName(), null, DIRECTION.NONE, "found no previous messages in queue %s", iQueueName); return false; } /** * Returns the queue. If not exists create and register it. */ public <T> IQueue<T> getQueue(final String iQueueName) { // configureQueue(iQueueName, 0, 0); return manager.getHazelcastInstance().getQueue(iQueueName); } protected void configureQueue(final String iQueueName, final int synchReplica, final int asynchReplica) { final QueueConfig queueCfg = manager.getHazelcastInstance().getConfig().getQueueConfig(iQueueName); queueCfg.setBackupCount(synchReplica); queueCfg.setAsyncBackupCount(asynchReplica); } /** * Removes the queue. Hazelcast doesn't allow to remove the queue, so now we just clear it. */ protected void removeQueue(final String iQueueName) { final IQueue<?> queue = manager.getHazelcastInstance().getQueue(iQueueName); if (queue != null) { ODistributedServerLog.info(this, manager.getLocalNodeName(), null, DIRECTION.NONE, "removing queue '%s' containing %d messages", iQueueName, queue.size()); queue.clear(); } } protected void collectMetric(final long iTime) { if (responseTimeMetricIndex >= responseTimeMetrics.length) responseTimeMetricIndex = 0; responseTimeMetrics[responseTimeMetricIndex++] = iTime; } }
package nl.weeaboo.entity; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.ObjectStreamException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import nl.weeaboo.io.IReadResolveSerializable; import nl.weeaboo.io.IWriteReplaceSerializable; /** * The environment for the entity system. Entities get a reference to this class * when constructed. */ public final class Scene implements IWriteReplaceSerializable { private static final long serialVersionUID = 1L; // ------------------------------------------------------------------------- // * Attributes must be serialized manually // * Update reset method after adding/removing attributes // ------------------------------------------------------------------------- transient World world; private final int id; // Unique scene identifier private boolean enabled = true; private final transient EntityManager entityManager = new EntityManager(this); private final transient PartManager partManager = new PartManager(this); private final transient CopyOnWriteArrayList<IEntityListener> entityListeners = new CopyOnWriteArrayList<IEntityListener>(); private final transient CopyOnWriteArrayList<IPartListener> partListeners = new CopyOnWriteArrayList<IPartListener>(); // ------------------------------------------------------------------------- Scene(World w, int id) { this.world = w; this.id = id; } @Override public Object writeReplace() { return new SceneRef(world, id); } private void reset() { enabled = true; entityManager.reset(); partManager.reset(); entityListeners.clear(); partListeners.clear(); } void serialize(ObjectOutput out) throws IOException { out.writeBoolean(enabled); entityManager.serialize(out); partManager.serialize(); out.writeInt(entityListeners.size()); for (IEntityListener listener : entityListeners) { out.writeObject(listener); } out.writeInt(partListeners.size()); for (IPartListener listener : partListeners) { out.writeObject(listener); } } void deserialize(World w, ObjectInput in) throws IOException, ClassNotFoundException { reset(); this.world = w; enabled = in.readBoolean(); entityManager.deserialize(this, in); partManager.deserialize(this); int entityListenersL = in.readInt(); for (int n = 0; n < entityListenersL; n++) { entityListeners.add((IEntityListener)in.readObject()); } int partListenersL = in.readInt(); for (int n = 0; n < partListenersL; n++) { partListeners.add((IPartListener)in.readObject()); } } /** * Destroys the scene and everything in it. */ public final void destroy() { clear(); if (world != null) { world.onSceneDestroyed(this); } } /** * Returns {@code true} if this scene is destroyed. * @see #destroy() */ public final boolean isDestroyed() { return world == null; } /** * The unique scene ID. */ public int getId() { return id; } /** * @return {@code true} if this scene is enabled. * * @see #setEnabled(boolean) */ public boolean isEnabled() { return enabled; } /** * Enables or disables this scene. The enabled state can be used by the * application to temporarily mark a scene as paused. */ public void setEnabled(boolean e) { enabled = e; } /** * Attaches a new entity listener. */ public void addEntityListener(IEntityListener el) { entityListeners.add(el); } /** * Removes a previously attached entity listener. */ public void removeEntityListener(IEntityListener el) { entityListeners.remove(el); } /** * Attaches a new part listener. */ public void addPartListener(IPartListener pl) { partListeners.add(pl); } /** * Removes a previously attached part listener. */ public void removePartListener(IPartListener pl) { partListeners.remove(pl); } /** * Sends a part-propert-changed event to all part listeners in the scene. * * @see World#firePartPropertyChanged(IPart, String, Object) */ void firePartPropertyChanged(IPart part, String propertyName, Object newValue) { boolean invalidated = false; for (Entity e : partManager.entitiesWithPart(part)) { if (!invalidated) { invalidated = true; entityManager.invalidateStreams(); } for (IPartListener pl : partListeners) { pl.onPartPropertyChanged(e, part, propertyName, newValue); } } } /** * Creates a new entity and registers it with this world. */ public Entity createEntity() { Entity e = new Entity(this, entityManager.generateId()); for (IEntityListener el : entityListeners) { el.onEntityCreated(e); } registerEntity(e, true); return e; } /** * Removes a destroyed entity from this scene. */ void onEntityDestroyed(Entity e) { boolean destroyed = unregisterEntity(e, true); if (destroyed) { for (IEntityListener el : entityListeners) { el.onEntityDestroyed(e); } } } /** * Registers an entity (used during deserialization). */ void registerEntity(Entity e, boolean notifyListeners) { e.scene = this; entityManager.add(e); if (notifyListeners) { for (IEntityListener el : entityListeners) { el.onEntityAttached(this, e); } } for (IPart p : e.parts()) { registerPart(e, p, notifyListeners); } } /** * Unregisters an entity (used when moving entities between Scenes). * * @return <code>true</code> if the entity was successfully removed, * <code>false</code> if the entity couldn't be removed because it * wasn't attached to this scene. */ boolean unregisterEntity(Entity e, boolean notifyListeners) { if (!entityManager.remove(e)) { return false; } e.scene = null; if (notifyListeners) { for (IEntityListener el : entityListeners) { el.onEntityDetached(this, e); } } for (IPart p : e.parts()) { unregisterPart(e, p, notifyListeners); } return true; } /** * Destroys and removes all entities from this scene. */ public void clear() { List<Entity> entities = getEntities(); //Reverse order removes the entities more efficiently from the arraylist that stores them. Collections.reverse(entities); for (Entity e : entities) { e.destroy(); } } /** * Creates (or joins an existing) EntityStream representing a filtered and sorted view of the collection * of entities. */ public EntityStream joinStream(EntityStreamDef esd) { return entityManager.joinStream(esd); } /** * Removes a previously joined stream. * * @see #joinStream(EntityStreamDef) */ public boolean removeStream(EntityStreamDef esd) { return entityManager.removeStream(esd); } /** * Returns all entities attached to this scene. */ public List<Entity> getEntities() { List<Entity> out = new ArrayList<Entity>(getEntitiesCount()); getEntities(out); return out; } /** * Adds all entities attached to this scene to the supplied output collection. */ public void getEntities(Collection<Entity> out) { entityManager.getEntities(out); } /** * The number of entities attaches to this scene. */ public int getEntitiesCount() { return entityManager.getEntitiesCount(); } /** * Returns the entity with the given ID, or {@code null} if no such entity was attached to this scene. */ public Entity getEntity(int id) { return entityManager.getEntity(id); } /** * Returns {@code true} if this scene contains the specified entity. */ public boolean contains(Entity e) { return e != null && contains(e.getId()); } /** * Returns {@code true} if this scene contains the entity with the specified ID. */ public boolean contains(int id) { return getEntity(id) != null; } void registerPart(Entity e, IPart p, boolean notifyListeners) { boolean newlyAttached = !partManager.contains(p); partManager.add(e, p); if (newlyAttached) { p.onAttached(this); } entityManager.invalidateStreams(); if (notifyListeners) { for (IPartListener pl : partListeners) { pl.onPartAttached(e, p); } } } void unregisterPart(Entity e, IPart p, boolean notifyListeners) { partManager.remove(e, p); entityManager.invalidateStreams(); if (notifyListeners) { for (IPartListener pl : partListeners) { pl.onPartDetached(e, p); } } if (!partManager.contains(p)) { p.onDetached(this); } } private static class SceneRef implements IReadResolveSerializable { private static final long serialVersionUID = Scene.serialVersionUID; private final World world; private final int id; public SceneRef(World w, int id) { this.world = w; this.id = id; } @Override public Object readResolve() throws ObjectStreamException { Scene scene = world.getScene(id); if (scene == null) { throw new InvalidObjectException("Scene lost during serialization: " + id); } return scene; } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.sqoop.metastore; import static org.junit.Assert.assertEquals; import com.cloudera.sqoop.SqoopOptions; import com.cloudera.sqoop.testutil.BaseSqoopTestCase; import com.cloudera.sqoop.testutil.CommonArgs; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.sqoop.manager.ConnManager; import org.apache.sqoop.manager.DefaultManagerFactory; import org.apache.sqoop.tool.JobTool; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; /** * Base test class for Incremental Import Metastore data, implemented for specific database services in sub-classes */ public abstract class MetaConnectIncrementalImportTestBase extends BaseSqoopTestCase { public static final Log LOG = LogFactory .getLog(MetaConnectIncrementalImportTestBase.class.getName()); private String metaConnectString; private String metaUser; private String metaPass; private Connection connMeta; private ConnManager cm; public MetaConnectIncrementalImportTestBase(String metaConnectString, String metaUser, String metaPass) { this.metaConnectString = metaConnectString; this.metaUser = metaUser; this.metaPass = metaPass; } @Before public void setUp() { super.setUp(); } @After public void tearDown() { super.tearDown(); } protected String[] getIncrementalJob(String metaConnectString, String metaUser, String metaPass) { List<String> args = new ArrayList<>(); CommonArgs.addHadoopFlags(args); args.add("--create"); args.add("testJob"); args.add("--meta-connect"); args.add(metaConnectString); args.add("--meta-username"); args.add(metaUser); args.add("--meta-password"); args.add(metaPass); args.add("--"); args.add("import"); args.add("-m"); args.add("1"); args.add("--connect"); args.add(getConnectString()); args.add("--table"); args.add("CARLOCATIONS"); args.add("--incremental"); args.add("append"); args.add("--check-column"); args.add("CARID"); args.add("--last-value"); args.add("0"); args.add("--as-textfile"); return args.toArray(new String[0]); } protected String[] getExecJob(String metaConnectString, String metaUser, String metaPass) { List<String> args = new ArrayList<>(); CommonArgs.addHadoopFlags(args); args.add("--exec"); args.add("testJob"); args.add("--meta-connect"); args.add(metaConnectString); args.add("--meta-username"); args.add(metaUser); args.add("--meta-password"); args.add(metaPass); return args.toArray(new String[0]); } @Test public void testIncrementalJob() throws SQLException { resetTable(); initMetastoreConnection(); resetMetastoreSchema(); //creates Job createJob(); //Executes the import execJob(); //Ensures the saveIncrementalState saved the right row checkIncrementalState(1); //Adds rows to the import table Statement insertStmt = getConnection().createStatement(); insertStmt.executeUpdate("INSERT INTO CARLOCATIONS VALUES (2, 'lexus')"); getConnection().commit(); //Execute the import again execJob(); //Ensures the last incremental value is updated correctly. checkIncrementalState(2); cm.close(); } private void checkIncrementalState(int expected) throws SQLException { Statement getSaveIncrementalState = connMeta.createStatement(); ResultSet lastCol = getSaveIncrementalState.executeQuery( "SELECT propVal FROM " + cm.escapeTableName("SQOOP_SESSIONS") + " WHERE propname = 'incremental.last.value'"); lastCol.next(); assertEquals("Last row value differs from expected", expected, lastCol.getInt("propVal")); } private void execJob() { JobTool jobToolExec = new JobTool(); org.apache.sqoop.Sqoop sqoopExec = new org.apache.sqoop.Sqoop(jobToolExec); String[] argsExec = getExecJob(metaConnectString, metaUser, metaPass); assertEquals("Sqoop Job did not execute properly", 0, org.apache.sqoop.Sqoop.runSqoop(sqoopExec, argsExec)); } private void createJob() { Configuration conf = new Configuration(); conf.set(org.apache.sqoop.SqoopOptions.METASTORE_PASSWORD_KEY, "true"); JobTool jobToolCreate = new JobTool(); org.apache.sqoop.Sqoop sqoopCreate = new org.apache.sqoop.Sqoop(jobToolCreate, conf); String[] argsCreate = getIncrementalJob(metaConnectString, metaUser, metaPass); org.apache.sqoop.Sqoop.runSqoop(sqoopCreate, argsCreate); } private void resetTable() throws SQLException { //Resets the target table dropTableIfExists("CARLOCATIONS"); setCurTableName("CARLOCATIONS"); createTableWithColTypesAndNames( new String [] {"CARID", "LOCATIONS"}, new String [] {"INTEGER", "VARCHAR"}, new String [] {"1", "'Lexus'"}); } private void resetMetastoreSchema() { try { //Resets the metastore schema Statement metastoreStatement = connMeta.createStatement(); metastoreStatement.execute("DROP TABLE " + cm.escapeTableName("SQOOP_ROOT")); metastoreStatement.execute("DROP TABLE " + cm.escapeTableName("SQOOP_SESSIONS")); connMeta.commit(); } catch (Exception e) { LOG.error( e.getLocalizedMessage() ); } } private void initMetastoreConnection() throws SQLException{ SqoopOptions options = new SqoopOptions(); options.setConnectString(metaConnectString); options.setUsername(metaUser); options.setPassword(metaPass); com.cloudera.sqoop.metastore.JobData jd = new com.cloudera.sqoop.metastore.JobData(options, new JobTool()); DefaultManagerFactory dmf = new DefaultManagerFactory(); cm = dmf.accept(jd); connMeta= cm.getConnection(); } }
/* * Copyright (C) 2007 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.dx.ssa; import com.android.dx.rop.code.Insn; import com.android.dx.rop.code.LocalItem; import com.android.dx.rop.code.RegisterSpec; import com.android.dx.rop.code.RegisterSpecList; import com.android.dx.rop.code.Rop; import com.android.dx.util.ToHuman; /** * An instruction in SSA form */ public abstract class SsaInsn implements ToHuman, Cloneable { /** {@code non-null;} the block that contains this instance */ private final SsaBasicBlock block; /** {@code null-ok;} result register */ private RegisterSpec result; /** * Constructs an instance. * * @param result {@code null-ok;} initial result register. May be changed. * @param block {@code non-null;} block containing this insn. Can * never change. */ protected SsaInsn(RegisterSpec result, SsaBasicBlock block) { if (block == null) { throw new NullPointerException("block == null"); } this.block = block; this.result = result; } /** * Makes a new SSA insn form a rop insn. * * @param insn {@code non-null;} rop insn * @param block {@code non-null;} owning block * @return {@code non-null;} an appropriately constructed instance */ public static SsaInsn makeFromRop(Insn insn, SsaBasicBlock block) { return new NormalSsaInsn(insn, block); } /** {@inheritDoc} */ @Override public SsaInsn clone() { try { return (SsaInsn)super.clone(); } catch (CloneNotSupportedException ex) { throw new RuntimeException ("unexpected", ex); } } /** * Like {@link com.android.dx.rop.code.Insn getResult()}. * * @return result register */ public RegisterSpec getResult() { return result; } /** * Set the result register. * * @param result {@code non-null;} the new result register */ protected void setResult(RegisterSpec result) { if (result == null) { throw new NullPointerException("result == null"); } this.result = result; } /** * Like {@link com.android.dx.rop.code.Insn getSources()}. * * @return {@code non-null;} sources list */ abstract public RegisterSpecList getSources(); /** * Gets the block to which this insn instance belongs. * * @return owning block */ public SsaBasicBlock getBlock() { return block; } /** * Returns whether or not the specified reg is the result reg. * * @param reg register to test * @return true if there is a result and it is stored in the specified * register */ public boolean isResultReg(int reg) { return result != null && result.getReg() == reg; } /** * Changes the result register if this insn has a result. This is used * during renaming. * * @param reg new result register */ public void changeResultReg(int reg) { if (result != null) { result = result.withReg(reg); } } /** * Sets the local association for the result of this insn. This is * sometimes updated during the SsaRenamer process. * * @param local {@code null-ok;} new debug/local variable info */ public final void setResultLocal(LocalItem local) { LocalItem oldItem = result.getLocalItem(); if (local != oldItem && (local == null || !local.equals(result.getLocalItem()))) { result = RegisterSpec.makeLocalOptional( result.getReg(), result.getType(), local); } } /** * Map registers after register allocation. * * @param mapper {@code non-null;} mapping from old to new registers */ public final void mapRegisters(RegisterMapper mapper) { RegisterSpec oldResult = result; result = mapper.map(result); block.getParent().updateOneDefinition(this, oldResult); mapSourceRegisters(mapper); } /** * Maps only source registers. * * @param mapper new mapping */ abstract public void mapSourceRegisters(RegisterMapper mapper); /** * Returns the Rop opcode for this insn, or null if this is a phi insn. * * TODO: Move this up into NormalSsaInsn. * * @return {@code null-ok;} Rop opcode if there is one. */ abstract public Rop getOpcode(); /** * Returns the original Rop insn for this insn, or null if this is * a phi insn. * * TODO: Move this up into NormalSsaInsn. * * @return {@code null-ok;} Rop insn if there is one. */ abstract public Insn getOriginalRopInsn(); /** * Gets the spec of a local variable assignment that occurs at this * instruction, or null if no local variable assignment occurs. This * may be the result register, or for {@code mark-local} insns * it may be the source. * * @see com.android.dx.rop.code.Insn#getLocalAssignment() * * @return {@code null-ok;} a local-associated register spec or null */ public RegisterSpec getLocalAssignment() { if (result != null && result.getLocalItem() != null) { return result; } return null; } /** * Indicates whether the specified register is amongst the registers * used as sources for this instruction. * * @param reg the register in question * @return true if the reg is a source */ public boolean isRegASource(int reg) { return null != getSources().specForRegister(reg); } /** * Transform back to ROP form. * * TODO: Move this up into NormalSsaInsn. * * @return {@code non-null;} a ROP representation of this instruction, with * updated registers. */ public abstract Insn toRopInsn(); /** * @return true if this is a PhiInsn or a normal move insn */ public abstract boolean isPhiOrMove(); /** * Returns true if this insn is considered to have a side effect beyond * that of assigning to the result reg. * * @return true if this insn is considered to have a side effect beyond * that of assigning to the result reg. */ public abstract boolean hasSideEffect(); /** * @return true if this is a move (but not a move-operand or * move-exception) instruction */ public boolean isNormalMoveInsn() { return false; } /** * @return true if this is a move-exception instruction. * These instructions must immediately follow a preceeding invoke* */ public boolean isMoveException() { return false; } /** * @return true if this instruction can throw. */ abstract public boolean canThrow(); /** * Accepts a visitor. * * @param v {@code non-null} the visitor */ public abstract void accept(Visitor v); /** * Visitor interface for this class. */ public static interface Visitor { /** * Any non-phi move instruction * @param insn {@code non-null;} the instruction to visit */ public void visitMoveInsn(NormalSsaInsn insn); /** * Any phi insn * @param insn {@code non-null;} the instruction to visit */ public void visitPhiInsn(PhiInsn insn); /** * Any insn that isn't a move or a phi (which is also a move). * @param insn {@code non-null;} the instruction to visit */ public void visitNonMoveInsn(NormalSsaInsn insn); } }
package com.intellij.tasks.pivotal; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.tasks.*; import com.intellij.tasks.impl.BaseRepository; import com.intellij.tasks.impl.BaseRepositoryImpl; import com.intellij.tasks.impl.SimpleComment; import com.intellij.tasks.impl.TaskUtil; import com.intellij.util.NullableFunction; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.net.HTTPMethod; import com.intellij.util.xmlb.annotations.Tag; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Dennis.Ushakov * * TODO: update to REST APIv5 */ @Tag("PivotalTracker") public class PivotalTrackerRepository extends BaseRepositoryImpl { private static final Logger LOG = Logger.getInstance("#com.intellij.tasks.pivotal.PivotalTrackerRepository"); private static final String API_URL = "/services/v3"; private Pattern myPattern; private String myProjectId; private String myAPIKey; //private boolean myTasksSupport = false; { if (StringUtil.isEmpty(getUrl())) { setUrl("http://www.pivotaltracker.com"); } } /** for serialization */ @SuppressWarnings({"UnusedDeclaration"}) public PivotalTrackerRepository() { myCommitMessageFormat = "[fixes #{number}] {summary}"; } public PivotalTrackerRepository(final PivotalTrackerRepositoryType type) { super(type); } private PivotalTrackerRepository(final PivotalTrackerRepository other) { super(other); setProjectId(other.myProjectId); setAPIKey(other.myAPIKey); } @Override public void testConnection() throws Exception { getIssues("", 10, 0); } @Override public boolean isConfigured() { return super.isConfigured() && StringUtil.isNotEmpty(getProjectId()) && StringUtil.isNotEmpty(getAPIKey()); } @Override public Task[] getIssues(@Nullable final String query, final int max, final long since) throws Exception { List<Element> children = getStories(query, max); final List<Task> tasks = ContainerUtil.mapNotNull(children, (NullableFunction<Element, Task>)o -> createIssue(o)); return tasks.toArray(new Task[tasks.size()]); } private List<Element> getStories(@Nullable final String query, final int max) throws Exception { String url = API_URL + "/projects/" + myProjectId + "/stories"; url += "?filter=" + encodeUrl("state:started,unstarted,unscheduled,rejected"); if (!StringUtil.isEmpty(query)) { url += encodeUrl(" \"" + query + '"'); } if (max >= 0) { url += "&limit=" + encodeUrl(String.valueOf(max)); } LOG.info("Getting all the stories with url: " + url); final HttpMethod method = doREST(url, HTTPMethod.GET); final InputStream stream = method.getResponseBodyAsStream(); final Element element = new SAXBuilder(false).build(stream).getRootElement(); if (!"stories".equals(element.getName())) { LOG.warn("Error fetching issues for: " + url + ", HTTP status code: " + method.getStatusCode()); throw new Exception("Error fetching issues for: " + url + ", HTTP status code: " + method.getStatusCode() + "\n" + element.getText()); } return element.getChildren("story"); } @Nullable private Task createIssue(final Element element) { final String id = element.getChildText("id"); if (id == null) { return null; } final String summary = element.getChildText("name"); if (summary == null) { return null; } final String type = element.getChildText("story_type"); if (type == null) { return null; } final Comment[] comments = parseComments(element.getChild("notes")); final boolean isClosed = "accepted".equals(element.getChildText("state")) || "delivered".equals(element.getChildText("state")) || "finished".equals(element.getChildText("state")); final String description = element.getChildText("description"); final Ref<Date> updated = new Ref<>(); final Ref<Date> created = new Ref<>(); try { updated.set(parseDate(element, "updated_at")); created.set(parseDate(element, "created_at")); } catch (ParseException e) { LOG.warn(e); } return new Task() { @Override public boolean isIssue() { return true; } @Override public String getIssueUrl() { final String id = getRealId(getId()); return id != null ? getUrl() + "/story/show/" + id : null; } @NotNull @Override public String getId() { return myProjectId + "-" + id; } @NotNull @Override public String getSummary() { return summary; } public String getDescription() { return description; } @NotNull @Override public Comment[] getComments() { return comments; } @NotNull @Override public Icon getIcon() { return IconLoader.getIcon(getCustomIcon(), PivotalTrackerRepository.class); } @NotNull @Override public TaskType getType() { return TaskType.OTHER; } @Override public Date getUpdated() { return updated.get(); } @Override public Date getCreated() { return created.get(); } @Override public boolean isClosed() { return isClosed; } @Override public TaskRepository getRepository() { return PivotalTrackerRepository.this; } @Override public String getPresentableName() { return getId() + ": " + getSummary(); } @NotNull @Override public String getCustomIcon() { return "/icons/pivotal/" + type + ".png"; } }; } private static Comment[] parseComments(Element notes) { if (notes == null) return Comment.EMPTY_ARRAY; final List<Comment> result = new ArrayList<>(); //noinspection unchecked for (Element note : (List<Element>)notes.getChildren("note")) { final String text = note.getChildText("text"); if (text == null) continue; final Ref<Date> date = new Ref<>(); try { date.set(parseDate(note, "noted_at")); } catch (ParseException e) { LOG.warn(e); } final String author = note.getChildText("author"); result.add(new SimpleComment(date.get(), author, text)); } return result.toArray(new Comment[result.size()]); } @Nullable private static Date parseDate(final Element element, final String name) throws ParseException { String date = element.getChildText(name); return TaskUtil.parseDate(date); } private HttpMethod doREST(final String request, final HTTPMethod type) throws Exception { final HttpClient client = getHttpClient(); client.getParams().setContentCharset("UTF-8"); final String uri = getUrl() + request; final HttpMethod method = type == HTTPMethod.POST ? new PostMethod(uri) : type == HTTPMethod.PUT ? new PutMethod(uri) : new GetMethod(uri); configureHttpMethod(method); client.executeMethod(method); return method; } @Nullable @Override public Task findTask(@NotNull final String id) throws Exception { final String realId = getRealId(id); if (realId == null) return null; final String url = API_URL + "/projects/" + myProjectId + "/stories/" + realId; LOG.info("Retrieving issue by id: " + url); final HttpMethod method = doREST(url, HTTPMethod.GET); final InputStream stream = method.getResponseBodyAsStream(); final Element element = new SAXBuilder(false).build(stream).getRootElement(); return element.getName().equals("story") ? createIssue(element) : null; } @Nullable private String getRealId(final String id) { final String[] split = id.split("\\-"); final String projectId = split[0]; return Comparing.strEqual(projectId, myProjectId) ? split[1] : null; } @Nullable public String extractId(@NotNull final String taskName) { Matcher matcher = myPattern.matcher(taskName); return matcher.find() ? matcher.group(1) : null; } @NotNull @Override public BaseRepository clone() { return new PivotalTrackerRepository(this); } @Override protected void configureHttpMethod(final HttpMethod method) { method.addRequestHeader("X-TrackerToken", myAPIKey); } public String getProjectId() { return myProjectId; } public void setProjectId(final String projectId) { myProjectId = projectId; myPattern = Pattern.compile("(" + projectId + "\\-\\d+):\\s+"); } public String getAPIKey() { return myAPIKey; } public void setAPIKey(final String APIKey) { myAPIKey = APIKey; } @Override public String getPresentableName() { final String name = super.getPresentableName(); return name + (!StringUtil.isEmpty(getProjectId()) ? "/" + getProjectId() : ""); } @Nullable @Override public String getTaskComment(@NotNull final Task task) { if (isShouldFormatCommitMessage()) { final String id = task.getId(); final String realId = getRealId(id); return realId != null ? myCommitMessageFormat.replace("{id}", realId).replace("{project}", myProjectId) + " " + task.getSummary() : null; } return super.getTaskComment(task); } @Override public void setTaskState(@NotNull Task task, @NotNull TaskState state) throws Exception { final String realId = getRealId(task.getId()); if (realId == null) return; final String stateName; switch (state) { case IN_PROGRESS: stateName = "started"; break; case RESOLVED: stateName = "finished"; break; // may add some others in future default: return; } String url = API_URL + "/projects/" + myProjectId + "/stories/" + realId; url += "?" + encodeUrl("story[current_state]") + "=" + encodeUrl(stateName); LOG.info("Updating issue state by id: " + url); final HttpMethod method = doREST(url, HTTPMethod.PUT); final InputStream stream = method.getResponseBodyAsStream(); final Element element = new SAXBuilder(false).build(stream).getRootElement(); if (!element.getName().equals("story")) { if (element.getName().equals("errors")) { throw new Exception(extractErrorMessage(element)); } else { // unknown error, probably our fault LOG.warn("Error setting state for: " + url + ", HTTP status code: " + method.getStatusCode()); throw new Exception(String.format("Cannot set state '%s' for issue.", stateName)); } } } @NotNull private static String extractErrorMessage(@NotNull Element element) { return StringUtil.notNullize(element.getChild("error").getText()); } @Override public boolean equals(final Object o) { if (!super.equals(o)) return false; if (!(o instanceof PivotalTrackerRepository)) return false; final PivotalTrackerRepository that = (PivotalTrackerRepository)o; if (getAPIKey() != null ? !getAPIKey().equals(that.getAPIKey()) : that.getAPIKey() != null) return false; if (getProjectId() != null ? !getProjectId().equals(that.getProjectId()) : that.getProjectId() != null) return false; if (getCommitMessageFormat() != null ? !getCommitMessageFormat().equals(that.getCommitMessageFormat()) : that.getCommitMessageFormat() != null) return false; return isShouldFormatCommitMessage() == that.isShouldFormatCommitMessage(); } @Override protected int getFeatures() { return super.getFeatures() | BASIC_HTTP_AUTHORIZATION | STATE_UPDATING; } }
/* * Copyright (C) 2005-2008 Jive Software. 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 org.jivesoftware.openfire.nio; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.filter.codec.ProtocolDecoderException; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.PropertyEventDispatcher; import org.jivesoftware.util.PropertyEventListener; /** * This is a Light-Weight XML Parser. * It read data from a channel and collect data until data are available in * the channel. * When a message is complete you can retrieve messages invoking the method * getMsgs() and you can invoke the method areThereMsgs() to know if at least * an message is presents. * * @author Daniele Piras * @author Gaston Dombiak */ class XMLLightweightParser { private static final Pattern XML_HAS_CHARREF = Pattern.compile("&#(0*([0-9]+)|[xX]0*([0-9a-fA-F]+));"); private static final String MAX_PROPERTY_NAME = "xmpp.parser.buffer.size"; private static int maxBufferSize; // Chars that rappresent CDATA section start protected static char[] CDATA_START = {'<', '!', '[', 'C', 'D', 'A', 'T', 'A', '['}; // Chars that rappresent CDATA section end protected static char[] CDATA_END = {']', ']', '>'}; // Buffer with all data retrieved protected StringBuilder buffer = new StringBuilder(); // ---- INTERNAL STATUS ------- // Initial status protected static final int INIT = 0; // Status used when the first tag name is retrieved protected static final int HEAD = 2; // Status used when robot is inside the xml and it looking for the tag conclusion protected static final int INSIDE = 3; // Status used when a '<' is found and try to find the conclusion tag. protected static final int PRETAIL = 4; // Status used when the ending tag is equal to the head tag protected static final int TAIL = 5; // Status used when robot is inside the main tag and found an '/' to check '/>'. protected static final int VERIFY_CLOSE_TAG = 6; // Status used when you are inside a parameter protected static final int INSIDE_PARAM_VALUE = 7; // Status used when you are inside a cdata section protected static final int INSIDE_CDATA = 8; // Status used when you are outside a tag/reading text protected static final int OUTSIDE = 9; final String[] sstatus = {"INIT", "", "HEAD", "INSIDE", "PRETAIL", "TAIL", "VERIFY", "INSIDE_PARAM", "INSIDE_CDATA", "OUTSIDE"}; // Current robot status protected int status = XMLLightweightParser.INIT; // Index to looking for a CDATA section start or end. protected int cdataOffset = 0; // Number of chars that machs with the head tag. If the tailCount is equal to // the head length so a close tag is found. protected int tailCount = 0; // Indicate the starting point in the buffer for the next message. protected int startLastMsg = 0; // Flag used to discover tag in the form <tag />. protected boolean insideRootTag = false; // Object conteining the head tag protected StringBuilder head = new StringBuilder(16); // List with all finished messages found. protected List<String> msgs = new ArrayList<>(); private int depth = 0; protected boolean insideChildrenTag = false; CharsetDecoder encoder; static { // Set default max buffer size to 1MB. If limit is reached then close connection maxBufferSize = JiveGlobals.getIntProperty(MAX_PROPERTY_NAME, 1048576); // Listen for changes to this property PropertyEventDispatcher.addListener(new PropertyListener()); } public XMLLightweightParser(Charset charset) { encoder = charset.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); } /* * true if the parser has found some complete xml message. */ public boolean areThereMsgs() { return (msgs.size() > 0); } /* * @return an array with all messages found */ public String[] getMsgs() { String[] res = new String[msgs.size()]; for (int i = 0; i < res.length; i++) { res[i] = msgs.get(i); } msgs.clear(); invalidateBuffer(); return res; } /* * Method use to re-initialize the buffer */ protected void invalidateBuffer() { if (buffer.length() > 0) { String str = buffer.substring(startLastMsg); buffer.delete(0, buffer.length()); buffer.append(str); buffer.trimToSize(); } startLastMsg = 0; } /* * Method that add a message to the list and reinit parser. */ protected void foundMsg(String msg) throws XMLNotWellFormedException { // Add message to the complete message list if (msg != null) { if (hasIllegalCharacterReferences(msg)) { buffer = null; throw new XMLNotWellFormedException("Illegal character reference found in: " + msg); } msgs.add(msg); } // Move the position into the buffer status = XMLLightweightParser.INIT; tailCount = 0; cdataOffset = 0; head.setLength(0); insideRootTag = false; insideChildrenTag = false; depth = 0; } /* * Main reading method */ public void read(IoBuffer byteBuffer) throws Exception { if (buffer == null) { // exception was thrown before, avoid duplicate exception(s) // "read" and discard remaining data byteBuffer.position(byteBuffer.limit()); return; } invalidateBuffer(); // Check that the buffer is not bigger than 1 Megabyte. For security reasons // we will abort parsing when 1 Mega of queued chars was found. if (buffer.length() > maxBufferSize) { // purge the local buffer / free memory buffer = null; // processing the exception takes quite long final ProtocolDecoderException ex = new ProtocolDecoderException("Stopped parsing never ending stanza"); ex.setHexdump("(redacted hex dump of never ending stanza)"); throw ex; } CharBuffer charBuffer = CharBuffer.allocate(byteBuffer.capacity()); encoder.reset(); encoder.decode(byteBuffer.buf(), charBuffer, false); char[] buf = new char[charBuffer.position()]; charBuffer.flip(); charBuffer.get(buf); int readChar = buf.length; // Just return if nothing was read if (readChar == 0) { return; } buffer.append(buf); // Robot. char ch; boolean isHighSurrogate = false; for (int i = 0; i < readChar; i++) { ch = buf[i]; if (ch < 0x20 && ch != 0x9 && ch != 0xA && ch != 0xD) { //Unicode characters in the range 0x0000-0x001F other than 9, A, and D are not allowed in XML buffer = null; throw new XMLNotWellFormedException("Character is invalid in: " + ch); } if (isHighSurrogate) { if (Character.isLowSurrogate(ch)) { // Everything is fine. Clean up traces for surrogates isHighSurrogate = false; } else { // Trigger error. Found high surrogate not followed by low surrogate buffer = null; throw new Exception("Found high surrogate not followed by low surrogate"); } } else if (Character.isHighSurrogate(ch)) { isHighSurrogate = true; } else if (Character.isLowSurrogate(ch)) { // Trigger error. Found low surrogate char without a preceding high surrogate buffer = null; throw new Exception("Found low surrogate char without a preceding high surrogate"); } if (status == XMLLightweightParser.TAIL) { // Looking for the close tag if (depth < 1 && ch == head.charAt(tailCount)) { tailCount++; if (tailCount == head.length()) { // Close stanza found! // Calculate the correct start,end position of the message into the buffer int end = buffer.length() - readChar + (i + 1); String msg = buffer.substring(startLastMsg, end); // Add message to the list foundMsg(msg); startLastMsg = end; } } else { tailCount = 0; status = XMLLightweightParser.INSIDE; } } else if (status == XMLLightweightParser.PRETAIL) { if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) { cdataOffset++; if (cdataOffset == XMLLightweightParser.CDATA_START.length) { status = XMLLightweightParser.INSIDE_CDATA; cdataOffset = 0; continue; } } else { cdataOffset = 0; status = XMLLightweightParser.INSIDE; } if (ch == '/') { status = XMLLightweightParser.TAIL; depth--; } else if (ch == '!') { // This is a <! (comment) so ignore it status = XMLLightweightParser.INSIDE; } else { depth++; } } else if (status == XMLLightweightParser.VERIFY_CLOSE_TAG) { if (ch == '>') { depth--; status = XMLLightweightParser.OUTSIDE; if (depth < 1) { // Found a tag in the form <tag /> int end = buffer.length() - readChar + (i + 1); String msg = buffer.substring(startLastMsg, end); // Add message to the list foundMsg(msg); startLastMsg = end; } } else if (ch == '<') { status = XMLLightweightParser.PRETAIL; insideChildrenTag = true; } else { status = XMLLightweightParser.INSIDE; } } else if (status == XMLLightweightParser.INSIDE_PARAM_VALUE) { if (ch == '"') { status = XMLLightweightParser.INSIDE; } } else if (status == XMLLightweightParser.INSIDE_CDATA) { if (ch == XMLLightweightParser.CDATA_END[cdataOffset]) { cdataOffset++; if (cdataOffset == XMLLightweightParser.CDATA_END.length) { status = XMLLightweightParser.OUTSIDE; cdataOffset = 0; } } else if (cdataOffset == XMLLightweightParser.CDATA_END.length-1 && ch == XMLLightweightParser.CDATA_END[cdataOffset - 1]) { // if we are looking for the last CDATA_END char, and we instead found an extra ']' // char, leave cdataOffset as is and proceed to the next char. This could be a case // where the XML character data ends with multiple square braces. For Example ]]]> } else { cdataOffset = 0; } } else if (status == XMLLightweightParser.INSIDE) { if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) { cdataOffset++; if (cdataOffset == XMLLightweightParser.CDATA_START.length) { status = XMLLightweightParser.INSIDE_CDATA; cdataOffset = 0; continue; } } else { cdataOffset = 0; status = XMLLightweightParser.INSIDE; } if (ch == '"') { status = XMLLightweightParser.INSIDE_PARAM_VALUE; } else if (ch == '>') { status = XMLLightweightParser.OUTSIDE; if (insideRootTag && (head.length() == 14 || head.length() == 5 || head.length() == 13)) { final String headString = head.toString(); if ("stream:stream>".equals(headString) || "?xml>".equals(headString)) { // Found closing stream:stream int end = buffer.length() - readChar + (i + 1); // Skip LF, CR and other "weird" characters that could appear while (startLastMsg < end && '<' != buffer.charAt(startLastMsg)) { startLastMsg++; } String msg = buffer.substring(startLastMsg, end); foundMsg(msg); startLastMsg = end; } } insideRootTag = false; } else if (ch == '/') { status = XMLLightweightParser.VERIFY_CLOSE_TAG; } } else if (status == XMLLightweightParser.HEAD) { if (Character.isWhitespace(ch) || ch == '>') { // Append > to head to allow searching </tag> head.append('>'); if(ch == '>') status = XMLLightweightParser.OUTSIDE; else status = XMLLightweightParser.INSIDE; insideRootTag = true; insideChildrenTag = false; continue; } else if (ch == '/' && head.length() > 0) { status = XMLLightweightParser.VERIFY_CLOSE_TAG; depth--; } head.append(ch); } else if (status == XMLLightweightParser.INIT) { if (ch == '<') { status = XMLLightweightParser.HEAD; depth = 1; } else { startLastMsg++; } } else if (status == XMLLightweightParser.OUTSIDE) { if (ch == '<') { status = XMLLightweightParser.PRETAIL; cdataOffset = 1; insideChildrenTag = true; } } } if (head.length() == 15 || head.length() == 14) { final String headString = head.toString(); if ("/stream:stream>".equals(headString)) { foundMsg("</stream:stream>"); } } } /** * This method verifies if the provided argument contains at least one numeric character reference ( * <code>CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';</code>) for which the decimal or hexidecimal * character value refers to an invalid XML 1.0 character. * * @param string * The input string * @return {@code true} if the input string contains an invalid numeric character reference, {@code false} * otherwise. * @see http://www.w3.org/TR/2008/REC-xml-20081126/#dt-charref */ public static boolean hasIllegalCharacterReferences(String string) { // If there's no character reference, don't bother to do more specific checking. final Matcher matcher = XML_HAS_CHARREF.matcher(string); while (matcher.find()) { final String decValue = matcher.group(2); if (decValue != null) { final int value = Integer.parseInt(decValue); if (!isLegalXmlCharacter(value)) { return true; } else { continue; } } final String hexValue = matcher.group(3); if (hexValue != null) { final int value = Integer.parseInt(hexValue, 16); if (!isLegalXmlCharacter(value)) { return true; } else { continue; } } // This is bad. The XML_HAS_CHARREF expression should have a hit for either the decimal // or the heximal notation. throw new IllegalStateException( "An error occurred while searching for illegal character references in the value [" + string + "]."); } return false; } /** * Verifies if the codepoint value represents a valid character as defined in paragraph 2.2 of * "Extensible Markup Language (XML) 1.0 (Fifth Edition)" * * @param value * the codepoint * @return {@code true} if the codepoint is a valid charater per XML 1.0 definition, {@code false} otherwise. * @see http://www.w3.org/TR/2008/REC-xml-20081126/#NT-Char */ public static boolean isLegalXmlCharacter(int value) { return value == 0x9 || value == 0xA || value == 0xD || (value >= 0x20 && value <= 0xD7FF) || (value >= 0xE000 && value <= 0xFFFD) || (value >= 0x10000 && value <= 0x10FFFF); } private static class PropertyListener implements PropertyEventListener { @Override public void propertySet(String property, Map<String, Object> params) { if (MAX_PROPERTY_NAME.equals(property)) { String value = (String) params.get("value"); if (value != null) { maxBufferSize = Integer.parseInt(value); } } } @Override public void propertyDeleted(String property, Map<String, Object> params) { if (MAX_PROPERTY_NAME.equals(property)) { // Use default value when none was specified maxBufferSize = 1048576; } } @Override public void xmlPropertySet(String property, Map<String, Object> params) { // Do nothing } @Override public void xmlPropertyDeleted(String property, Map<String, Object> params) { // Do nothing } } }
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts; import java.beans.PropertyChangeListener; import java.util.ListIterator; import org.eclipse.draw2d.FigureCanvas; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.GridData; import org.eclipse.draw2d.GridLayout; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.PositionConstants; import org.eclipse.draw2d.RoundedRectangle; import org.eclipse.draw2d.Shape; import org.eclipse.draw2d.StackLayout; import org.eclipse.draw2d.ToolbarLayout; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.impl.EAttributeImpl; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.GraphicalEditPart; import org.eclipse.gef.Request; import org.eclipse.gef.commands.Command; import org.eclipse.gef.editpolicies.LayoutEditPolicy; import org.eclipse.gef.editpolicies.NonResizableEditPolicy; import org.eclipse.gef.requests.CreateRequest; import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderedShapeEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IBorderItemEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.BorderItemSelectionEditPolicy; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.DragDropEditPolicy; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles; import org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator; import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout; import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel; import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure; import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.gmf.runtime.notation.impl.BoundsImpl; import org.eclipse.gmf.tooling.runtime.edit.policies.reparent.CreationEditPolicyWithCustomReparent; import org.eclipse.swt.graphics.Color; import org.wso2.developerstudio.eclipse.gmf.esb.InboundEndpoint; import org.wso2.developerstudio.eclipse.gmf.esb.ProxyService; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.CustomNonResizableEditPolicyEx; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.EditorUtils; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.FixedBorderItemLocator; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.InboundEndpointGroupBox; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.ShowPropertyViewEditPolicy; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.InboundEndpointCanonicalEditPolicy; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.InboundEndpointItemSemanticEditPolicy; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbVisualIDRegistry; /** * @generated */ public class InboundEndpointEditPart extends AbstractBorderedShapeEditPart { public IFigure sequenceInputConnectorFigure; public IFigure sequenceOutputConnectorFigure; public IFigure onErrorSequenceInputConnectorFigure; public IFigure onErrorSequenceOutputConnectorFigure; /** * @generated */ public static final int VISUAL_ID = 3767; /** * @generated */ protected IFigure contentPane; /** * @generated */ protected IFigure primaryShape; /** * figure update status */ private boolean figureUpdated; /** * @generated */ public InboundEndpointEditPart(View view) { super(view); } /** * @generated NOT */ protected void createDefaultEditPolicies() { installEditPolicy(EditPolicyRoles.CREATION_ROLE, new CreationEditPolicyWithCustomReparent(EsbVisualIDRegistry.TYPED_INSTANCE)); super.createDefaultEditPolicies(); removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE); removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.POPUPBAR_ROLE); installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE, new InboundEndpointItemSemanticEditPolicy()); installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE, new DragDropEditPolicy()); installEditPolicy(EditPolicyRoles.CANONICAL_ROLE, new InboundEndpointCanonicalEditPolicy()); installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy()); // For handle Double click Event. installEditPolicy(EditPolicyRoles.OPEN_ROLE, new ShowPropertyViewEditPolicy()); // XXX need an SCR to runtime to have another abstract superclass that // would let children add reasonable editpolicies // removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE); // remove 8 corners installEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE, new CustomNonResizableEditPolicyEx()); } /** * @generated */ protected LayoutEditPolicy createLayoutEditPolicy() { org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy lep = new org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy() { protected EditPolicy createChildEditPolicy(EditPart child) { View childView = (View) child.getModel(); switch (EsbVisualIDRegistry.getVisualID(childView)) { case InboundEndpointSequenceInputConnectorEditPart.VISUAL_ID: case InboundEndpointSequenceOutputConnectorEditPart.VISUAL_ID: case InboundEndpointOnErrorSequenceInputConnectorEditPart.VISUAL_ID: case InboundEndpointOnErrorSequenceOutputConnectorEditPart.VISUAL_ID: return new BorderItemSelectionEditPolicy(); } EditPolicy result = child.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE); if (result == null) { result = new NonResizableEditPolicy(); } return result; } protected Command getMoveChildrenCommand(Request request) { return null; } protected Command getCreateCommand(CreateRequest request) { return null; } }; return lep; } public void notifyChanged(Notification notification) { super.notifyChanged(notification); if (notification.getFeature() instanceof EAttributeImpl) { if (notification.getNotifier() instanceof BoundsImpl) { int y = ((BoundsImpl) notification.getNotifier()).getY(); if (y == -1) { y = +2; } alignLeft(y, ((BoundsImpl) notification.getNotifier()).getWidth(), ((BoundsImpl) notification.getNotifier()).getHeight()); FigureCanvas canvas = (FigureCanvas) getViewer().getControl(); canvas.getViewport().repaint(); } } } private void alignLeft(int y, int width, int height) { y = 100; Rectangle constraints = new Rectangle(0, y, width, height); ((GraphicalEditPart) getParent()).setLayoutConstraint(this, getFigure(), constraints); } private void alignLeft() { alignLeft(getFigure().getBounds().y, getFigure().getBounds().width, getFigure().getBounds().height); } /** * @generated NOT */ protected IFigure createNodeShape() { return primaryShape = new InboundEndpointFigure() { public void setBounds(org.eclipse.draw2d.geometry.Rectangle rect) { super.setBounds(rect); if (this.getBounds().getLocation().x != 0 && this.getBounds().getLocation().y != 0) { alignLeft(); } /* * if (!figureUpdated) { * updateFigure(); * } */ }; }; } protected void addChildVisual(EditPart childEditPart, int index) { if (addFixedChild(childEditPart)) { return; } super.addChildVisual(childEditPart, -1); } protected boolean addFixedChild(EditPart childEditPart) { if (childEditPart instanceof InboundEndpointSequenceInputConnectorEditPart) { IFigure borderItemFigure = ((InboundEndpointSequenceInputConnectorEditPart) childEditPart).getFigure(); BorderItemLocator locator = new FixedBorderItemLocator(getMainFigure(), borderItemFigure, PositionConstants.EAST, 0.25); getBorderedFigure().getBorderItemContainer().add(borderItemFigure, locator); sequenceInputConnectorFigure = borderItemFigure; return true; } if (childEditPart instanceof InboundEndpointSequenceOutputConnectorEditPart) { IFigure borderItemFigure = ((InboundEndpointSequenceOutputConnectorEditPart) childEditPart).getFigure(); BorderItemLocator locator = new FixedBorderItemLocator( (IFigure) ((IFigure) ((IFigure) (IFigure) getFigure().getChildren().get(0)).getChildren().get(0)) .getChildren().get(0), borderItemFigure, PositionConstants.EAST, 0.25); getBorderedFigure().getBorderItemContainer().add(borderItemFigure, locator); sequenceOutputConnectorFigure = borderItemFigure; return true; } if (childEditPart instanceof InboundEndpointOnErrorSequenceInputConnectorEditPart) { IFigure borderItemFigure = ((InboundEndpointOnErrorSequenceInputConnectorEditPart) childEditPart) .getFigure(); BorderItemLocator locator = new FixedBorderItemLocator(getMainFigure(), borderItemFigure, PositionConstants.EAST, 0.75); getBorderedFigure().getBorderItemContainer().add(borderItemFigure, locator); onErrorSequenceInputConnectorFigure = borderItemFigure; return true; } if (childEditPart instanceof InboundEndpointOnErrorSequenceOutputConnectorEditPart) { IFigure borderItemFigure = ((InboundEndpointOnErrorSequenceOutputConnectorEditPart) childEditPart) .getFigure(); BorderItemLocator locator = new FixedBorderItemLocator( (IFigure) ((IFigure) ((IFigure) (IFigure) getFigure().getChildren().get(0)).getChildren().get(0)) .getChildren().get(0), borderItemFigure, PositionConstants.EAST, 0.75); getBorderedFigure().getBorderItemContainer().add(borderItemFigure, locator); onErrorSequenceOutputConnectorFigure = borderItemFigure; return true; } return false; } /** * @generated */ public InboundEndpointFigure getPrimaryShape() { return (InboundEndpointFigure) primaryShape; } /** * @generated */ protected NodeFigure createNodePlate() { DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(40, 40); return result; } /** * Creates figure for this edit part. * * Body of this method does not depend on settings in generation model * so you may safely remove <i>generated</i> tag and modify it. * * @generated */ protected NodeFigure createMainFigure() { NodeFigure figure = createNodePlate(); figure.setLayoutManager(new StackLayout()); IFigure shape = createNodeShape(); figure.add(shape); contentPane = setupContentPane(shape); return figure; } /** * Default implementation treats passed figure as content pane. * Respects layout one may have set for generated figure. * * @param nodeShape * instance of generated figure class * @generated */ protected IFigure setupContentPane(IFigure nodeShape) { if (nodeShape.getLayoutManager() == null) { ConstrainedToolbarLayout layout = new ConstrainedToolbarLayout(); layout.setSpacing(5); nodeShape.setLayoutManager(layout); } return nodeShape; // use nodeShape itself as contentPane } /** * @generated */ public IFigure getContentPane() { if (contentPane != null) { return contentPane; } return super.getContentPane(); } protected IFigure getContentPaneFor(IGraphicalEditPart editPart) { if (editPart instanceof IBorderItemEditPart) { return getBorderedFigure().getBorderItemContainer(); } return getContentPane(); } /** * @generated */ protected void setForegroundColor(Color color) { if (primaryShape != null) { primaryShape.setForegroundColor(color); } } /** * @generated */ protected void setBackgroundColor(Color color) { if (primaryShape != null) { primaryShape.setBackgroundColor(color); } } /** * @generated */ protected void setLineWidth(int width) { if (primaryShape instanceof Shape) { ((Shape) primaryShape).setLineWidth(width); } } /** * @generated */ protected void setLineType(int style) { if (primaryShape instanceof Shape) { ((Shape) primaryShape).setLineStyle(style); } } /** * @generated NOT */ public class InboundEndpointFigure extends InboundEndpointGroupBox { private WrappingLabel fFigureProxyNamePropertyLabel; /** * @generated NOT */ public InboundEndpointFigure() { ToolbarLayout layoutThis = new ToolbarLayout(); layoutThis.setStretchMinorAxis(true); layoutThis.setMinorAlignment(ToolbarLayout.ALIGN_CENTER); layoutThis.setSpacing(0); layoutThis.setVertical(false); this.setLayoutManager(layoutThis); this.setPreferredSize(new Dimension(getMapMode().DPtoLP(300), getMapMode().DPtoLP(400))); this.setOutline(false); this.setBackgroundColor(THIS_BACK); this.setForegroundColor(new Color(null, 0, 0, 0)); createContents(); } public void addPropertyChangeListener(PropertyChangeListener listener) { // TODO Auto-generated method stub super.addPropertyChangeListener(listener); } public void add(IFigure figure, Object constraint, int index) { if (figure instanceof DefaultSizeNodeFigure) { GridData layoutData = new GridData(); layoutData.grabExcessHorizontalSpace = true; layoutData.grabExcessVerticalSpace = true; layoutData.horizontalAlignment = GridData.FILL; layoutData.verticalAlignment = GridData.FILL; super.add(figure, layoutData, index); } else if (figure instanceof RoundedRectangle) { GridData layoutData = new GridData(); layoutData.grabExcessHorizontalSpace = true; layoutData.grabExcessVerticalSpace = true; layoutData.horizontalAlignment = GridData.FILL; layoutData.verticalAlignment = GridData.FILL; super.add(figure, layoutData, index); } else { super.add(figure, constraint, index); } } /** * @generated NOT * @customizations add the property label to parent figure */ private void createContents() { fFigureProxyNamePropertyLabel = getProxyNameLabel(); } public String getIconPath() { return "icons/ico20/inbound-endpoint.png"; } public String getNodeName() { return "Inbound EP"; } public Color getBackgroundColor() { return THIS_BACK; } public Color getLabelBackColor() { return THIS_LABEL_BACK; } } /** * @generated */ static final Color THIS_BACK = new Color(null, 255, 255, 255); static final Color THIS_LABEL_BACK = new Color(null, 0, 0, 0); }
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.query.timeseries; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import com.google.common.collect.ImmutableList; import io.druid.java.util.common.granularity.Granularity; import io.druid.query.BaseQuery; import io.druid.query.DataSource; import io.druid.query.Druids; import io.druid.query.Queries; import io.druid.query.Query; import io.druid.query.Result; import io.druid.query.aggregation.AggregatorFactory; import io.druid.query.aggregation.PostAggregator; import io.druid.query.filter.DimFilter; import io.druid.query.spec.QuerySegmentSpec; import io.druid.segment.VirtualColumns; import java.util.List; import java.util.Map; import java.util.Objects; /** */ @JsonTypeName("timeseries") public class TimeseriesQuery extends BaseQuery<Result<TimeseriesResultValue>> { static final String CTX_GRAND_TOTAL = "grandTotal"; public static final String SKIP_EMPTY_BUCKETS = "skipEmptyBuckets"; private final VirtualColumns virtualColumns; private final DimFilter dimFilter; private final List<AggregatorFactory> aggregatorSpecs; private final List<PostAggregator> postAggregatorSpecs; @JsonCreator public TimeseriesQuery( @JsonProperty("dataSource") DataSource dataSource, @JsonProperty("intervals") QuerySegmentSpec querySegmentSpec, @JsonProperty("descending") boolean descending, @JsonProperty("virtualColumns") VirtualColumns virtualColumns, @JsonProperty("filter") DimFilter dimFilter, @JsonProperty("granularity") Granularity granularity, @JsonProperty("aggregations") List<AggregatorFactory> aggregatorSpecs, @JsonProperty("postAggregations") List<PostAggregator> postAggregatorSpecs, @JsonProperty("context") Map<String, Object> context ) { super(dataSource, querySegmentSpec, descending, context, granularity); this.virtualColumns = VirtualColumns.nullToEmpty(virtualColumns); this.dimFilter = dimFilter; this.aggregatorSpecs = aggregatorSpecs == null ? ImmutableList.of() : aggregatorSpecs; this.postAggregatorSpecs = Queries.prepareAggregations( ImmutableList.of(), this.aggregatorSpecs, postAggregatorSpecs == null ? ImmutableList.of() : postAggregatorSpecs ); } @Override public boolean hasFilters() { return dimFilter != null; } @Override public DimFilter getFilter() { return dimFilter; } @Override public String getType() { return Query.TIMESERIES; } @JsonProperty public VirtualColumns getVirtualColumns() { return virtualColumns; } @JsonProperty("filter") public DimFilter getDimensionsFilter() { return dimFilter; } @JsonProperty("aggregations") public List<AggregatorFactory> getAggregatorSpecs() { return aggregatorSpecs; } @JsonProperty("postAggregations") public List<PostAggregator> getPostAggregatorSpecs() { return postAggregatorSpecs; } public boolean isGrandTotal() { return getContextBoolean(CTX_GRAND_TOTAL, false); } public boolean isSkipEmptyBuckets() { return getContextBoolean(SKIP_EMPTY_BUCKETS, false); } @Override public TimeseriesQuery withQuerySegmentSpec(QuerySegmentSpec querySegmentSpec) { return Druids.TimeseriesQueryBuilder.copy(this).intervals(querySegmentSpec).build(); } @Override public Query<Result<TimeseriesResultValue>> withDataSource(DataSource dataSource) { return Druids.TimeseriesQueryBuilder.copy(this).dataSource(dataSource).build(); } @Override public TimeseriesQuery withOverriddenContext(Map<String, Object> contextOverrides) { Map<String, Object> newContext = computeOverriddenContext(getContext(), contextOverrides); return Druids.TimeseriesQueryBuilder.copy(this).context(newContext).build(); } public TimeseriesQuery withDimFilter(DimFilter dimFilter) { return Druids.TimeseriesQueryBuilder.copy(this).filters(dimFilter).build(); } public TimeseriesQuery withPostAggregatorSpecs(final List<PostAggregator> postAggregatorSpecs) { return Druids.TimeseriesQueryBuilder.copy(this).postAggregators(postAggregatorSpecs).build(); } @Override public String toString() { return "TimeseriesQuery{" + "dataSource='" + getDataSource() + '\'' + ", querySegmentSpec=" + getQuerySegmentSpec() + ", descending=" + isDescending() + ", virtualColumns=" + virtualColumns + ", dimFilter=" + dimFilter + ", granularity='" + getGranularity() + '\'' + ", aggregatorSpecs=" + aggregatorSpecs + ", postAggregatorSpecs=" + postAggregatorSpecs + ", context=" + getContext() + '}'; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } final TimeseriesQuery that = (TimeseriesQuery) o; return Objects.equals(virtualColumns, that.virtualColumns) && Objects.equals(dimFilter, that.dimFilter) && Objects.equals(aggregatorSpecs, that.aggregatorSpecs) && Objects.equals(postAggregatorSpecs, that.postAggregatorSpecs); } @Override public int hashCode() { return Objects.hash(super.hashCode(), virtualColumns, dimFilter, aggregatorSpecs, postAggregatorSpecs); } }
/* * Copyright 2011 buddycloud * * 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.buddycloud.channeldirectory.crawler.node; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smack.util.PacketUtil; import org.jivesoftware.smackx.pubsub.BuddycloudAffiliation; import org.jivesoftware.smackx.pubsub.BuddycloudNode; import org.jivesoftware.smackx.pubsub.Node; import org.jivesoftware.smackx.rsm.packet.RSMSet; import com.buddycloud.channeldirectory.commons.db.ChannelDirectoryDataSource; /** * Responsible for crawling {@link Node} data * regarding subscribers. * */ public class FollowerCrawler implements NodeCrawler { private static Logger LOGGER = Logger.getLogger(FollowerCrawler.class); private final ChannelDirectoryDataSource dataSource; public FollowerCrawler(ChannelDirectoryDataSource dataSource) { this.dataSource = dataSource; } /* (non-Javadoc) * @see com.buddycloud.channeldirectory.crawler.node.NodeCrawler#crawl(org.jivesoftware.smackx.pubsub.Node) */ @Override public void crawl(BuddycloudNode node, String server) throws Exception { String nodeId = node.getId(); LOGGER.debug("Fetching followers for " + nodeId); List<BuddycloudAffiliation> affiliations = getAffiliations(node); String nodeSimpleId = CrawlerHelper.getNodeId(nodeId); if (nodeSimpleId == null) { return; } for (BuddycloudAffiliation affiliation : affiliations) { try { processAffiliation(nodeSimpleId, affiliation); } catch (Exception e) { LOGGER.warn(e); } } try { updateSubscribedNode(node.getId(), server); } catch (SQLException e1) { LOGGER.warn("Could not update subscribed node", e1); } } private void processAffiliation(String itemJID, BuddycloudAffiliation affiliation) throws SQLException { String user = affiliation.getNodeId(); CrawlerHelper.enqueueNewServer(user, dataSource); Long userId = fetchRowId(user, "t_user"); Long itemId = fetchRowId(itemJID, "item"); boolean affiliationExists = affiliationExists(userId, itemId); LOGGER.debug(user + " follows " + itemJID + ". Affiliation exists? " + affiliationExists); if (!affiliationExists) { insertTaste(userId, itemId); } } private boolean affiliationExists(Long userId, Long itemId) throws SQLException { Statement selectTasteSt = null; try { selectTasteSt = dataSource.createStatement(); ResultSet selectTasteResult = selectTasteSt.executeQuery( "SELECT * FROM taste_preferences WHERE user_id = '" + userId + "' " + "AND item_id = '" + itemId + "'"); return selectTasteResult.next(); } catch (SQLException e) { LOGGER.error(e); throw e; } finally { ChannelDirectoryDataSource.close(selectTasteSt); } } private void insertTaste(Long userId, Long itemId) throws SQLException { Statement insertTasteSt = null; try { insertTasteSt = dataSource.createStatement(); insertTasteSt.execute("INSERT INTO taste_preferences(user_id, item_id) " + "VALUES ('" + userId + "', '" + itemId + "')"); } catch (SQLException e) { LOGGER.error(e); throw e; } finally { ChannelDirectoryDataSource.close(insertTasteSt); } } private void updateSubscribedNode(String nodeName, String server) throws SQLException { PreparedStatement prepareStatement = null; try { prepareStatement = dataSource.prepareStatement( "UPDATE subscribed_node SET subscribers_updated = ? WHERE name = ? AND server = ?", new Date(System.currentTimeMillis()), nodeName, server); prepareStatement.execute(); } catch (SQLException e) { LOGGER.error(e); throw e; } finally { ChannelDirectoryDataSource.close(prepareStatement); } } private Long fetchRowId(String user, String tableName) throws SQLException { Statement selectRowSt =null; try { selectRowSt = dataSource.createStatement(); ResultSet selectRowResult = selectRowSt.executeQuery( "SELECT id FROM " + tableName + " WHERE jid = '" + user + "'"); Long userId = null; if (selectRowResult.next()) { userId = selectRowResult.getLong("id"); } else { userId = insertTasteObject(user, tableName); } return userId; } catch (SQLException e) { LOGGER.error(e); throw e; } finally { ChannelDirectoryDataSource.close(selectRowSt); } } private Long insertTasteObject(String object, String tableName) throws SQLException { Statement insertRowSt = null; try { insertRowSt = dataSource.createStatement(); insertRowSt.execute("INSERT INTO " + tableName + "(jid) VALUES ('" + object + "') RETURNING id"); ResultSet insertUserResult = insertRowSt.getResultSet(); insertUserResult.next(); return insertUserResult.getLong("id"); } catch (SQLException e) { LOGGER.error(e); throw e; } finally { ChannelDirectoryDataSource.close(insertRowSt); } } /* (non-Javadoc) * @see com.buddycloud.channeldirectory.crawler.node.NodeCrawler#accept(org.jivesoftware.smackx.pubsub.Node) */ @Override public boolean accept(BuddycloudNode node) { return node.getId().endsWith("/posts"); } private List<BuddycloudAffiliation> getAffiliations(BuddycloudNode node) throws XMPPException { List<BuddycloudAffiliation> allAffiliations = new LinkedList<BuddycloudAffiliation>(); RSMSet nextRsmSet = null; while (true) { List<PacketExtension> additionalExtensions = new LinkedList<PacketExtension>(); List<PacketExtension> returnedExtensions = new LinkedList<PacketExtension>(); if (nextRsmSet != null) { additionalExtensions.add(nextRsmSet); } List<BuddycloudAffiliation> nodeAffiliations = null; try { nodeAffiliations = node.getBuddycloudAffiliations( additionalExtensions, returnedExtensions); } catch (Exception e) { break; } allAffiliations.addAll(nodeAffiliations); RSMSet returnedRsmSet = PacketUtil.packetExtensionfromCollection( returnedExtensions, RSMSet.ELEMENT, RSMSet.NAMESPACE); if (returnedRsmSet == null || allAffiliations.size() == returnedRsmSet.getCount()) { break; } nextRsmSet = RSMSet.newAfter(returnedRsmSet.getLast()); } return allAffiliations; } }
/* * Copyright (C) 2016 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 androidx.test.espresso.contrib; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import android.view.View; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.test.espresso.Espresso; import androidx.test.espresso.IdlingResource; import androidx.test.espresso.UiController; import androidx.test.espresso.ViewAction; import androidx.test.espresso.action.CoordinatesProvider; import androidx.test.espresso.action.GeneralClickAction; import androidx.test.espresso.action.Press; import androidx.test.espresso.action.Tap; import androidx.viewpager.widget.PagerTitleStrip; import androidx.viewpager.widget.ViewPager; import org.hamcrest.Matcher; /** Espresso actions for interacting with a {@link ViewPager}. */ public final class ViewPagerActions { private static final boolean DEFAULT_SMOOTH_SCROLL = false; private ViewPagerActions() { // forbid instantiation } /** Moves <code>ViewPager</code> to the right be one page. */ public static ViewAction scrollRight() { return scrollRight(DEFAULT_SMOOTH_SCROLL); } /** Moves <code>ViewPager</code> to the right by one page. */ public static ViewAction scrollRight(final boolean smoothScroll) { return new ViewPagerScrollAction() { @Override public String getDescription() { return "ViewPager move one page to the right"; } @Override protected void performScroll(ViewPager viewPager) { int current = viewPager.getCurrentItem(); viewPager.setCurrentItem(current + 1, smoothScroll); } }; } /** Moves <code>ViewPager</code> to the left be one page. */ public static ViewAction scrollLeft() { return scrollLeft(DEFAULT_SMOOTH_SCROLL); } /** Moves <code>ViewPager</code> to the left by one page. */ public static ViewAction scrollLeft(final boolean smoothScroll) { return new ViewPagerScrollAction() { @Override public String getDescription() { return "ViewPager move one page to the left"; } @Override protected void performScroll(ViewPager viewPager) { int current = viewPager.getCurrentItem(); viewPager.setCurrentItem(current - 1, smoothScroll); } }; } /** Moves <code>ViewPager</code> to the last page. */ public static ViewAction scrollToLast() { return scrollToLast(DEFAULT_SMOOTH_SCROLL); } /** Moves <code>ViewPager</code> to the last page. */ public static ViewAction scrollToLast(final boolean smoothScroll) { return new ViewPagerScrollAction() { @Override public String getDescription() { return "ViewPager move to last page"; } @Override protected void performScroll(ViewPager viewPager) { int size = viewPager.getAdapter().getCount(); if (size > 0) { viewPager.setCurrentItem(size - 1, smoothScroll); } } }; } /** Moves <code>ViewPager</code> to the first page. */ public static ViewAction scrollToFirst() { return scrollToFirst(DEFAULT_SMOOTH_SCROLL); } /** Moves <code>ViewPager</code> to the first page. */ public static ViewAction scrollToFirst(final boolean smoothScroll) { return new ViewPagerScrollAction() { @Override public String getDescription() { return "ViewPager move to first page"; } @Override protected void performScroll(ViewPager viewPager) { int size = viewPager.getAdapter().getCount(); if (size > 0) { viewPager.setCurrentItem(0, smoothScroll); } } }; } /** Moves <code>ViewPager</code> to a specific page. */ public static ViewAction scrollToPage(int page) { return scrollToPage(page, DEFAULT_SMOOTH_SCROLL); } /** Moves <code>ViewPager</code> to specific page. */ public static ViewAction scrollToPage(final int page, final boolean smoothScroll) { return new ViewPagerScrollAction() { @Override public String getDescription() { return "ViewPager move to page"; } @Override protected void performScroll(ViewPager viewPager) { viewPager.setCurrentItem(page, smoothScroll); } }; } /** Clicks between two titles in a <code>ViewPager</code> title strip */ public static ViewAction clickBetweenTwoTitles(final String title1, final String title2) { return new GeneralClickAction( Tap.SINGLE, new CoordinatesProvider() { @Override public float[] calculateCoordinates(View view) { PagerTitleStrip pagerStrip = (PagerTitleStrip) view; // Get the screen position of the pager strip final int[] viewScreenPosition = new int[2]; pagerStrip.getLocationOnScreen(viewScreenPosition); // Get the left / right of the first title int title1Left = 0, title1Right = 0, title2Left = 0, title2Right = 0; final int childCount = pagerStrip.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = pagerStrip.getChildAt(i); if (child instanceof TextView) { final TextView textViewChild = (TextView) child; final CharSequence childText = textViewChild.getText(); if (title1.equals(childText)) { title1Left = textViewChild.getLeft(); title1Right = textViewChild.getRight(); } else if (title2.equals(childText)) { title2Left = textViewChild.getLeft(); title2Right = textViewChild.getRight(); } } } if (title1Right < title2Left) { // Title 1 is to the left of title 2 return new float[] { viewScreenPosition[0] + (title1Right + title2Left) / 2, viewScreenPosition[1] + pagerStrip.getHeight() / 2 }; } else { // The assumption here is that PagerTitleStrip prevents titles // from overlapping, so if we get here it means that title 1 // is to the right of title 2 return new float[] { viewScreenPosition[0] + (title2Right + title1Left) / 2, viewScreenPosition[1] + pagerStrip.getHeight() / 2 }; } } }, Press.FINGER, 0, 0); } /** * View pager listener that serves as Espresso's {@link IdlingResource} and notifies the * registered callback when the view pager gets to STATE_IDLE state. */ private static final class CustomViewPagerListener implements ViewPager.OnPageChangeListener, IdlingResource { private int mCurrState = ViewPager.SCROLL_STATE_IDLE; @Nullable private IdlingResource.ResourceCallback mCallback; private boolean mNeedsIdle = false; @Override public void registerIdleTransitionCallback(ResourceCallback resourceCallback) { mCallback = resourceCallback; } @Override public String getName() { return "View pager listener"; } @Override public boolean isIdleNow() { if (!mNeedsIdle) { return true; } else { return mCurrState == ViewPager.SCROLL_STATE_IDLE; } } @Override public void onPageSelected(int position) { if (mCurrState == ViewPager.SCROLL_STATE_IDLE) { if (mCallback != null) { mCallback.onTransitionToIdle(); } } } @Override public void onPageScrollStateChanged(int state) { mCurrState = state; if (mCurrState == ViewPager.SCROLL_STATE_IDLE) { if (mCallback != null) { mCallback.onTransitionToIdle(); } } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {} } private abstract static class ViewPagerScrollAction implements ViewAction { @Override public final Matcher<View> getConstraints() { return isDisplayed(); } @Override public final void perform(UiController uiController, View view) { final ViewPager viewPager = (ViewPager) view; // Add a custom tracker listener final CustomViewPagerListener customListener = new CustomViewPagerListener(); viewPager.addOnPageChangeListener(customListener); // Note that we're running the following block in a try-finally construct. This // is needed since some of the actions are going to throw (expected) exceptions. If that // happens, we still need to clean up after ourselves to leave the system (Espresso) in a good // state. try { // Register our listener as idling resource so that Espresso waits until the // wrapped action results in the view pager getting to the STATE_IDLE state Espresso.registerIdlingResources(customListener); uiController.loopMainThreadUntilIdle(); performScroll((ViewPager) view); uiController.loopMainThreadUntilIdle(); customListener.mNeedsIdle = true; uiController.loopMainThreadUntilIdle(); customListener.mNeedsIdle = false; } finally { // Unregister our idling resource Espresso.unregisterIdlingResources(customListener); // And remove our tracker listener from ViewPager viewPager.removeOnPageChangeListener(customListener); } } protected abstract void performScroll(ViewPager viewPager); } }
package de.fraunhofer.iosb.ilt.sta.model; import com.fasterxml.jackson.annotation.JsonProperty; import de.fraunhofer.iosb.ilt.sta.ServiceFailureException; import de.fraunhofer.iosb.ilt.sta.dao.BaseDao; import de.fraunhofer.iosb.ilt.sta.dao.DatastreamDao; import de.fraunhofer.iosb.ilt.sta.dao.ObservationDao; import de.fraunhofer.iosb.ilt.sta.model.ext.EntityList; import de.fraunhofer.iosb.ilt.sta.model.ext.UnitOfMeasurement; import de.fraunhofer.iosb.ilt.sta.service.SensorThingsService; import java.util.List; import java.util.Map; import java.util.Objects; import org.geojson.GeoJsonObject; import org.threeten.extra.Interval; public class Datastream extends Entity<Datastream> { private String name; private String description; private String observationType; private UnitOfMeasurement unitOfMeasurement; private GeoJsonObject observedArea; private Interval phenomenonTime; private Map<String, Object> properties; private Interval resultTime; @JsonProperty("Thing") private Thing thing; @JsonProperty("Sensor") private Sensor sensor; @JsonProperty("ObservedProperty") private ObservedProperty observedProperty; private final EntityList<Observation> observations = new EntityList<>(EntityType.OBSERVATIONS); public Datastream() { super(EntityType.DATASTREAM); } public Datastream(String name, String description, String observationType, UnitOfMeasurement unitOfMeasurement) { this(); this.name = name; this.description = description; this.observationType = observationType; this.unitOfMeasurement = unitOfMeasurement; } @Override protected void ensureServiceOnChildren(SensorThingsService service) { if (thing != null) { thing.setService(service); } if (sensor != null) { sensor.setService(service); } if (observedProperty != null) { observedProperty.setService(service); } if (observations != null) { observations.setService(service, Observation.class); } } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Datastream other = (Datastream) obj; return Objects.equals(this.name, other.name) && Objects.equals(this.description, other.description) && Objects.equals(this.observationType, other.observationType) && Objects.equals(this.unitOfMeasurement, other.unitOfMeasurement) && Objects.equals(this.properties, other.properties) && Objects.equals(this.resultTime, other.resultTime) && super.equals(obj); } @Override public int hashCode() { return Objects.hash( super.hashCode(), name, description, observationType, unitOfMeasurement, properties, resultTime); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getObservationType() { return this.observationType; } public void setObservationType(String observationType) { this.observationType = observationType; } public Map<String, Object> getProperties() { return this.properties; } public void setProperties(Map<String, Object> properties) { this.properties = properties; } public UnitOfMeasurement getUnitOfMeasurement() { return this.unitOfMeasurement; } public void setUnitOfMeasurement(UnitOfMeasurement unitOfMeasurement) { this.unitOfMeasurement = unitOfMeasurement; } public GeoJsonObject getObservedArea() { return this.observedArea; } public void setObservedArea(GeoJsonObject observedArea) { this.observedArea = observedArea; } public Interval getPhenomenonTime() { return this.phenomenonTime; } public void setPhenomenonTime(Interval phenomenonTime) { this.phenomenonTime = phenomenonTime; } public Interval getResultTime() { return this.resultTime; } public void setResultTime(Interval resultTime) { this.resultTime = resultTime; } public Thing getThing() throws ServiceFailureException { if (thing == null && getService() != null) { thing = getService().things().find(this); } return thing; } public void setThing(Thing thing) { this.thing = thing; } public Sensor getSensor() throws ServiceFailureException { if (sensor == null && getService() != null) { sensor = getService().sensors().find(this); } return sensor; } public void setSensor(Sensor sensor) { this.sensor = sensor; } public ObservedProperty getObservedProperty() throws ServiceFailureException { if (observedProperty == null && getService() != null) { observedProperty = getService().observedProperties().find(this); } return observedProperty; } public void setObservedProperty(ObservedProperty observedProperty) { this.observedProperty = observedProperty; } public ObservationDao observations() { ObservationDao result = getService().observations(); result.setParent(this); return result; } @JsonProperty("Observations") public EntityList<Observation> getObservations() { return this.observations; } @JsonProperty("Observations") public void setObservations(List<Observation> observations) { this.observations.replaceAll(observations); } @Override public BaseDao<Datastream> getDao(SensorThingsService service) { return new DatastreamDao(service); } @Override public Datastream withOnlyId() { Datastream copy = new Datastream(); copy.setId(id); return copy; } @Override public String toString() { return super.toString() + " " + getName(); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/datastore/v1/entity.proto package com.google.datastore.v1; /** * <pre> * A partition ID identifies a grouping of entities. The grouping is always * by project and namespace, however the namespace ID may be empty. * A partition ID contains several dimensions: * project ID and namespace ID. * Partition dimensions: * - May be `""`. * - Must be valid UTF-8 bytes. * - Must have values that match regex `[A-Za-z&#92;d&#92;.&#92;-_]{1,100}` * If the value of any dimension matches regex `__.*__`, the partition is * reserved/read-only. * A reserved/read-only partition ID is forbidden in certain documented * contexts. * Foreign partition IDs (in which the project ID does * not match the context project ID ) are discouraged. * Reads and writes of foreign partition IDs may fail if the project is not in an active state. * </pre> * * Protobuf type {@code google.datastore.v1.PartitionId} */ public final class PartitionId extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.datastore.v1.PartitionId) PartitionIdOrBuilder { private static final long serialVersionUID = 0L; // Use PartitionId.newBuilder() to construct. private PartitionId(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private PartitionId() { projectId_ = ""; namespaceId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private PartitionId( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); projectId_ = s; break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); namespaceId_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.datastore.v1.EntityProto.internal_static_google_datastore_v1_PartitionId_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.datastore.v1.EntityProto.internal_static_google_datastore_v1_PartitionId_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.datastore.v1.PartitionId.class, com.google.datastore.v1.PartitionId.Builder.class); } public static final int PROJECT_ID_FIELD_NUMBER = 2; private volatile java.lang.Object projectId_; /** * <pre> * The ID of the project to which the entities belong. * </pre> * * <code>string project_id = 2;</code> */ public java.lang.String getProjectId() { java.lang.Object ref = projectId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); projectId_ = s; return s; } } /** * <pre> * The ID of the project to which the entities belong. * </pre> * * <code>string project_id = 2;</code> */ public com.google.protobuf.ByteString getProjectIdBytes() { java.lang.Object ref = projectId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); projectId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NAMESPACE_ID_FIELD_NUMBER = 4; private volatile java.lang.Object namespaceId_; /** * <pre> * If not empty, the ID of the namespace to which the entities belong. * </pre> * * <code>string namespace_id = 4;</code> */ public java.lang.String getNamespaceId() { java.lang.Object ref = namespaceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); namespaceId_ = s; return s; } } /** * <pre> * If not empty, the ID of the namespace to which the entities belong. * </pre> * * <code>string namespace_id = 4;</code> */ public com.google.protobuf.ByteString getNamespaceIdBytes() { java.lang.Object ref = namespaceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); namespaceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getProjectIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, projectId_); } if (!getNamespaceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, namespaceId_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getProjectIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, projectId_); } if (!getNamespaceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, namespaceId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.datastore.v1.PartitionId)) { return super.equals(obj); } com.google.datastore.v1.PartitionId other = (com.google.datastore.v1.PartitionId) obj; boolean result = true; result = result && getProjectId() .equals(other.getProjectId()); result = result && getNamespaceId() .equals(other.getNamespaceId()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PROJECT_ID_FIELD_NUMBER; hash = (53 * hash) + getProjectId().hashCode(); hash = (37 * hash) + NAMESPACE_ID_FIELD_NUMBER; hash = (53 * hash) + getNamespaceId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.datastore.v1.PartitionId parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.datastore.v1.PartitionId parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.datastore.v1.PartitionId parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.datastore.v1.PartitionId parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.datastore.v1.PartitionId parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.datastore.v1.PartitionId parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.datastore.v1.PartitionId parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.datastore.v1.PartitionId parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.datastore.v1.PartitionId parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.datastore.v1.PartitionId parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.datastore.v1.PartitionId parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.datastore.v1.PartitionId parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.datastore.v1.PartitionId prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * A partition ID identifies a grouping of entities. The grouping is always * by project and namespace, however the namespace ID may be empty. * A partition ID contains several dimensions: * project ID and namespace ID. * Partition dimensions: * - May be `""`. * - Must be valid UTF-8 bytes. * - Must have values that match regex `[A-Za-z&#92;d&#92;.&#92;-_]{1,100}` * If the value of any dimension matches regex `__.*__`, the partition is * reserved/read-only. * A reserved/read-only partition ID is forbidden in certain documented * contexts. * Foreign partition IDs (in which the project ID does * not match the context project ID ) are discouraged. * Reads and writes of foreign partition IDs may fail if the project is not in an active state. * </pre> * * Protobuf type {@code google.datastore.v1.PartitionId} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.datastore.v1.PartitionId) com.google.datastore.v1.PartitionIdOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.datastore.v1.EntityProto.internal_static_google_datastore_v1_PartitionId_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.datastore.v1.EntityProto.internal_static_google_datastore_v1_PartitionId_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.datastore.v1.PartitionId.class, com.google.datastore.v1.PartitionId.Builder.class); } // Construct using com.google.datastore.v1.PartitionId.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); projectId_ = ""; namespaceId_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.datastore.v1.EntityProto.internal_static_google_datastore_v1_PartitionId_descriptor; } public com.google.datastore.v1.PartitionId getDefaultInstanceForType() { return com.google.datastore.v1.PartitionId.getDefaultInstance(); } public com.google.datastore.v1.PartitionId build() { com.google.datastore.v1.PartitionId result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.google.datastore.v1.PartitionId buildPartial() { com.google.datastore.v1.PartitionId result = new com.google.datastore.v1.PartitionId(this); result.projectId_ = projectId_; result.namespaceId_ = namespaceId_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.datastore.v1.PartitionId) { return mergeFrom((com.google.datastore.v1.PartitionId)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.datastore.v1.PartitionId other) { if (other == com.google.datastore.v1.PartitionId.getDefaultInstance()) return this; if (!other.getProjectId().isEmpty()) { projectId_ = other.projectId_; onChanged(); } if (!other.getNamespaceId().isEmpty()) { namespaceId_ = other.namespaceId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.datastore.v1.PartitionId parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.datastore.v1.PartitionId) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object projectId_ = ""; /** * <pre> * The ID of the project to which the entities belong. * </pre> * * <code>string project_id = 2;</code> */ public java.lang.String getProjectId() { java.lang.Object ref = projectId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); projectId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The ID of the project to which the entities belong. * </pre> * * <code>string project_id = 2;</code> */ public com.google.protobuf.ByteString getProjectIdBytes() { java.lang.Object ref = projectId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); projectId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The ID of the project to which the entities belong. * </pre> * * <code>string project_id = 2;</code> */ public Builder setProjectId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } projectId_ = value; onChanged(); return this; } /** * <pre> * The ID of the project to which the entities belong. * </pre> * * <code>string project_id = 2;</code> */ public Builder clearProjectId() { projectId_ = getDefaultInstance().getProjectId(); onChanged(); return this; } /** * <pre> * The ID of the project to which the entities belong. * </pre> * * <code>string project_id = 2;</code> */ public Builder setProjectIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); projectId_ = value; onChanged(); return this; } private java.lang.Object namespaceId_ = ""; /** * <pre> * If not empty, the ID of the namespace to which the entities belong. * </pre> * * <code>string namespace_id = 4;</code> */ public java.lang.String getNamespaceId() { java.lang.Object ref = namespaceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); namespaceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * If not empty, the ID of the namespace to which the entities belong. * </pre> * * <code>string namespace_id = 4;</code> */ public com.google.protobuf.ByteString getNamespaceIdBytes() { java.lang.Object ref = namespaceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); namespaceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * If not empty, the ID of the namespace to which the entities belong. * </pre> * * <code>string namespace_id = 4;</code> */ public Builder setNamespaceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } namespaceId_ = value; onChanged(); return this; } /** * <pre> * If not empty, the ID of the namespace to which the entities belong. * </pre> * * <code>string namespace_id = 4;</code> */ public Builder clearNamespaceId() { namespaceId_ = getDefaultInstance().getNamespaceId(); onChanged(); return this; } /** * <pre> * If not empty, the ID of the namespace to which the entities belong. * </pre> * * <code>string namespace_id = 4;</code> */ public Builder setNamespaceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); namespaceId_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.datastore.v1.PartitionId) } // @@protoc_insertion_point(class_scope:google.datastore.v1.PartitionId) private static final com.google.datastore.v1.PartitionId DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.datastore.v1.PartitionId(); } public static com.google.datastore.v1.PartitionId getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<PartitionId> PARSER = new com.google.protobuf.AbstractParser<PartitionId>() { public PartitionId parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new PartitionId(input, extensionRegistry); } }; public static com.google.protobuf.Parser<PartitionId> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<PartitionId> getParserForType() { return PARSER; } public com.google.datastore.v1.PartitionId getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package de.andre.maven.install.ui; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Collections; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import org.apache.maven.shared.invoker.DefaultInvocationRequest; import org.apache.maven.shared.invoker.DefaultInvoker; import org.apache.maven.shared.invoker.InvocationRequest; import org.apache.maven.shared.invoker.Invoker; /** * Created with Netbeans Swing UI Design builder. * @author Andre Albert */ public class InstallLibraryDialog extends javax.swing.JDialog { /** * A return status code - returned if Cancel button has been pressed */ public static final int RET_CANCEL = 0; /** * A return status code - returned if OK button has been pressed */ public static final int RET_OK = 1; /** * Creates new form InstallLibraryDialog */ public InstallLibraryDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); // Close the dialog when Esc is pressed setTitle("Install .jar Library"); String cancelName = "cancel"; InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName); ActionMap actionMap = getRootPane().getActionMap(); actionMap.put(cancelName, new AbstractAction() { public void actionPerformed(ActionEvent e) { doClose(RET_CANCEL); } }); } /** * @return the return status of this dialog - one of RET_OK or RET_CANCEL */ public int getReturnStatus() { return returnStatus; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jFileChooser1 = new javax.swing.JFileChooser(); okButton = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); groupIdField = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); artifactIdField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); versionField = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); fileField = new javax.swing.JTextField(); openFileChooserBtn = new javax.swing.JButton(); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { closeDialog(evt); } }); okButton.setText("Install"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); jLabel1.setText("GroupId"); jLabel2.setText("ArtifactId"); jLabel3.setText("Version"); jLabel4.setText("Library"); openFileChooserBtn.setText("..."); openFileChooserBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openFileChooserBtnActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4)) .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(versionField) .addComponent(artifactIdField) .addComponent(groupIdField) .addComponent(fileField)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(openFileChooserBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(88, 88, 88) .addComponent(okButton, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(16, 16, 16) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(groupIdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(artifactIdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(versionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(fileField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(openFileChooserBtn)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE) .addComponent(okButton) .addContainerGap()) ); getRootPane().setDefaultButton(okButton); pack(); }// </editor-fold>//GEN-END:initComponents private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed String groupId = this.groupIdField.getText(); String artifactId = this.artifactIdField.getText(); String version = this.versionField.getText(); String file = this.fileField.getText(); InvocationRequest req = new DefaultInvocationRequest(); req.setGoals( Collections.singletonList( "install:install-file" ) ); req.setMavenOpts("-Dfile="+file+" -DgroupId="+groupId+" -DartifactId="+artifactId+" -Dversion="+version+" -Dpackaging=jar"); Invoker invoker = new DefaultInvoker(); try { invoker.execute( req ); JOptionPane.showMessageDialog(null, "Library installed"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Library could not be installed", "Install Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_okButtonActionPerformed /** * Closes the dialog */ private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog doClose(RET_CANCEL); }//GEN-LAST:event_closeDialog private void openFileChooserBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openFileChooserBtnActionPerformed //Create a file chooser final JFileChooser fc = new JFileChooser(); //In response to a button click: int returnVal = fc.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { final String absolutePath = fc.getSelectedFile().getAbsolutePath(); this.fileField.setText(absolutePath); } }//GEN-LAST:event_openFileChooserBtnActionPerformed private void doClose(int retStatus) { returnStatus = retStatus; setVisible(false); dispose(); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(InstallLibraryDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(InstallLibraryDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(InstallLibraryDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(InstallLibraryDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { InstallLibraryDialog dialog = new InstallLibraryDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField artifactIdField; private javax.swing.JTextField fileField; private javax.swing.JTextField groupIdField; private javax.swing.JFileChooser jFileChooser1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JButton okButton; private javax.swing.JButton openFileChooserBtn; private javax.swing.JTextField versionField; // End of variables declaration//GEN-END:variables private int returnStatus = RET_CANCEL; }
package com.dcp.sm.gui.pivot.tasks; import java.io.File; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import javax.xml.stream.XMLStreamException; import org.apache.commons.io.FileUtils; import org.apache.pivot.collections.List; import org.apache.pivot.util.concurrent.Task; import org.apache.pivot.wtk.Component; import com.dcp.sm.config.compile.NugetProcessCompiler; import com.dcp.sm.config.io.IOFactory; import com.dcp.sm.config.io.ps.chocolatey.InstallWriter; import com.dcp.sm.config.io.xml.nuget.ConfigWriter; import com.dcp.sm.config.io.xml.nuget.SpecWriter; import com.dcp.sm.gui.pivot.Master; import com.dcp.sm.logic.factory.PackFactory; import com.dcp.sm.logic.factory.TypeFactory.FILE_TYPE; import com.dcp.sm.logic.factory.TypeFactory.LOG_LEVEL; import com.dcp.sm.logic.model.Pack; import com.dcp.sm.logic.model.config.SetupConfig; import com.dcp.sm.main.log.Out; /** * * @author SSAIDELI * */ public class TaskNugetCompile extends Task<Boolean> { private NugetProcessCompiler compiler = new NugetProcessCompiler();// NuGet process compiler private String feedUrl;// nuget feed http url private int stepNbr;// step nbr (1.Config - 2.Spec - 3.Pack - 4.Push) private List<Pack> packs = PackFactory.getPacks(); private SetupConfig setupConfig = Master.facade.setupConfig; public TaskNugetCompile(String targetPath, String feedUrl, int stepNbr) { this.compiler.setTarget(targetPath); this.feedUrl = feedUrl; this.stepNbr = stepNbr; } // Set log component to display compile stream public void setLogger(Component LOGGER) { Out.setLogger(LOGGER); } @Override public Boolean execute() { try { Out.print(LOG_LEVEL.INFO, "Compiling package to " + compiler.getTarget()); if (stepNbr > 0 && !config()) return false; if (stepNbr > 1 && !writeSpecs()) return false; if (stepNbr > 2 && (!pack() || !clean()) ) return false; if (stepNbr > 3 && !push()) return false; Out.print(LOG_LEVEL.INFO, "Compilation success."); return true; } catch (IOException e) { e.printStackTrace(); } catch (XMLStreamException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } /** * Write a config file containing a list of all packages to install * Used for Chocolatey install command ($ cinst packages.config) * @return boolean: success * @throws XMLStreamException */ private boolean config() throws XMLStreamException { Out.print(LOG_LEVEL.INFO, "Adding chocolatey config file for install.."); ConfigWriter CW = new ConfigWriter(new File(compiler.getTarget(), "packages.config").toString(), this.feedUrl); CW.writePackages(packs); CW.close(); return true; } /** * Writes Specs (.nuspec) files for packs * @return boolean: success * @throws XMLStreamException * @throws IOException */ private boolean writeSpecs() throws XMLStreamException, IOException, FileAlreadyExistsException { Out.print(LOG_LEVEL.INFO, "Writing NuSpec files.."); SpecWriter SW; InstallWriter InstW = new InstallWriter(IOFactory.psChocolateyInstall); InstallWriter UninstW = new InstallWriter(IOFactory.psChocolateyUninstall); File repo, tools, nuspec, install, uninstall; for(Pack pack:packs) { if (pack.isHidden()) continue; // discard hidden packs (included in packs depending on them) // file pointers repo = new File(compiler.getTarget(), pack.getInstallName()); tools = new File(repo.toString(), "tools"); nuspec = new File(repo.toString(), pack.getInstallName()+".nuspec"); install = new File(tools.toString(), "chocolateyInstall.ps1"); uninstall = new File(tools.toString(), "chocolateyUninstall.ps1"); // files cleaning if override if (!repo.exists()) repo.mkdir(); else if (!pack.isOverride()) continue; else if (nuspec.exists()) Files.delete(nuspec.toPath()); if (!tools.exists()) tools.mkdir(); else if (install.exists()) Files.delete(install.toPath()); // nuspec writing SW = new SpecWriter(nuspec.toString()); SW.writeMetadata(pack); SW.close(); // powershell ps files templating // install script InstW.fillFrom(setupConfig.getInstallPath(), pack); InstW.writeTo(install); // uninstall script UninstW.fillFrom(setupConfig.getInstallPath(), pack); UninstW.writeTo(uninstall); deployOptionPrepare(repo, pack); if (pack.getPackDependency() != null && pack.getPackDependency().isHidden()) deployOptionPrepare(repo, pack.getPackDependency()); else if (pack.getGroupDependency() != null) { for(Pack p:packs) if (p.getGroup() != null && p.isHidden() && ( p.getGroup() == pack.getGroupDependency() || p.getGroup().hasParent(pack.getGroupDependency()) )) deployOptionPrepare(repo, p); } } return true; } // Copy file/folder content to target path private void copy(File srcFile, File targetFile) throws IOException { assert srcFile.exists(); if (srcFile.isDirectory()) { FileUtils.copyDirectory(srcFile, targetFile); } else { FileUtils.copyFile(srcFile, targetFile); //Files.copy(srcFile.toPath(), targetFile.toPath()); } } /** * Adds files to folder depending on deploy type * @param repo * @param p * @throws IOException */ private void deployOptionPrepare(File repo, Pack p) throws IOException { File copyFolder, extrFolder, execFolder; switch (p.getInstallType()) { case DEFAULT: case COPY: copyFolder = new File(repo.toString(), "copy"); copyFolder.mkdir(); //Files.copy(new File(p.getPath()).toPath(), new File(copyFolder, p.getName()).toPath()); copy(new File(p.getPath()), new File(copyFolder, p.getName())); Out.print(LOG_LEVEL.DEBUG, "copy "+ p.getPath() + " to " + new File(copyFolder, p.getName()).toString()); break; case EXTRACT: extrFolder = new File(repo.toString(), "extr"); extrFolder.mkdir(); //Files.copy(new File(p.getPath()).toPath(), new File(extrFolder, p.getName()).toPath()); copy(new File(p.getPath()), new File(extrFolder, p.getName())); Out.print(LOG_LEVEL.DEBUG, "copy "+ p.getPath() + " to " + new File(extrFolder, p.getName()).toString()); break; case EXECUTE: execFolder = new File(repo.toString(), "exec"); execFolder.mkdir(); //Files.copy(new File(p.getPath()).toPath(), new File(execFolder, p.getName()).toPath()); copy(new File(p.getPath()), new File(execFolder, p.getName())); if (p.getFileType() == FILE_TYPE.Executable) // create new empty file flag to ignore batch redirection to executable new File(execFolder, p.getName()+".ignore").createNewFile(); Out.print(LOG_LEVEL.DEBUG, "copy "+ p.getPath() + " to " + new File(execFolder, p.getName()).toString()); break; default: break; } } //nuget pack oracle/oracle.nuspec -NoPackageAnalysis /** * Pack nuspec files to nupkg packages * @return boolean: success * @throws IOException * @throws InterruptedException */ private boolean pack() throws IOException, InterruptedException { Out.print(LOG_LEVEL.INFO, "Packing NuSpec files to NuPkg.."); boolean success = true; int errCode = 0; File pkg, nuspec; for (Pack p:packs) { if (p.isHidden()) continue; // discard hidden packs (included in packs depending on them) pkg = new File(compiler.getTarget(), p.getInstallName() + "." + p.getInstallVersion() + ".nupkg"); nuspec = new File(compiler.getTarget(), new File(p.getInstallName(), p.getInstallName()+".nuspec").toString()); Out.print(LOG_LEVEL.DEBUG, "Packing spec file "+ nuspec.toString() + " to package " + pkg.toString()); if (!p.isOverride() && pkg.exists()) continue; errCode = compiler.pack(nuspec).waitFor(); if (errCode != 0) { Out.print(LOG_LEVEL.ERR, "Packing package " + pkg.toString() + " exited with code " + errCode); success = false; } } return success; } /** * Delete source folders containing spec files * @return boolean: success * @throws IOException */ private boolean clean() throws IOException { Out.print(LOG_LEVEL.INFO, "Cleaning Specification folders.."); File file; String path; for(Pack p:packs) { file = new File(compiler.getTarget(), p.getInstallName()); if (file.exists()) { path = file.toString(); Out.print(LOG_LEVEL.DEBUG, "Deleting file " + path); compiler.cleanDir(path); } } return true; } /** * Push (send) packaged packs to nuget feed * @return boolean: success * @throws IOException * @throws InterruptedException */ private boolean push() throws InterruptedException, IOException { Out.print(LOG_LEVEL.INFO, "Sending packages to nuget feed " + feedUrl); boolean success = true; int errCode = 0; File pkg; for(Pack p:packs) { pkg = new File(compiler.getTarget(), p.getInstallName() + "." + p.getInstallVersion() + ".nupkg"); if (!p.isHidden() && pkg.exists()) { Out.print(LOG_LEVEL.DEBUG, "Sending file " + pkg.toString()); errCode = compiler.push(pkg, feedUrl).waitFor(); if (errCode != 0) { Out.print(LOG_LEVEL.ERR, "Pushing package " + pkg.toString() + " exited with code " + errCode); success = false; } } } return success; } }
/* * 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.activemq.artemis.core.remoting.server.impl; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.ActiveMQInterruptedException; import org.apache.activemq.artemis.api.core.BaseInterceptor; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.protocol.core.CoreRemotingConnection; import org.apache.activemq.artemis.core.protocol.core.impl.CoreProtocolManagerFactory; import org.apache.activemq.artemis.core.remoting.FailureListener; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.core.remoting.server.RemotingService; import org.apache.activemq.artemis.core.security.ActiveMQPrincipal; import org.apache.activemq.artemis.core.server.ActiveMQComponent; import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.core.server.ServiceRegistry; import org.apache.activemq.artemis.core.server.cluster.ClusterConnection; import org.apache.activemq.artemis.core.server.cluster.ClusterManager; import org.apache.activemq.artemis.core.server.impl.ServerSessionImpl; import org.apache.activemq.artemis.core.server.management.ManagementService; import org.apache.activemq.artemis.spi.core.protocol.ConnectionEntry; import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager; import org.apache.activemq.artemis.spi.core.protocol.ProtocolManagerFactory; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.spi.core.remoting.Acceptor; import org.apache.activemq.artemis.spi.core.remoting.AcceptorFactory; import org.apache.activemq.artemis.spi.core.remoting.BufferHandler; import org.apache.activemq.artemis.spi.core.remoting.Connection; import org.apache.activemq.artemis.spi.core.remoting.ConnectionLifeCycleListener; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; import org.apache.activemq.artemis.utils.ConfigurationHelper; import org.apache.activemq.artemis.utils.ReusableLatch; public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycleListener { // Constants ----------------------------------------------------- private static final boolean isTrace = ActiveMQServerLogger.LOGGER.isTraceEnabled(); public static final long CONNECTION_TTL_CHECK_INTERVAL = 2000; // Attributes ---------------------------------------------------- private volatile boolean started = false; private final Set<TransportConfiguration> acceptorsConfig; private final List<BaseInterceptor> incomingInterceptors = new CopyOnWriteArrayList<>(); private final List<BaseInterceptor> outgoingInterceptors = new CopyOnWriteArrayList<>(); private final Map<String, Acceptor> acceptors = new HashMap<String, Acceptor>(); private final Map<Object, ConnectionEntry> connections = new ConcurrentHashMap<Object, ConnectionEntry>(); private final ReusableLatch connectionCountLatch = new ReusableLatch(0); private final ActiveMQServer server; private final ManagementService managementService; private ExecutorService threadPool; private final Executor flushExecutor; private final ScheduledExecutorService scheduledThreadPool; private FailureCheckAndFlushThread failureCheckAndFlushThread; private final ClusterManager clusterManager; private final Map<String, ProtocolManager> protocolMap = new ConcurrentHashMap(); private ActiveMQPrincipal defaultInvmSecurityPrincipal; private ServiceRegistry serviceRegistry; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public RemotingServiceImpl(final ClusterManager clusterManager, final Configuration config, final ActiveMQServer server, final ManagementService managementService, final ScheduledExecutorService scheduledThreadPool, List<ProtocolManagerFactory> protocolManagerFactories, final Executor flushExecutor, final ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; acceptorsConfig = config.getAcceptorConfigurations(); this.server = server; this.clusterManager = clusterManager; setInterceptors(config); this.managementService = managementService; this.scheduledThreadPool = scheduledThreadPool; CoreProtocolManagerFactory coreProtocolManagerFactory = new CoreProtocolManagerFactory(); //i know there is only 1 this.flushExecutor = flushExecutor; ActiveMQServerLogger.LOGGER.addingProtocolSupport(coreProtocolManagerFactory.getProtocols()[0], coreProtocolManagerFactory.getModuleName()); this.protocolMap.put(coreProtocolManagerFactory.getProtocols()[0], coreProtocolManagerFactory.createProtocolManager(server, coreProtocolManagerFactory.filterInterceptors(incomingInterceptors), coreProtocolManagerFactory.filterInterceptors(outgoingInterceptors))); if (config.isResolveProtocols()) { resolveProtocols(server, this.getClass().getClassLoader()); if (this.getClass().getClassLoader() != Thread.currentThread().getContextClassLoader()) { resolveProtocols(server, Thread.currentThread().getContextClassLoader()); } } if (protocolManagerFactories != null) { for (ProtocolManagerFactory protocolManagerFactory : protocolManagerFactories) { String[] protocols = protocolManagerFactory.getProtocols(); for (String protocol : protocols) { ActiveMQServerLogger.LOGGER.addingProtocolSupport(protocol, protocolManagerFactory.getModuleName()); protocolMap.put(protocol, protocolManagerFactory.createProtocolManager(server, incomingInterceptors, outgoingInterceptors)); } } } } private void resolveProtocols(ActiveMQServer server, ClassLoader loader) { ServiceLoader<ProtocolManagerFactory> serviceLoader = ServiceLoader.load(ProtocolManagerFactory.class, loader); if (serviceLoader != null) { for (ProtocolManagerFactory next : serviceLoader) { String[] protocols = next.getProtocols(); for (String protocol : protocols) { ActiveMQServerLogger.LOGGER.addingProtocolSupport(protocol, next.getModuleName()); protocolMap.put(protocol, next.createProtocolManager(server, next.filterInterceptors(incomingInterceptors), next.filterInterceptors(outgoingInterceptors))); } } } } private void setInterceptors(Configuration configuration) { incomingInterceptors.addAll(serviceRegistry.getIncomingInterceptors(configuration.getIncomingInterceptorClassNames())); outgoingInterceptors.addAll(serviceRegistry.getOutgoingInterceptors(configuration.getOutgoingInterceptorClassNames())); } public synchronized void start() throws Exception { if (started) { return; } // The remoting service maintains it's own thread pool for handling remoting traffic // If OIO each connection will have it's own thread // If NIO these are capped at nio-remoting-threads which defaults to num cores * 3 // This needs to be a different thread pool to the main thread pool especially for OIO where we may need // to support many hundreds of connections, but the main thread pool must be kept small for better performance ThreadFactory tFactory = AccessController.doPrivileged(new PrivilegedAction<ThreadFactory>() { @Override public ThreadFactory run() { return new ActiveMQThreadFactory("ActiveMQ-remoting-threads-" + server.toString() + "-" + System.identityHashCode(this), false, Thread.currentThread().getContextClassLoader()); } }); threadPool = Executors.newCachedThreadPool(tFactory); HashSet<TransportConfiguration> namelessAcceptors = new HashSet<>(); for (TransportConfiguration info : acceptorsConfig) { TransportConfiguration nameless = info.newTransportConfig(""); if (namelessAcceptors.contains(nameless)) { ActiveMQServerLogger.LOGGER.duplicatedAcceptor(info.getName(), "" + info.getParams(), info.getFactoryClassName()); continue; } namelessAcceptors.add(nameless); try { AcceptorFactory factory = server.getServiceRegistry().getAcceptorFactory(info.getName(), info.getFactoryClassName()); Map<String, ProtocolManager> supportedProtocols = new ConcurrentHashMap(); String protocol = ConfigurationHelper.getStringProperty(TransportConstants.PROTOCOL_PROP_NAME, null, info.getParams()); if (protocol != null) { ActiveMQServerLogger.LOGGER.warnDeprecatedProtocol(); ProtocolManager protocolManager = protocolMap.get(protocol); if (protocolManager == null) { ActiveMQServerLogger.LOGGER.noProtocolManagerFound(protocol, info.toString()); } else { supportedProtocols.put(protocol, protocolManager); } } String protocols = ConfigurationHelper.getStringProperty(TransportConstants.PROTOCOLS_PROP_NAME, null, info.getParams()); if (protocols != null) { String[] actualProtocols = protocols.split(","); if (actualProtocols != null) { for (String actualProtocol : actualProtocols) { ProtocolManager protocolManager = protocolMap.get(actualProtocol); if (protocolManager == null) { ActiveMQServerLogger.LOGGER.noProtocolManagerFound(actualProtocol, info.toString()); } else { supportedProtocols.put(actualProtocol, protocolManager); } } } } ClusterConnection clusterConnection = lookupClusterConnection(info); Acceptor acceptor = factory.createAcceptor(info.getName(), clusterConnection, info.getParams(), new DelegatingBufferHandler(), this, threadPool, scheduledThreadPool, supportedProtocols.isEmpty() ? protocolMap : supportedProtocols); if (defaultInvmSecurityPrincipal != null && acceptor.isUnsecurable()) { acceptor.setDefaultActiveMQPrincipal(defaultInvmSecurityPrincipal); } acceptors.put(info.getName(), acceptor); if (managementService != null) { acceptor.setNotificationService(managementService); managementService.registerAcceptor(acceptor, info); } } catch (Exception e) { ActiveMQServerLogger.LOGGER.errorCreatingAcceptor(e, info.getFactoryClassName()); } } /** * Don't start the acceptors here. Only start the acceptors at the every end of the start-up process to avoid * race conditions. See {@link #startAcceptors()}. */ // This thread checks connections that need to be closed, and also flushes confirmations failureCheckAndFlushThread = new FailureCheckAndFlushThread(RemotingServiceImpl.CONNECTION_TTL_CHECK_INTERVAL); failureCheckAndFlushThread.start(); started = true; } public synchronized void startAcceptors() throws Exception { if (isStarted()) { for (Acceptor a : acceptors.values()) { a.start(); } } } public synchronized void allowInvmSecurityOverride(ActiveMQPrincipal principal) { defaultInvmSecurityPrincipal = principal; for (Acceptor acceptor : acceptors.values()) { if (acceptor.isUnsecurable()) { acceptor.setDefaultActiveMQPrincipal(principal); } } } public synchronized void pauseAcceptors() { if (!started) return; for (Acceptor acceptor : acceptors.values()) { try { acceptor.pause(); } catch (Exception e) { ActiveMQServerLogger.LOGGER.errorStoppingAcceptor(); } } } public synchronized void freeze(final String scaleDownNodeID, final CoreRemotingConnection connectionToKeepOpen) { if (!started) return; failureCheckAndFlushThread.close(false); HashMap<Object, ConnectionEntry> connectionEntries = new HashMap<Object, ConnectionEntry>(connections); // Now we ensure that no connections will process any more packets after this method is // complete then send a disconnect packet for (Entry<Object, ConnectionEntry> entry : connectionEntries.entrySet()) { RemotingConnection conn = entry.getValue().connection; if (conn.equals(connectionToKeepOpen)) continue; if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Sending connection.disconnection packet to " + conn); } if (!conn.isClient()) { conn.disconnect(scaleDownNodeID, false); removeConnection(entry.getKey()); } } } public void stop(final boolean criticalError) throws Exception { if (!started) { return; } failureCheckAndFlushThread.close(criticalError); // We need to stop them accepting first so no new connections are accepted after we send the disconnect message for (Acceptor acceptor : acceptors.values()) { if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Pausing acceptor " + acceptor); } acceptor.pause(); } if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Sending disconnect on live connections"); } HashSet<ConnectionEntry> connectionEntries = new HashSet<ConnectionEntry>(connections.values()); // Now we ensure that no connections will process any more packets after this method is complete // then send a disconnect packet for (ConnectionEntry entry : connectionEntries) { RemotingConnection conn = entry.connection; if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("Sending connection.disconnection packet to " + conn); } conn.disconnect(criticalError); } for (Acceptor acceptor : acceptors.values()) { acceptor.stop(); } acceptors.clear(); connections.clear(); connectionCountLatch.setCount(0); if (managementService != null) { managementService.unregisterAcceptors(); } threadPool.shutdown(); if (!criticalError) { boolean ok = threadPool.awaitTermination(10000, TimeUnit.MILLISECONDS); if (!ok) { ActiveMQServerLogger.LOGGER.timeoutRemotingThreadPool(); } } started = false; } @Override public Acceptor getAcceptor(String name) { return acceptors.get(name); } public boolean isStarted() { return started; } private RemotingConnection getConnection(final Object remotingConnectionID) { ConnectionEntry entry = connections.get(remotingConnectionID); if (entry != null) { return entry.connection; } else { ActiveMQServerLogger.LOGGER.errorRemovingConnection(); return null; } } public RemotingConnection removeConnection(final Object remotingConnectionID) { ConnectionEntry entry = connections.remove(remotingConnectionID); if (entry != null) { ActiveMQServerLogger.LOGGER.debug("RemotingServiceImpl::removing connection ID " + remotingConnectionID); connectionCountLatch.countDown(); return entry.connection; } else { ActiveMQServerLogger.LOGGER.debug("The connectionID::" + remotingConnectionID + " was already removed by some other module"); return null; } } public synchronized Set<RemotingConnection> getConnections() { Set<RemotingConnection> conns = new HashSet<RemotingConnection>(connections.size()); for (ConnectionEntry entry : connections.values()) { conns.add(entry.connection); } return conns; } public synchronized ReusableLatch getConnectionCountLatch() { return connectionCountLatch; } // ConnectionLifeCycleListener implementation ----------------------------------- private ProtocolManager getProtocolManager(String protocol) { return protocolMap.get(protocol); } public void connectionCreated(final ActiveMQComponent component, final Connection connection, final String protocol) { if (server == null) { throw new IllegalStateException("Unable to create connection, server hasn't finished starting up"); } ProtocolManager pmgr = this.getProtocolManager(protocol.toString()); if (pmgr == null) { throw ActiveMQMessageBundle.BUNDLE.unknownProtocol(protocol); } ConnectionEntry entry = pmgr.createConnectionEntry((Acceptor) component, connection); if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Connection created " + connection); } connections.put(connection.getID(), entry); connectionCountLatch.countUp(); } public void connectionDestroyed(final Object connectionID) { if (isTrace) { ActiveMQServerLogger.LOGGER.trace("Connection removed " + connectionID + " from server " + this.server, new Exception("trace")); } ConnectionEntry conn = connections.get(connectionID); if (conn != null) { // Bit of a hack - find a better way to do this List<FailureListener> failureListeners = conn.connection.getFailureListeners(); boolean empty = true; for (FailureListener listener : failureListeners) { if (listener instanceof ServerSessionImpl) { empty = false; break; } } // We only destroy the connection if the connection has no sessions attached to it // Otherwise it means the connection has died without the sessions being closed first // so we need to keep them for ttl, in case re-attachment occurs if (empty) { removeConnection(connectionID); conn.connection.destroy(); } } } public void connectionException(final Object connectionID, final ActiveMQException me) { // We DO NOT call fail on connection exception, otherwise in event of real connection failure, the // connection will be failed, the session will be closed and won't be able to reconnect // E.g. if live server fails, then this handler wil be called on backup server for the server // side replicating connection. // If the connection fail() is called then the sessions on the backup will get closed. // Connections should only fail when TTL is exceeded } public void connectionReadyForWrites(final Object connectionID, final boolean ready) { } @Override public void addIncomingInterceptor(final BaseInterceptor interceptor) { incomingInterceptors.add(interceptor); updateProtocols(); } @Override public List<BaseInterceptor> getIncomingInterceptors() { return Collections.unmodifiableList(incomingInterceptors); } @Override public boolean removeIncomingInterceptor(final BaseInterceptor interceptor) { if (incomingInterceptors.remove(interceptor)) { updateProtocols(); return true; } else { return false; } } @Override public void addOutgoingInterceptor(final BaseInterceptor interceptor) { outgoingInterceptors.add(interceptor); updateProtocols(); } @Override public List<BaseInterceptor> getOutgoinInterceptors() { return Collections.unmodifiableList(outgoingInterceptors); } @Override public boolean removeOutgoingInterceptor(final BaseInterceptor interceptor) { if (outgoingInterceptors.remove(interceptor)) { updateProtocols(); return true; } else { return false; } } private ClusterConnection lookupClusterConnection(TransportConfiguration acceptorConfig) { String clusterConnectionName = (String) acceptorConfig.getParams().get(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.CLUSTER_CONNECTION); ClusterConnection clusterConnection = null; if (clusterConnectionName != null) { clusterConnection = clusterManager.getClusterConnection(clusterConnectionName); } // if not found we will still use the default name, even if a name was provided if (clusterConnection == null) { clusterConnection = clusterManager.getDefaultConnection(acceptorConfig); } return clusterConnection; } // Inner classes ------------------------------------------------- private final class DelegatingBufferHandler implements BufferHandler { public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer) { ConnectionEntry conn = connections.get(connectionID); if (conn != null) { conn.connection.bufferReceived(connectionID, buffer); } else { if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) { ActiveMQServerLogger.LOGGER.trace("ConnectionID = " + connectionID + " was already closed, so ignoring packet"); } } } } private final class FailureCheckAndFlushThread extends Thread { private final long pauseInterval; private volatile boolean closed; private final CountDownLatch latch = new CountDownLatch(1); FailureCheckAndFlushThread(final long pauseInterval) { super("activemq-failure-check-thread"); this.pauseInterval = pauseInterval; } public void close(final boolean criticalError) { closed = true; latch.countDown(); if (!criticalError) { try { join(); } catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } } } @Override public void run() { while (!closed) { try { long now = System.currentTimeMillis(); Set<Object> idsToRemove = new HashSet<Object>(); for (ConnectionEntry entry : connections.values()) { final RemotingConnection conn = entry.connection; boolean flush = true; if (entry.ttl != -1) { if (!conn.checkDataReceived()) { if (now >= entry.lastCheck + entry.ttl) { idsToRemove.add(conn.getID()); flush = false; } } else { entry.lastCheck = now; } } if (flush) { flushExecutor.execute(new Runnable() { public void run() { try { // this is using a different thread // as if anything wrong happens on flush // failure detection could be affected conn.flush(); } catch (Throwable e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } }); } } for (Object id : idsToRemove) { RemotingConnection conn = getConnection(id); if (conn != null) { conn.fail(ActiveMQMessageBundle.BUNDLE.clientExited(conn.getRemoteAddress())); removeConnection(id); } } if (latch.await(pauseInterval, TimeUnit.MILLISECONDS)) return; } catch (Throwable e) { ActiveMQServerLogger.LOGGER.errorOnFailureCheck(e); } } } } protected void updateProtocols() { for (ProtocolManager<?> protocolManager : this.protocolMap.values()) { protocolManager.updateInterceptors(incomingInterceptors, outgoingInterceptors); } } }
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.indexing.common.actions; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableSet; import io.druid.indexing.common.TaskLockType; import io.druid.indexing.common.task.Task; import io.druid.indexing.overlord.IndexerMetadataStorageCoordinator; import io.druid.indexing.overlord.LockResult; import io.druid.java.util.common.IAE; import io.druid.java.util.common.ISE; import io.druid.java.util.common.StringUtils; import io.druid.java.util.common.granularity.Granularity; import io.druid.java.util.common.logger.Logger; import io.druid.segment.realtime.appenderator.SegmentIdentifier; import io.druid.timeline.DataSegment; import org.joda.time.DateTime; import org.joda.time.Interval; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * Allocates a pending segment for a given timestamp. The preferredSegmentGranularity is used if there are no prior * segments for the given timestamp, or if the prior segments for the given timestamp are already at the * preferredSegmentGranularity. Otherwise, the prior segments will take precedence. * <p/> * This action implicitly acquires locks when it allocates segments. You do not have to acquire them beforehand, * although you *do* have to release them yourself. * <p/> * If this action cannot acquire an appropriate lock, or if it cannot expand an existing segment set, it returns null. */ public class SegmentAllocateAction implements TaskAction<SegmentIdentifier> { private static final Logger log = new Logger(SegmentAllocateAction.class); // Prevent spinning forever in situations where the segment list just won't stop changing. private static final int MAX_ATTEMPTS = 90; private final String dataSource; private final DateTime timestamp; private final Granularity queryGranularity; private final Granularity preferredSegmentGranularity; private final String sequenceName; private final String previousSegmentId; private final boolean skipSegmentLineageCheck; public SegmentAllocateAction( @JsonProperty("dataSource") String dataSource, @JsonProperty("timestamp") DateTime timestamp, @JsonProperty("queryGranularity") Granularity queryGranularity, @JsonProperty("preferredSegmentGranularity") Granularity preferredSegmentGranularity, @JsonProperty("sequenceName") String sequenceName, @JsonProperty("previousSegmentId") String previousSegmentId, @JsonProperty("skipSegmentLineageCheck") boolean skipSegmentLineageCheck ) { this.dataSource = Preconditions.checkNotNull(dataSource, "dataSource"); this.timestamp = Preconditions.checkNotNull(timestamp, "timestamp"); this.queryGranularity = Preconditions.checkNotNull(queryGranularity, "queryGranularity"); this.preferredSegmentGranularity = Preconditions.checkNotNull( preferredSegmentGranularity, "preferredSegmentGranularity" ); this.sequenceName = Preconditions.checkNotNull(sequenceName, "sequenceName"); this.previousSegmentId = previousSegmentId; this.skipSegmentLineageCheck = skipSegmentLineageCheck; } @JsonProperty public String getDataSource() { return dataSource; } @JsonProperty public DateTime getTimestamp() { return timestamp; } @JsonProperty public Granularity getQueryGranularity() { return queryGranularity; } @JsonProperty public Granularity getPreferredSegmentGranularity() { return preferredSegmentGranularity; } @JsonProperty public String getSequenceName() { return sequenceName; } @JsonProperty public String getPreviousSegmentId() { return previousSegmentId; } @JsonProperty public boolean isSkipSegmentLineageCheck() { return skipSegmentLineageCheck; } @Override public TypeReference<SegmentIdentifier> getReturnTypeReference() { return new TypeReference<SegmentIdentifier>() { }; } @Override public SegmentIdentifier perform( final Task task, final TaskActionToolbox toolbox ) { int attempt = 0; while (true) { attempt++; if (!task.getDataSource().equals(dataSource)) { throw new IAE("Task dataSource must match action dataSource, [%s] != [%s].", task.getDataSource(), dataSource); } final IndexerMetadataStorageCoordinator msc = toolbox.getIndexerMetadataStorageCoordinator(); // 1) if something overlaps our timestamp, use that // 2) otherwise try preferredSegmentGranularity & going progressively smaller final Interval rowInterval = queryGranularity.bucket(timestamp); final Set<DataSegment> usedSegmentsForRow = ImmutableSet.copyOf( msc.getUsedSegmentsForInterval(dataSource, rowInterval) ); final SegmentIdentifier identifier = usedSegmentsForRow.isEmpty() ? tryAllocateFirstSegment(toolbox, task, rowInterval) : tryAllocateSubsequentSegment( toolbox, task, rowInterval, usedSegmentsForRow.iterator().next() ); if (identifier != null) { return identifier; } // Could not allocate a pending segment. There's a chance that this is because someone else inserted a segment // overlapping with this row between when we called "mdc.getUsedSegmentsForInterval" and now. Check it again, // and if it's different, repeat. if (!ImmutableSet.copyOf(msc.getUsedSegmentsForInterval(dataSource, rowInterval)).equals(usedSegmentsForRow)) { if (attempt < MAX_ATTEMPTS) { final long shortRandomSleep = 50 + (long) (Math.random() * 450); log.debug( "Used segment set changed for rowInterval[%s]. Retrying segment allocation in %,dms (attempt = %,d).", rowInterval, shortRandomSleep, attempt ); try { Thread.sleep(shortRandomSleep); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } } else { log.error( "Used segment set changed for rowInterval[%s]. Not trying again (attempt = %,d).", rowInterval, attempt ); return null; } } else { return null; } } } private SegmentIdentifier tryAllocateFirstSegment(TaskActionToolbox toolbox, Task task, Interval rowInterval) { // No existing segments for this row, but there might still be nearby ones that conflict with our preferred // segment granularity. Try that first, and then progressively smaller ones if it fails. final List<Interval> tryIntervals = Granularity.granularitiesFinerThan(preferredSegmentGranularity) .stream() .map(granularity -> granularity.bucket(timestamp)) .collect(Collectors.toList()); for (Interval tryInterval : tryIntervals) { if (tryInterval.contains(rowInterval)) { final SegmentIdentifier identifier = tryAllocate(toolbox, task, tryInterval, rowInterval, false); if (identifier != null) { return identifier; } } } return null; } private SegmentIdentifier tryAllocateSubsequentSegment( TaskActionToolbox toolbox, Task task, Interval rowInterval, DataSegment usedSegment ) { // Existing segment(s) exist for this row; use the interval of the first one. if (!usedSegment.getInterval().contains(rowInterval)) { log.error("The interval of existing segment[%s] doesn't contain rowInterval[%s]", usedSegment, rowInterval); return null; } else { // If segment allocation failed here, it is highly likely an unrecoverable error. We log here for easier // debugging. return tryAllocate(toolbox, task, usedSegment.getInterval(), rowInterval, true); } } private SegmentIdentifier tryAllocate( TaskActionToolbox toolbox, Task task, Interval tryInterval, Interval rowInterval, boolean logOnFail ) { log.debug( "Trying to allocate pending segment for rowInterval[%s], segmentInterval[%s].", rowInterval, tryInterval ); final LockResult lockResult = toolbox.getTaskLockbox().tryLock(TaskLockType.EXCLUSIVE, task, tryInterval); if (lockResult.isRevoked()) { // We had acquired a lock but it was preempted by other locks throw new ISE("The lock for interval[%s] is preempted and no longer valid", tryInterval); } if (lockResult.isOk()) { final SegmentIdentifier identifier = toolbox.getIndexerMetadataStorageCoordinator().allocatePendingSegment( dataSource, sequenceName, previousSegmentId, tryInterval, lockResult.getTaskLock().getVersion(), skipSegmentLineageCheck ); if (identifier != null) { return identifier; } else { final String msg = StringUtils.format( "Could not allocate pending segment for rowInterval[%s], segmentInterval[%s].", rowInterval, tryInterval ); if (logOnFail) { log.error(msg); } else { log.debug(msg); } return null; } } else { final String msg = StringUtils.format( "Could not acquire lock for rowInterval[%s], segmentInterval[%s].", rowInterval, tryInterval ); if (logOnFail) { log.error(msg); } else { log.debug(msg); } return null; } } @Override public boolean isAudited() { return false; } @Override public String toString() { return "SegmentAllocateAction{" + "dataSource='" + dataSource + '\'' + ", timestamp=" + timestamp + ", queryGranularity=" + queryGranularity + ", preferredSegmentGranularity=" + preferredSegmentGranularity + ", sequenceName='" + sequenceName + '\'' + ", previousSegmentId='" + previousSegmentId + '\'' + ", skipSegmentLineageCheck='" + skipSegmentLineageCheck + '\'' + '}'; } }
package io.subutai.core.environment.impl.adapter; import java.util.HashSet; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.reflect.TypeToken; import io.subutai.common.command.CommandException; import io.subutai.common.command.RequestBuilder; import io.subutai.common.environment.ContainerHostNotFoundException; import io.subutai.common.environment.EnvironmentPeer; import io.subutai.common.environment.EnvironmentStatus; import io.subutai.common.environment.RhP2pIp; import io.subutai.common.exception.ActionFailedException; import io.subutai.common.host.ContainerHostInfo; import io.subutai.common.peer.EnvironmentContainerHost; import io.subutai.common.peer.Peer; import io.subutai.common.peer.PeerException; import io.subutai.common.security.SshKey; import io.subutai.common.security.SshKeys; import io.subutai.common.settings.Common; import io.subutai.common.util.P2PUtil; import io.subutai.common.util.ServiceLocator; import io.subutai.core.environment.impl.EnvironmentManagerImpl; import io.subutai.core.environment.impl.entity.EnvironmentContainerImpl; import io.subutai.core.environment.impl.entity.LocalEnvironment; import io.subutai.core.bazaarmanager.api.BazaarManager; import io.subutai.core.identity.api.IdentityManager; import io.subutai.core.peer.api.PeerManager; import io.subutai.bazaar.share.common.BazaaarAdapter; import io.subutai.bazaar.share.json.JsonUtil; public class EnvironmentAdapter { private final Logger log = LoggerFactory.getLogger( getClass() ); private final EnvironmentManagerImpl environmentManager; private final ProxyContainerHelper proxyContainerHelper; private final BazaaarAdapter bazaaarAdapter; private final IdentityManager identityManager; public EnvironmentAdapter( EnvironmentManagerImpl environmentManager, PeerManager peerManager, BazaaarAdapter bazaaarAdapter, IdentityManager identityManager ) { this.environmentManager = environmentManager; proxyContainerHelper = new ProxyContainerHelper( peerManager ); this.bazaaarAdapter = bazaaarAdapter; this.identityManager = identityManager; } public BazaaarAdapter getBazaaarAdapter() { return bazaaarAdapter; } public BazaarEnvironment get( String id ) { try { for ( BazaarEnvironment e : getEnvironments( identityManager.isTenantManager() ) ) { if ( e.getId().equals( id ) ) { return e; } } } catch ( ActionFailedException e ) { //ignore } catch ( Exception e ) { log.warn( e.getMessage() ); } return null; } /** * Returns bazaar environments for this peer. Throws {@code ActionFailedException} if requests tobazaar failed for some * reason * * @param all true: returns all environments, false: returns current user environments */ public Set<BazaarEnvironment> getEnvironments( boolean all ) { if ( !canWorkWithBazaar() ) { throw new ActionFailedException( "Peer is not registered with Bazaar or connection to Bazaar failed" ); } String json = all ? bazaaarAdapter.getAllEnvironmentsForPeer() : bazaaarAdapter.getUserEnvironmentsForPeer(); if ( json == null ) { throw new ActionFailedException( "Failed to obtain environments from Bazaar" ); } log.debug( "Json with environments: {}", json ); Set<BazaarEnvironment> envs = new HashSet<>(); try { ArrayNode arr = JsonUtil.fromJson( json, ArrayNode.class ); for ( int i = 0; i < arr.size(); i++ ) { envs.add( new BazaarEnvironment( this, arr.get( i ), environmentManager, proxyContainerHelper ) ); } } catch ( Exception e ) { log.error( "Failed to parse environments from Bazaar", e ); throw new ActionFailedException( "Failed to parse environments from Bazaar: " + e.getMessage() ); } return envs; } public Set<String> getDeletedEnvironmentsIds() { if ( !canWorkWithBazaar() ) { throw new ActionFailedException( "Peer is not registered with Bazaar or connection to Bazaar failed" ); } String json = bazaaarAdapter.getDeletedEnvironmentsForPeer(); if ( json == null ) { throw new ActionFailedException( "Failed to obtain deleted environments from Bazaar" ); } log.debug( "Json with deleted environments: {}", json ); try { return io.subutai.common.util.JsonUtil.fromJson( json, new TypeToken<Set<String>>() { }.getType() ); } catch ( Exception e ) { log.error( "Error to parse json: ", e ); throw new ActionFailedException( "Failed to parse deleted environments from Bazaar: " + e.getMessage() ); } } public void destroyContainer( BazaarEnvironment env, String containerId ) { if ( !canWorkWithBazaar() ) { return; } if ( env.getContainerHosts().size() == 1 ) { throw new IllegalStateException( "Environment will have 0 containers after modification. Please, destroy environment instead" ); } try { EnvironmentContainerHost ch = env.getContainerHostById( containerId ); ( ( EnvironmentContainerImpl ) ch ).destroy( false ); bazaaarAdapter.destroyContainer( env.getId(), containerId ); } catch ( Exception e ) { log.error( "Error to destroy container: ", e ); } } public boolean removeEnvironment( String envId ) { if ( !canWorkWithBazaar() ) { return false; } try { bazaaarAdapter.removeEnvironment( envId ); return true; } catch ( Exception e ) { log.error( "Error to remove environment: ", e ); } return false; } public boolean removeEnvironment( LocalEnvironment env ) { return removeEnvironment( env.getId() ); } public boolean canWorkWithBazaar() { return isBazaarReachable() && isRegisteredWithBazaar(); } public boolean isBazaarReachable() { BazaarManager bazaarManager = ServiceLocator.getServiceOrNull( BazaarManager.class ); return bazaarManager != null && bazaarManager.isBazaarReachable(); } public boolean isRegisteredWithBazaar() { BazaarManager bazaarManager = ServiceLocator.getServiceOrNull( BazaarManager.class ); return bazaarManager != null && bazaarManager.isRegisteredWithBazaar(); } public boolean uploadEnvironment( LocalEnvironment env ) { if ( !canWorkWithBazaar() ) { return false; } if ( env.getStatus() != EnvironmentStatus.HEALTHY ) { return false; } try { ObjectNode envJson = environmentToJson( env ); environmentPeersToJson( env, envJson ); environmentContainersToJson( env, envJson ); bazaaarAdapter.uploadEnvironment( envJson.toString() ); return true; } catch ( Exception e ) { log.debug( "Error to post local environment to Bazaar: ", e ); return false; } } public boolean uploadPeerOwnerEnvironment( LocalEnvironment env ) { if ( !canWorkWithBazaar() ) { return false; } if ( env.getStatus() != EnvironmentStatus.HEALTHY ) { return false; } try { ObjectNode envJson = environmentToJson( env ); environmentPeersToJson( env, envJson ); environmentContainersToJson( env, envJson ); return bazaaarAdapter.uploadPeerOwnerEnvironment( envJson.toString() ); } catch ( Exception e ) { log.debug( "Error to post local environment to Bazaar: ", e ); } return false; } public void removeSshKey( String envId, String sshKey ) { if ( !canWorkWithBazaar() ) { return; } bazaaarAdapter.removeSshKey( envId, sshKey ); } public void addSshKey( String envId, String sshKey ) { if ( !canWorkWithBazaar() ) { return; } bazaaarAdapter.addSshKey( envId, sshKey ); } private void environmentContainersToJson( LocalEnvironment env, ObjectNode json ) throws PeerException { ArrayNode contNode = json.putArray( "containers" ); for ( EnvironmentContainerHost ch : env.getContainerHosts() ) { ObjectNode peerJson = JsonUtil.createNode( "id", ch.getId() ); peerJson.put( "name", ch.getContainerName() ); peerJson.put( "hostname", ch.getHostname() ); peerJson.put( "containerName", ch.getContainerName() ); peerJson.put( "state", ch.getState().toString() ); peerJson.put( "template", ch.getTemplateName() ); peerJson.put( "size", ch.getContainerSize().toString() ); peerJson.put( "peerId", ch.getPeer().getId() ); peerJson.put( "rhId", ch.getResourceHostId().getId() ); String ip = ch.getIp(); peerJson.put( "ip", ip ); ArrayNode sshKeys = peerJson.putArray( "sshkeys" ); SshKeys chSshKeys = ch.getAuthorizedKeys(); for ( SshKey sshKey : chSshKeys.getKeys() ) { sshKeys.add( sshKey.getPublicKey() ); } contNode.add( peerJson ); } } private ObjectNode environmentToJson( LocalEnvironment env ) { ObjectNode json = JsonUtil.createNode( "id", env.getEnvironmentId().getId() ); json.put( "name", env.getName() ); json.put( "status", env.getStatus().toString() ); json.put( "p2pHash", P2PUtil.generateHash( env.getEnvironmentId().getId() ) ); json.put( "p2pTtl", Common.DEFAULT_P2P_SECRET_KEY_TTL_SEC ); json.put( "p2pKey", env.getP2pKey() ); json.put( "vni", env.getVni() ); return json; } private void environmentPeersToJson( LocalEnvironment env, ObjectNode json ) throws PeerException { ArrayNode peers = json.putArray( "peers" ); for ( Peer peer : env.getPeers() ) { ObjectNode peerJson = JsonUtil.createNode( "id", peer.getId() ); peerJson.put( "online", peer.isOnline() ); putPeerResourceHostsJson( peerJson, env.getEnvironmentPeer( peer.getId() ) ); peers.add( peerJson ); } } private void putPeerResourceHostsJson( ObjectNode peerJson, EnvironmentPeer environmentPeer ) { ArrayNode rhs = peerJson.putArray( "resourceHosts" ); for ( RhP2pIp rh : environmentPeer.getRhP2pIps() ) { ObjectNode rhJson = JsonUtil.createNode( "id", rh.getRhId() ); rhJson.put( "p2pIp", rh.getP2pIp() ); rhs.add( rhJson ); } } public void handleHostnameChange( final ContainerHostInfo containerInfo, final String previousHostname, final String currentHostname ) { BazaarEnvironment environment = null; for ( BazaarEnvironment bazaarEnvironment : getEnvironments( true ) ) { try { bazaarEnvironment.getContainerHostById( containerInfo.getId() ); environment = bazaarEnvironment; break; } catch ( ContainerHostNotFoundException e ) { //ignore } } if ( environment == null ) { return; } for ( EnvironmentContainerHost containerHost : environment.getContainerHosts() ) { try { containerHost.execute( getChangeHostnameInEtcHostsCommand( previousHostname, currentHostname ) ); } catch ( CommandException e ) { log.warn( "Error updating /etc/hosts file on container {} with container hostname change: [{}] -> [{}]", containerHost.getHostname(), previousHostname, currentHostname ); } } } private RequestBuilder getChangeHostnameInEtcHostsCommand( String oldHostname, String newHostname ) { return new RequestBuilder( String.format( "sed -i 's/\\b%1$s\\b/%2$s/g' %4$s && sed -i 's/\\b%1$s.%3$s\\b/%2$s.%3$s/g' %4$s", oldHostname, newHostname, Common.DEFAULT_DOMAIN_NAME, Common.ETC_HOSTS_FILE ) ); } }
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.introduce.inplace; import com.intellij.codeInsight.highlighting.HighlightManager; import com.intellij.codeInsight.template.TextResult; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.command.impl.StartMarkAction; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.ReadonlyStatusHandler; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.listeners.RefactoringEventData; import com.intellij.refactoring.listeners.RefactoringEventListener; import com.intellij.refactoring.rename.inplace.InplaceRefactoring; import com.intellij.util.ui.PositionTracker; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.util.*; import java.util.List; public abstract class AbstractInplaceIntroducer<V extends PsiNameIdentifierOwner, E extends PsiElement> extends InplaceVariableIntroducer<E> { protected V myLocalVariable; protected RangeMarker myLocalMarker; protected final String myExprText; private final String myLocalName; public static final Key<AbstractInplaceIntroducer> ACTIVE_INTRODUCE = Key.create("ACTIVE_INTRODUCE"); private EditorEx myPreview; private final JComponent myPreviewComponent; private DocumentListener myDocumentAdapter; protected final JPanel myWholePanel; protected boolean myFinished = false; public AbstractInplaceIntroducer(Project project, Editor editor, @Nullable E expr, @Nullable V localVariable, E[] occurrences, String title, final FileType languageFileType) { super(null, editor, project, title, occurrences, expr); myLocalVariable = localVariable; if (localVariable != null) { final PsiElement nameIdentifier = localVariable.getNameIdentifier(); if (nameIdentifier != null) { myLocalMarker = createMarker(nameIdentifier); } } else { myLocalMarker = null; } myExprText = getExpressionText(expr); myLocalName = localVariable != null ? localVariable.getName() : null; myPreview = createPreviewComponent(project, languageFileType); myPreviewComponent = new JPanel(new BorderLayout()); myPreviewComponent.add(myPreview.getComponent(), BorderLayout.CENTER); myPreviewComponent.setBorder(new EmptyBorder(2, 2, 6, 2)); myWholePanel = new JPanel(new GridBagLayout()); myWholePanel.setBorder(null); showDialogAdvertisement(getActionName()); } @Nullable protected String getExpressionText(E expr) { return expr != null ? expr.getText() : null; } protected final void setPreviewText(final String text) { if (myPreview == null) return; //already disposed ApplicationManager.getApplication().runWriteAction(() -> myPreview.getDocument().replaceString(0, myPreview.getDocument().getTextLength(), text)); } protected final JComponent getPreviewComponent() { return myPreviewComponent; } protected final Editor getPreviewEditor() { return myPreview; } @Override protected StartMarkAction startRename() throws StartMarkAction.AlreadyStartedException { return StartMarkAction.start(myEditor, myProject, getCommandName()); } /** * Returns ID of the action the shortcut of which is used to show the non-in-place refactoring dialog. * * @return action ID */ protected abstract String getActionName(); /** * Creates an initial version of the declaration for the introduced element. Note that this method is not called in a write action * and most likely needs to create one itself. * * @param replaceAll whether all occurrences are going to be replaced * @param names the suggested names for the declaration * @return the declaration */ @Nullable protected abstract V createFieldToStartTemplateOn(boolean replaceAll, @NotNull String[] names); /** * Returns the suggested names for the introduced element. * * @param replaceAll whether all occurrences are going to be replaced * @param variable introduced element declaration, if already created. * @return the suggested names */ @NotNull protected abstract String[] suggestNames(boolean replaceAll, @Nullable V variable); protected abstract void performIntroduce(); protected void performPostIntroduceTasks() {} public abstract boolean isReplaceAllOccurrences(); public abstract void setReplaceAllOccurrences(boolean allOccurrences); @Override @Nullable protected abstract JComponent getComponent(); protected abstract void saveSettings(@NotNull V variable); @Override @Nullable protected abstract V getVariable(); public abstract E restoreExpression(@NotNull PsiFile containingFile, @NotNull V variable, @NotNull RangeMarker marker, @Nullable String exprText); /** * Begins the in-place refactoring operation. * * @return true if the in-place refactoring was successfully started, false if it failed to start and a dialog should be shown instead. */ public boolean startInplaceIntroduceTemplate() { final boolean replaceAllOccurrences = isReplaceAllOccurrences(); final Ref<Boolean> result = new Ref<>(); CommandProcessor.getInstance().executeCommand(myProject, () -> { final String[] names = suggestNames(replaceAllOccurrences, getLocalVariable()); final V variable = createFieldToStartTemplateOn(replaceAllOccurrences, names); boolean started = false; if (variable != null) { int caretOffset = getCaretOffset(); myEditor.getCaretModel().moveToOffset(caretOffset); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); final LinkedHashSet<String> nameSuggestions = new LinkedHashSet<>(); nameSuggestions.add(variable.getName()); nameSuggestions.addAll(Arrays.asList(names)); initOccurrencesMarkers(); setElementToRename(variable); updateTitle(getVariable()); started = super.performInplaceRefactoring(nameSuggestions); if (started) { myDocumentAdapter = new DocumentListener() { @Override public void documentChanged(DocumentEvent e) { if (myPreview == null) return; final TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); if (templateState != null) { final TextResult value = templateState.getVariableValue(InplaceRefactoring.PRIMARY_VARIABLE_NAME); if (value != null) { updateTitle(getVariable(), value.getText()); } } } }; myEditor.getDocument().addDocumentListener(myDocumentAdapter); updateTitle(getVariable()); if (TemplateManagerImpl.getTemplateState(myEditor) != null) { myEditor.putUserData(ACTIVE_INTRODUCE, this); } } } result.set(started); if (!started) { finish(true); } }, getCommandName(), getCommandName()); return result.get(); } protected int getCaretOffset() { RangeMarker r; if (myLocalMarker != null) { final PsiReference reference = myExpr != null ? myExpr.getReference() : null; if (reference != null && reference.resolve() == myLocalVariable) { r = myExprMarker; } else { r = myLocalMarker; } } else { r = myExprMarker; } return r != null ? r.getStartOffset() : 0; } protected void updateTitle(@Nullable V variable, String value) { if (variable == null) return; final String variableText = variable.getText(); final PsiElement identifier = variable.getNameIdentifier(); if (identifier != null) { final int startOffsetInParent = identifier.getStartOffsetInParent(); setPreviewText(variableText.substring(0, startOffsetInParent) + value + variableText.substring(startOffsetInParent + identifier.getTextLength())); } else { setPreviewText(variableText.replaceFirst(variable.getName(), value)); } revalidate(); } protected void updateTitle(@Nullable V variable) { if (variable == null) return; setPreviewText(variable.getText()); revalidate(); } protected void revalidate() { myWholePanel.revalidate(); if (myTarget != null) { myBalloon.revalidate(new PositionTracker.Static<>(myTarget)); } } private boolean myShouldSelect = true; @Override protected boolean shouldSelectAll() { return myShouldSelect; } public void restartInplaceIntroduceTemplate() { Runnable restartTemplateRunnable = () -> { final TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); if (templateState != null) { myEditor.putUserData(INTRODUCE_RESTART, true); try { final TextRange range = templateState.getCurrentVariableRange(); if (range != null) { final TextResult inputText = templateState.getVariableValue(PRIMARY_VARIABLE_NAME); final String inputName = inputText != null ? inputText.getText() : null; final V variable = getVariable(); if (inputName == null || variable == null || !isIdentifier(inputName, variable.getLanguage())) { final String[] names = suggestNames(isReplaceAllOccurrences(), getLocalVariable()); ApplicationManager.getApplication().runWriteAction(() -> myEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), names[0])); } } templateState.gotoEnd(true); try { myShouldSelect = false; startInplaceIntroduceTemplate(); } finally { myShouldSelect = true; } } finally { myEditor.putUserData(INTRODUCE_RESTART, false); } } updateTitle(getVariable()); }; CommandProcessor.getInstance().executeCommand(myProject, restartTemplateRunnable, getCommandName(), getCommandName()); } @Override protected void restoreSelection() { if (!shouldSelectAll()) { myEditor.getSelectionModel().removeSelection(); } } public String getInputName() { return myInsertedName; } @Override public void finish(boolean success) { myFinished = true; myEditor.putUserData(ACTIVE_INTRODUCE, null); if (myDocumentAdapter != null) { myEditor.getDocument().removeDocumentListener(myDocumentAdapter); } if (myBalloon == null) { releaseIfNotRestart(); } super.finish(success); if (success) { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); final V variable = getVariable(); if (variable == null) { return; } restoreState(variable); } } @Override protected void releaseResources() { super.releaseResources(); if (myPreview == null) return; EditorFactory.getInstance().releaseEditor(myPreview); myPreview = null; } @Override protected void addReferenceAtCaret(Collection<PsiReference> refs) { final V variable = getLocalVariable(); if (variable != null) { for (PsiReference reference : ReferencesSearch.search(variable)) { refs.add(reference); } } else { refs.clear(); } } @Override protected void collectAdditionalElementsToRename(@NotNull List<Pair<PsiElement, TextRange>> stringUsages) { if (isReplaceAllOccurrences()) { for (E expression : getOccurrences()) { PsiUtilCore.ensureValid(expression); stringUsages.add(Pair.create(expression, new TextRange(0, expression.getTextLength()))); } } else if (getExpr() != null) { correctExpression(); final E expr = getExpr(); PsiUtilCore.ensureValid(expr); stringUsages.add(Pair.create(expr, new TextRange(0, expr.getTextLength()))); } final V localVariable = getLocalVariable(); if (localVariable != null) { final PsiElement nameIdentifier = localVariable.getNameIdentifier(); if (nameIdentifier != null) { int length = nameIdentifier.getTextLength(); stringUsages.add(Pair.create(nameIdentifier, new TextRange(0, length))); } } } protected void correctExpression() {} @Override protected void addHighlights(@NotNull Map<TextRange, TextAttributes> ranges, @NotNull Editor editor, @NotNull Collection<RangeHighlighter> highlighters, @NotNull HighlightManager highlightManager) { final TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); final V variable = getVariable(); if (variable != null) { final String name = variable.getName(); LOG.assertTrue(name != null, variable); final int variableNameLength = name.length(); if (isReplaceAllOccurrences()) { for (RangeMarker marker : getOccurrenceMarkers()) { final int startOffset = marker.getStartOffset(); highlightManager.addOccurrenceHighlight(editor, startOffset, startOffset + variableNameLength, attributes, 0, highlighters, null); } } else if (getExpr() != null) { final int startOffset = getExprMarker().getStartOffset(); highlightManager.addOccurrenceHighlight(editor, startOffset, startOffset + variableNameLength, attributes, 0, highlighters, null); } } for (RangeHighlighter highlighter : highlighters) { highlighter.setGreedyToLeft(true); highlighter.setGreedyToRight(true); } } protected void restoreState(@NotNull final V psiField) { if (!ReadonlyStatusHandler.ensureDocumentWritable(myProject, InjectedLanguageUtil.getTopLevelEditor(myEditor).getDocument())) return; ApplicationManager.getApplication().runWriteAction(() -> { final PsiFile containingFile = psiField.getContainingFile(); final RangeMarker exprMarker = getExprMarker(); if (exprMarker != null) { myExpr = restoreExpression(containingFile, psiField, exprMarker, myExprText); } if (myLocalMarker != null) { final PsiElement refVariableElement = containingFile.findElementAt(myLocalMarker.getStartOffset()); if (refVariableElement != null) { final PsiElement parent = refVariableElement.getParent(); if (parent instanceof PsiNamedElement) { ((PsiNamedElement)parent).setName(myLocalName); } } final V localVariable = getLocalVariable(); if (localVariable != null && localVariable.isPhysical()) { myLocalVariable = localVariable; final PsiElement nameIdentifier = localVariable.getNameIdentifier(); if (nameIdentifier != null) { myLocalMarker = createMarker(nameIdentifier); } } } final List<RangeMarker> occurrenceMarkers = getOccurrenceMarkers(); for (int i = 0; i < occurrenceMarkers.size(); i++) { RangeMarker marker = occurrenceMarkers.get(i); if (getExprMarker() != null && marker.getStartOffset() == getExprMarker().getStartOffset() && myExpr != null) { myOccurrences[i] = myExpr; continue; } final E psiExpression = restoreExpression(containingFile, psiField, marker, getLocalVariable() != null ? myLocalName : myExprText); if (psiExpression != null) { myOccurrences[i] = psiExpression; } } if (myExpr != null && myExpr.isPhysical()) { myExprMarker = createMarker(myExpr); } myOccurrenceMarkers = null; deleteTemplateField(psiField); }); } protected void deleteTemplateField(V psiField) { if (psiField.isValid()) { psiField.delete(); } } @Override protected boolean performRefactoring() { if (!ensureValid()) return false; CommandProcessor.getInstance().executeCommand(myProject, () -> { final String refactoringId = getRefactoringId(); if (refactoringId != null) { final RefactoringEventData beforeData = new RefactoringEventData(); final V localVariable = getLocalVariable(); if (localVariable != null) { beforeData.addElement(localVariable); } else { final E beforeExpr = getBeforeExpr(); if (beforeExpr != null) { beforeData.addElement(beforeExpr); } } myProject.getMessageBus() .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, beforeData); } performIntroduce(); }, getCommandName(), getCommandName()); V variable = getVariable(); if (variable != null) { saveSettings(variable); } return false; } protected E getBeforeExpr() { return getExpr(); } protected boolean ensureValid() { final String newName = getInputName(); if (getLocalVariable() == null && myExpr == null || newName == null || getLocalVariable() != null && !getLocalVariable().isValid() || myExpr != null && !myExpr.isValid()) { super.moveOffsetAfter(false); return false; } if (getLocalVariable() != null) { WriteCommandAction.writeCommandAction(myProject).withName(getCommandName()).withGroupId(getCommandName()).run(() -> { getLocalVariable().setName(myLocalName); }); } if (!isIdentifier(newName, myExpr != null ? myExpr.getLanguage() : getLocalVariable().getLanguage())) return false; return true; } @Override protected void moveOffsetAfter(boolean success) { if (getLocalVariable() != null && getLocalVariable().isValid()) { myEditor.getCaretModel().moveToOffset(getLocalVariable().getTextOffset()); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); } else if (getExprMarker() != null) { final RangeMarker exprMarker = getExprMarker(); if (exprMarker.isValid()) { myEditor.getCaretModel().moveToOffset(exprMarker.getStartOffset()); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); } } super.moveOffsetAfter(success); if (myLocalMarker != null && !isRestart()) { myLocalMarker.dispose(); } if (success) { performPostIntroduceTasks(); final String refactoringId = getRefactoringId(); if (refactoringId != null) { final RefactoringEventData afterData = new RefactoringEventData(); afterData.addElement(getVariable()); myProject.getMessageBus() .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(refactoringId, afterData); } } } protected String getRefactoringId() { return null; } @Override protected boolean startsOnTheSameElement(RefactoringActionHandler handler, PsiElement element) { return super.startsOnTheSameElement(handler, element) || getLocalVariable() == element; } public V getLocalVariable() { if (myLocalVariable != null && myLocalVariable.isValid()) { return myLocalVariable; } if (myLocalMarker != null) { V variable = getVariable(); PsiFile containingFile; if (variable != null) { containingFile = variable.getContainingFile(); } else { containingFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument()); } PsiNameIdentifierOwner identifierOwner = PsiTreeUtil.getParentOfType(containingFile.findElementAt(myLocalMarker.getStartOffset()), PsiNameIdentifierOwner.class, false); return identifierOwner != null && identifierOwner.getClass() == myLocalVariable.getClass() ? (V)identifierOwner : null; } return myLocalVariable; } public void stopIntroduce(Editor editor) { final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); if (templateState != null) { final Runnable runnable = () -> templateState.gotoEnd(true); CommandProcessor.getInstance().executeCommand(myProject, runnable, getCommandName(), getCommandName()); } } @Override protected void navigateToAlreadyStarted(Document oldDocument, int exitCode) { finish(true); super.navigateToAlreadyStarted(oldDocument, exitCode); } @Override protected void showBalloon() { if (myFinished) return; super.showBalloon(); } public boolean startsOnTheSameElement(E expr, V localVariable) { if (myExprMarker != null && myExprMarker.isValid() && expr != null && myExprMarker.getStartOffset() == expr.getTextOffset()) { return true; } if (myLocalMarker != null && myLocalMarker.isValid() && localVariable != null && myLocalMarker.getStartOffset() == localVariable.getTextOffset()) { return true; } return isRestart(); } @Nullable public static AbstractInplaceIntroducer getActiveIntroducer(@Nullable Editor editor) { if (editor == null) return null; return editor.getUserData(ACTIVE_INTRODUCE); } }
package com.github.zarena; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.logging.Level; import com.github.zarena.utils.ConfigEnum; import org.bukkit.Material; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.inventory.ItemStack; import com.github.zarena.entities.ZEntityType; import com.github.zarena.signs.ZSignCustomItem; import com.github.zarena.utils.Constants; import com.github.zarena.utils.Utils; public class Gamemode { private String name; private int initWave; private boolean isApocalypse; private boolean isScavenger; private boolean isNoRegen; private boolean isSlowRegen; private double weight; private double healthModifier; private double damageModifier; private double zombieAmountModifier; private double difficultyModifier; private List<ZEntityType> defaultZombies = new ArrayList<ZEntityType>(); private List<ZEntityType> defaultWolves = new ArrayList<ZEntityType>(); private List<ZEntityType> defaultSkeletons = new ArrayList<ZEntityType>(); private List<ItemStack> startItems = new ArrayList<ItemStack>(); private Map<String, Double> allowedEntityModifiers = new HashMap<String, Double>(); private Map<String, Double> itemCostModifiers = new HashMap<String, Double>(); public Gamemode(FileConfiguration config) { name = config.getString("Name", "Normal"); initWave = config.getInt("Initial Wave", 1); isApocalypse = config.getBoolean("Apocalypse", false); isScavenger = config.getBoolean("Scavenger", false); isNoRegen = config.getBoolean("No Regen", false); isSlowRegen = config.getBoolean("Slow Regen", false); weight = config.getDouble("Gamemode Choice Weight", 1); healthModifier = config.getDouble("Health Modifier", 1); damageModifier = config.getDouble("Damage Modifier", 1); zombieAmountModifier = config.getDouble("Zombie Amount Modifier", 1); difficultyModifier = config.getDouble("Difficulty Modifier", 1); List<String> defaultsNames = new ArrayList<String>(); if(config.contains("Default Zombie")) defaultsNames = config.getStringList("Default Zombie"); if(defaultsNames.isEmpty()) defaultsNames.add(config.getString("Default Zombie", ZArena.getInstance().getConfig().getString(ConfigEnum.DEFAULT_ZOMBIE.toString()))); defaultZombies.addAll(handleConversion(defaultsNames)); if(config.contains("Default Wolf")) defaultsNames = config.getStringList("Default Wolf"); if(defaultsNames.isEmpty()) defaultsNames.add(config.getString("Default Wolf", ZArena.getInstance().getConfig().getString(ConfigEnum.DEFAULT_WOLF.toString()))); defaultWolves.addAll(handleConversion(defaultsNames)); if(config.contains("Default Skeleton")) defaultsNames = config.getStringList("Default Skeleton"); if(defaultsNames.isEmpty()) defaultsNames.add(config.getString("Default Skeleton", ZArena.getInstance().getConfig().getString(ConfigEnum.DEFAULT_SKELETON.toString()))); defaultSkeletons.addAll(handleConversion(defaultsNames)); if(config.getStringList("Start Items") != null) { for(String arg : config.getStringList("Start Items")) { //If the second argument isn't an integer, we can assume it's part of the item if(arg.split("\\s").length > 1 && Utils.parseInt(arg.split("\\s")[1], -1) == -1) arg = arg.replaceFirst(" ", "_"); int amount = 1; if(Utils.getConfigArgs(arg).length > 0) amount = Utils.parseInt(Utils.getConfigArgs(arg)[0], 1); ZSignCustomItem customItem = ZSignCustomItem.getCustomItem(arg.split("\\s")); if(customItem != null) { ItemStack item = customItem.getItem(); if(amount != 1) item.setAmount(amount); startItems.add(item); continue; } Material material = Material.matchMaterial(arg.split("\\s")[0]); if(material != null) { ItemStack item = new ItemStack(material); if(amount != 1) item.setAmount(amount); startItems.add(item); } } } if(config.getStringList("Allowed Entities") != null) { for(String arg : config.getStringList("Allowed Entities")) { double spawnChanceMod = 1; String[] args = Utils.getConfigArgs(arg); if(args.length > 0) spawnChanceMod = Utils.parseDouble(args[0], 1); allowedEntityModifiers.put(arg.split("\\s")[0].toLowerCase().split(".")[0], spawnChanceMod); } } if(allowedEntityModifiers.isEmpty()) allowedEntityModifiers.put("ALL", 1.0); if(config.getStringList("Allowed Items") != null) { for(String arg : config.getStringList("Allowed Items")) { if(arg.split("\\s").length > 1 && Utils.parseInt(arg.split("\\s")[1], -1) < 0) //If the second argument isn't an integer, we can assume it's part of the item arg = arg.replaceFirst(" ", "_"); double costMod = 1; String[] args = Utils.getConfigArgs(arg); if(args.length > 0) costMod = Utils.parseDouble(args[0], 1); itemCostModifiers.put(arg.split("\\s")[0].toUpperCase(), costMod); } } if(itemCostModifiers.isEmpty()) itemCostModifiers.put("ALL", 1.0); } public boolean canBuyItem(String item) { if(itemCostModifiers.containsKey("ALL")) return true; if(itemCostModifiers.containsKey("NONE")) return false; return itemCostModifiers.containsKey(item.toUpperCase().replaceAll(" ", "_")); } public boolean canSpawn(String entity) { if(allowedEntityModifiers.containsKey("ALL")) return true; return allowedEntityModifiers.containsKey(entity.toLowerCase().split(".")[0]); } public double getChoiceWeight() { return weight; } public Double getCostModifier(String item) { if(!canBuyItem(item)) //Generally shouldn't ever be true return null; if(itemCostModifiers.get(item.toUpperCase().replaceAll(" ", "_")) != null) return itemCostModifiers.get(item.toUpperCase().replaceAll(" ", "_")); return itemCostModifiers.get("ALL"); } public double getDamageModifier() { return damageModifier; } public List<ZEntityType> getDefaultSkeletons() { return defaultSkeletons; } public List<ZEntityType> getDefaultWolves() { return defaultWolves; } public List<ZEntityType> getDefaultZombies() { return defaultZombies; } public double getDifficultyModifier() { return difficultyModifier; } public double getHealthModifier() { return healthModifier; } public String getName() { return name; } public double getSpawnChanceModifier(String entity) { if(!(canSpawn(entity))) //Generally shouldn't ever be true return 0; return allowedEntityModifiers.get(entity.toLowerCase().split(".")[0]); } public List<ItemStack> getStartItems() { return startItems; } public double getZombieAmountModifier() { return zombieAmountModifier; } public boolean isApocalypse() { return isApocalypse; } public boolean isNoRegen() { return isNoRegen; } public boolean isScavenger() { return isScavenger; } public boolean isSlowRegen() { return isSlowRegen; } public int getInitialWave() { return initWave; } @Override public String toString() { return name; } private ZEntityType convertToEntityType(String typeName) { WaveHandler waveHandler = ZArena.getInstance().getGameHandler().getWaveHandler(); for(ZEntityType type : waveHandler.getAllEntityTypes()) { if(type.getName().replaceAll(" ", "").equalsIgnoreCase(typeName)) return type; } return null; } private List<ZEntityType> handleConversion(List<String> typeNames) { List<ZEntityType> types = new ArrayList<ZEntityType>(); for(String name : typeNames) { ZEntityType type = convertToEntityType(name.replaceAll(".yml", "").replaceAll(" ", "")); if(type != null) types.add(type); else ZArena.log(Level.WARNING, "Entity type, "+name+", specified in the configuration of the gamemode, "+this.name+", could not be found."); } typeNames.clear(); return types; } public static Gamemode getGamemode(String name) { Gamemode defaultGm = ZArena.getInstance().getGameHandler().defaultGamemode; if(defaultGm.getName().replaceAll(" ", "").equalsIgnoreCase(name.replaceAll("_", ""))) return defaultGm; for(Gamemode gm : ZArena.getInstance().getGameHandler().gamemodes) { if(gm.getName().replaceAll(" ", "").equalsIgnoreCase(name.replaceAll("_", ""))) return gm; } return null; } public static Gamemode getRandomGamemode() { return getRandomGamemode(new ArrayList<Gamemode>()); } public static Gamemode getRandomGamemode(Gamemode exclude) { List<Gamemode> excludes = new ArrayList<Gamemode>(); excludes.add(exclude); return getRandomGamemode(excludes); } public static Gamemode getRandomGamemode(List<Gamemode> excludes) { int totalWeight = 0; for(Gamemode gm : ZArena.getInstance().getGameHandler().gamemodes) totalWeight += (int) (gm.weight * 10); Gamemode[] weightedGameModes = new Gamemode[totalWeight]; for(Gamemode gm : ZArena.getInstance().getGameHandler().gamemodes) { for(int weight = (int) (gm.weight * 10); weight > 0; weight--) { weightedGameModes[totalWeight - 1] = gm; totalWeight--; } } if(excludes.containsAll(ZArena.getInstance().getGameHandler().gamemodes)) return weightedGameModes[new Random().nextInt(weightedGameModes.length)]; Gamemode gamemode; do { gamemode = weightedGameModes[new Random().nextInt(weightedGameModes.length)]; } while(excludes.contains(gamemode)); return gamemode; } }
package com.beef.dataorigin.generator; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.log4j.Logger; import com.beef.dataorigin.context.DataOriginDirManager; import com.beef.dataorigin.generator.DataOriginGenerator.DataOriginGenerateTaskType; import com.beef.dataorigin.generator.util.DataOriginGeneratorUtil; import com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException; import com.salama.modeldriven.util.db.DBTable; import com.salama.modeldriven.util.db.mysql.MysqlTableInfoUtil; import com.salama.util.ResourceUtil; public class DataOriginGeneratorContext { private final static Logger logger = Logger.getLogger(DataOriginGeneratorContext.class); public final static String DefaultCharsetName = "utf-8"; public final static Charset DefaultCharset = Charset.forName(DefaultCharsetName); public final static String DIR_DATA_ORIGIN_BASE = "webapp/WEB-INF/data-origin"; public final static String DIR_JAVA_SRC = "src"; public final static String JAVA_SUB_PACKAGE_DATA_DB = "data.db"; public final static String JAVA_SUB_PACKAGE_SERVICE = "service"; public final static String JAVA_SUB_PACKAGE_DAO = "dao"; public final static String PROP_KEY_DATA_ORIGIN_TEMPLATE_DIR = "data-origin.generate.template.dir"; public final static String PROP_KEY_DATA_ORIGIN_OUTPUT_WEB_PROJECT_DIR = "data-origin.generate.output.web.project.dir"; public final static String PROP_KEY_DATA_ORIGIN_OUTPUT_WEB_PROJECT_JAVA_PACKAGE = "data-origin.generate.output.web.project.java.package"; public final static String PROP_KEY_DATA_ORIGIN_OUTPUT_WEB_CONTEXT_NAME = "data-origin.generate.output.web.contextname"; public final static String PROP_KEY_DB_DRIVER = "db.driver"; public final static String PROP_KEY_PRODUCTION_DB_URL = "production.db.url"; public final static String PROP_KEY_PRODUCTION_DB_USER = "production.db.user"; public final static String PROP_KEY_PRODUCTION_DB_PASSWORD = "production.db.password"; public final static String PROP_KEY_ONEDITING_DB_URL = "onediting.db.url"; public final static String PROP_KEY_ONEDITING_DB_USER = "onediting.db.user"; public final static String PROP_KEY_ONEDITING_DB_PASSWORD = "onediting.db.password"; private List<String> _dbTableNameList = null; private List<DBTable> _dbTableList = new ArrayList<DBTable>(); private DataOriginDirManager _dataOriginDirManager = null; private File _templateDir; private File _outputWebProjectDir; private File _outputWebProjectJavaSrcDir; private String _outputWebProjectJavaPackage; private String _outputWebContextName; //private HashSet<String> _builtInTableNameSet = new HashSet<String>(); private Properties _dataOriginProperties = null; public DataOriginGeneratorContext(DataOriginGenerateTaskType taskType) throws ClassNotFoundException, SQLException, IOException { _dataOriginProperties = ResourceUtil.getProperties("/data-origin-generator.properties"); makeBaseDir(); initDBTables(); if(taskType == DataOriginGenerateTaskType.GenerateMeta) { initBuiltinDBTables(); } } protected void makeBaseDir() { _templateDir = new File(getValueByPropertyKey(PROP_KEY_DATA_ORIGIN_TEMPLATE_DIR)); _outputWebProjectDir = new File(getValueByPropertyKey(PROP_KEY_DATA_ORIGIN_OUTPUT_WEB_PROJECT_DIR)); _outputWebProjectJavaSrcDir = new File(_outputWebProjectDir, DIR_JAVA_SRC); _outputWebProjectJavaPackage = getValueByPropertyKey(PROP_KEY_DATA_ORIGIN_OUTPUT_WEB_PROJECT_JAVA_PACKAGE); _outputWebContextName = getValueByPropertyKey(PROP_KEY_DATA_ORIGIN_OUTPUT_WEB_CONTEXT_NAME); File baseDir = new File(_outputWebProjectDir, DIR_DATA_ORIGIN_BASE); if(!baseDir.exists()) { baseDir.mkdirs(); } _dataOriginDirManager = new DataOriginDirManager(baseDir); } protected void initBuiltinDBTables() throws IOException { Connection conn = null; try { //create builtin tables ----------------------------------------------------- //read sql of create table InputStream sqlSourceInput = DataOriginGenerator.class.getResourceAsStream("/data-origin-db.sql"); ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(); DataOriginGeneratorUtil.copy(sqlSourceInput, bytesOutput); String sqlSource = bytesOutput.toString(DataOriginGeneratorContext.DefaultCharsetName); //split to array of create table sql String[] createTableSqlArray = sqlSource.split("(;[ \t\r]*[\n]+)"); //DB operation conn = createConnectionOfOnEditingDB(); PreparedStatement stmt = null; for(int i = 0; i < createTableSqlArray.length; i++) { try { stmt = conn.prepareStatement(createTableSqlArray[i]); stmt.executeUpdate(); } catch(Exception e) { if((e.getClass() == MySQLSyntaxErrorException.class && ((MySQLSyntaxErrorException)e).getSQLState().equals("42S01") ) || (e.getClass() == com.mysql.jdbc.exceptions.MySQLSyntaxErrorException.class && ((com.mysql.jdbc.exceptions.MySQLSyntaxErrorException)e).getSQLState().equals("42S01") ) ) { //table exists logger.info("initBuiltinDBTables() table exists:\n" + createTableSqlArray[i]); } else { throw e; } } finally { try { stmt.close(); } catch(Throwable e) { } } } //add dbTable into list ----------------------------------------------- addDBTableByTableName(conn, "DOAdmin"); addDBTableByTableName(conn, "DOUploadFileMeta"); addDBTableByTableName(conn, "DODataModificationCommitTask"); addDBTableByTableName(conn, "DODataModificationCommitTaskBundle"); } catch(Throwable e) { e.printStackTrace(); } finally { try { conn.close(); } catch(Throwable e) { } } } private void addDBTableByTableName(Connection conn, String dbTableName) throws SQLException { _dbTableNameList.add(dbTableName); DBTable dbTable = MysqlTableInfoUtil.GetTable(conn, dbTableName); _dbTableList.add(dbTable); } protected void initDBTables() throws ClassNotFoundException, SQLException { Connection conn = null; try { conn = createConnectionOfProductionDB(); _dbTableNameList = MysqlTableInfoUtil.getAllTables(conn); //output db tables xml String dbTableName = null; DBTable dbTable = null; for(int i = 0; i < _dbTableNameList.size(); i++) { dbTableName = _dbTableNameList.get(i); dbTable = MysqlTableInfoUtil.GetTable(conn, dbTableName); _dbTableList.add(dbTable); } } finally { try { conn.close(); } catch(Throwable e) { } } } public Connection createConnectionOfProductionDB() throws ClassNotFoundException, SQLException { return createConnection( getValueByPropertyKey(PROP_KEY_DB_DRIVER), getValueByPropertyKey(PROP_KEY_PRODUCTION_DB_URL), getValueByPropertyKey(PROP_KEY_PRODUCTION_DB_USER), getValueByPropertyKey(PROP_KEY_PRODUCTION_DB_PASSWORD) ); } public Connection createConnectionOfOnEditingDB() throws ClassNotFoundException, SQLException { return createConnection( getValueByPropertyKey(PROP_KEY_DB_DRIVER), getValueByPropertyKey(PROP_KEY_ONEDITING_DB_URL), getValueByPropertyKey(PROP_KEY_ONEDITING_DB_USER), getValueByPropertyKey(PROP_KEY_ONEDITING_DB_PASSWORD) ); } private static Connection createConnection( String dbDriver, String dbUrl, String dbUser, String dbPassword) throws ClassNotFoundException, SQLException { Class.forName(dbDriver); return DriverManager.getConnection(dbUrl, dbUser, dbPassword); } /***************** Getter Setter *******************/ private String getValueByPropertyKey(String key) { return _dataOriginProperties.getProperty(key); } public List<String> getDbTableNameList() { return _dbTableNameList; } public void setDbTableNameList(List<String> dbTableNameList) { _dbTableNameList = dbTableNameList; } public List<DBTable> getDbTableList() { return _dbTableList; } public void setDbTableList(List<DBTable> dbTableList) { _dbTableList = dbTableList; } public DataOriginDirManager getDataOriginDirManager() { return _dataOriginDirManager; } public void setDataOriginDirManager(DataOriginDirManager dataOriginDirManager) { _dataOriginDirManager = dataOriginDirManager; } public File getTemplateDir() { return _templateDir; } public void setTemplateDir(File templateDir) { _templateDir = templateDir; } public File getOutputWebProjectDir() { return _outputWebProjectDir; } public void setOutputWebProjectDir(File outputWebProjectDir) { _outputWebProjectDir = outputWebProjectDir; } public String getOutputWebProjectJavaPackage() { return _outputWebProjectJavaPackage; } public void setOutputWebProjectJavaPackage(String outputWebProjectJavaPackage) { _outputWebProjectJavaPackage = outputWebProjectJavaPackage; } public File getOutputWebProjectJavaSrcDir() { return _outputWebProjectJavaSrcDir; } public void setOutputWebProjectJavaSrcDir(File outputWebProjectJavaSrcDir) { _outputWebProjectJavaSrcDir = outputWebProjectJavaSrcDir; } public String getOutputWebContextName() { return _outputWebContextName; } public void setOutputWebContextName(String outputWebContextName) { _outputWebContextName = outputWebContextName; } }
/* * Copyright 2013, 2014, 2015 Antoine Vianey * * 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 fr.avianey.androidsvgdrawable; import fr.avianey.androidsvgdrawable.util.TestLogger; import fr.avianey.androidsvgdrawable.util.TestParameters; import org.apache.batik.transcoder.TranscoderException; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.xpath.XPathExpressionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static fr.avianey.androidsvgdrawable.Density.Value.mdpi; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(Parameterized.class) public class SvgMaskTest { private static final String PATH_IN = "./target/test-classes/" + SvgMaskTest.class.getSimpleName() + "/"; private static final String PATH_OUT_PNG = "./target/generated-png/" + SvgMaskTest.class.getSimpleName() + "/"; private static final String PATH_OUT_SVG = "./target/generated-svg/"; private static int RUN = 0; private static QualifiedSVGResourceFactory qualifiedSVGResourceFactory; private final String mask; private final List<QualifiedResource> resources; private final List<String> maskedResourcesNames; private final File dir; private final boolean useSameSvgOnlyOnceInMask; private static SvgDrawablePlugin plugin; private static File output; @BeforeClass public static void setup() { plugin = new SvgDrawablePlugin(new TestParameters(), new TestLogger()); qualifiedSVGResourceFactory = plugin.getQualifiedSVGResourceFactory(); output = new File(PATH_OUT_PNG); output.mkdirs(); } public SvgMaskTest(String mask, List<String> resourceNames, List<String> maskedResourcesNames, boolean useSameSvgOnlyOnceInMask) throws IOException { RUN++; this.dir = new File(PATH_OUT_SVG, String.valueOf(RUN)); this.mask = mask; this.resources = new ArrayList<>(resourceNames.size()); for (String name : resourceNames) { this.resources.add(qualifiedSVGResourceFactory.fromSVGFile(new File(PATH_IN, name))); } this.maskedResourcesNames = maskedResourcesNames; this.useSameSvgOnlyOnceInMask = useSameSvgOnlyOnceInMask; } @Parameters public static Collection<Object[]> data() { return asList( new Object[][]{ { "mask-mdpi.svgmask", asList("square_red-mdpi.svg"), asList("mask_square_red-mdpi.svg"), false }, { "mask_image_ns-mdpi.svgmask", asList("square_red-mdpi.svg"), asList("mask_image_ns_square_red-mdpi.svg"), false }, { "mask_image_ns_bad-mdpi.svgmask", asList("square_red-mdpi.svg"), Collections.EMPTY_LIST, false }, { "mask_svg_ns-mdpi.svgmask", asList("square_red-mdpi.svg"), asList("mask_svg_ns_square_red-mdpi.svg"), false }, { "mask_no_image-mdpi.svgmask", asList("square_red-mdpi.svg"), Collections.EMPTY_LIST, false }, { "mask_no_match-mdpi.svgmask", asList("square_red-mdpi.svg"), Collections.EMPTY_LIST, false }, { "mask_no_regexp-mdpi.svgmask", asList("square_red-mdpi.svg"), Collections.EMPTY_LIST, false }, { "mask_multiple_image-mdpi.svgmask", asList("square_red-mdpi.svg", "square_yellow-mdpi.svg", "circle_blue-mdpi.svg", "circle_green-mdpi.svg"), asList( "mask_multiple_image_square_red_circle_blue-mdpi.svg", "mask_multiple_image_square_red_circle_green-mdpi.svg", "mask_multiple_image_square_yellow_circle_blue-mdpi.svg", "mask_multiple_image_square_yellow_circle_green-mdpi.svg" ), false }, { "mask_same_image_twice-mdpi.svgmask", asList( "square_red-mdpi.svg", "square_yellow-mdpi.svg", "circle_blue-mdpi.svg", "circle_green-mdpi.svg", "circle_pink-mdpi.svg", "triangle_black-mdpi.svg", "triangle_white-mdpi.svg" ), asList( "mask_same_image_twice_square_red_circle_blue_triangle_black_square_red-mdpi.svg", "mask_same_image_twice_square_red_circle_blue_triangle_black_square_yellow-mdpi.svg", "mask_same_image_twice_square_red_circle_green_triangle_black_square_red-mdpi.svg", "mask_same_image_twice_square_red_circle_green_triangle_black_square_yellow-mdpi.svg", "mask_same_image_twice_square_red_circle_pink_triangle_black_square_red-mdpi.svg", "mask_same_image_twice_square_red_circle_pink_triangle_black_square_yellow-mdpi.svg", "mask_same_image_twice_square_yellow_circle_blue_triangle_black_square_red-mdpi.svg", "mask_same_image_twice_square_yellow_circle_blue_triangle_black_square_yellow-mdpi.svg", "mask_same_image_twice_square_yellow_circle_green_triangle_black_square_red-mdpi.svg", "mask_same_image_twice_square_yellow_circle_green_triangle_black_square_yellow-mdpi.svg", "mask_same_image_twice_square_yellow_circle_pink_triangle_black_square_red-mdpi.svg", "mask_same_image_twice_square_yellow_circle_pink_triangle_black_square_yellow-mdpi.svg", "mask_same_image_twice_square_red_circle_blue_triangle_white_square_red-mdpi.svg", "mask_same_image_twice_square_red_circle_blue_triangle_white_square_yellow-mdpi.svg", "mask_same_image_twice_square_red_circle_green_triangle_white_square_red-mdpi.svg", "mask_same_image_twice_square_red_circle_green_triangle_white_square_yellow-mdpi.svg", "mask_same_image_twice_square_red_circle_pink_triangle_white_square_red-mdpi.svg", "mask_same_image_twice_square_red_circle_pink_triangle_white_square_yellow-mdpi.svg", "mask_same_image_twice_square_yellow_circle_blue_triangle_white_square_red-mdpi.svg", "mask_same_image_twice_square_yellow_circle_blue_triangle_white_square_yellow-mdpi.svg", "mask_same_image_twice_square_yellow_circle_green_triangle_white_square_red-mdpi.svg", "mask_same_image_twice_square_yellow_circle_green_triangle_white_square_yellow-mdpi.svg", "mask_same_image_twice_square_yellow_circle_pink_triangle_white_square_red-mdpi.svg", "mask_same_image_twice_square_yellow_circle_pink_triangle_white_square_yellow-mdpi.svg" ), false }, { "mask_same_image_twice-mdpi.svgmask", asList( "square_red-mdpi.svg", "square_yellow-mdpi.svg", "circle_blue-mdpi.svg", "circle_green-mdpi.svg", "circle_pink-mdpi.svg", "triangle_black-mdpi.svg", "triangle_white-mdpi.svg" ), asList( "mask_same_image_twice_square_red_circle_blue_triangle_black_square_yellow-mdpi.svg", "mask_same_image_twice_square_red_circle_green_triangle_black_square_yellow-mdpi.svg", "mask_same_image_twice_square_red_circle_pink_triangle_black_square_yellow-mdpi.svg", "mask_same_image_twice_square_yellow_circle_blue_triangle_black_square_red-mdpi.svg", "mask_same_image_twice_square_yellow_circle_green_triangle_black_square_red-mdpi.svg", "mask_same_image_twice_square_yellow_circle_pink_triangle_black_square_red-mdpi.svg", "mask_same_image_twice_square_red_circle_blue_triangle_white_square_yellow-mdpi.svg", "mask_same_image_twice_square_red_circle_green_triangle_white_square_yellow-mdpi.svg", "mask_same_image_twice_square_red_circle_pink_triangle_white_square_yellow-mdpi.svg", "mask_same_image_twice_square_yellow_circle_blue_triangle_white_square_red-mdpi.svg", "mask_same_image_twice_square_yellow_circle_green_triangle_white_square_red-mdpi.svg", "mask_same_image_twice_square_yellow_circle_pink_triangle_white_square_red-mdpi.svg" ), true } }); } @Test public void fromJson() throws TransformerException, ParserConfigurationException, SAXException, IOException, XPathExpressionException, InstantiationException, IllegalAccessException, TranscoderException { QualifiedResource maskResource = qualifiedSVGResourceFactory.fromSVGFile(new File(PATH_IN, mask)); SvgMask svgMask = new SvgMask(maskResource); Collection<QualifiedResource> maskedResources = svgMask.generatesMaskedResources(qualifiedSVGResourceFactory, dir, resources, useSameSvgOnlyOnceInMask, OverrideMode.always); assertEquals(maskedResourcesNames.size(), maskedResources.size()); assertEquals(maskedResourcesNames.size(), dir.list().length); QualifiedResource qr; for (String maskedResource : maskedResourcesNames) { qr = qualifiedSVGResourceFactory.fromSVGFile(new File(dir, maskedResource)); assertTrue(qr.exists()); plugin.transcode(qr, mdpi, output, null); } } }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.world.gen; import static com.google.common.base.Preconditions.checkNotNull; import com.flowpowered.math.vector.Vector2i; import com.flowpowered.math.vector.Vector3i; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.minecraft.block.BlockFalling; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EnumCreatureType; import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.util.IProgressUpdate; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.BiomeGenBase.SpawnListEntry; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.ChunkProviderGenerate; import net.minecraft.world.gen.NoiseGeneratorPerlin; import net.minecraft.world.gen.structure.MapGenStronghold; import net.minecraft.world.gen.structure.StructureOceanMonument; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.data.Transaction; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.NamedCause; import org.spongepowered.api.event.world.chunk.PopulateChunkEvent; import org.spongepowered.api.world.biome.BiomeGenerationSettings; import org.spongepowered.api.world.biome.BiomeType; import org.spongepowered.api.world.biome.GroundCoverLayer; import org.spongepowered.api.world.extent.ImmutableBiomeArea; import org.spongepowered.api.world.extent.MutableBlockVolume; import org.spongepowered.api.world.gen.BiomeGenerator; import org.spongepowered.api.world.gen.GenerationPopulator; import org.spongepowered.api.world.gen.Populator; import org.spongepowered.api.world.gen.PopulatorType; import org.spongepowered.api.world.gen.WorldGenerator; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.interfaces.world.IMixinWorld; import org.spongepowered.common.interfaces.world.biome.IBiomeGenBase; import org.spongepowered.common.interfaces.world.gen.IChunkProviderGenerate; import org.spongepowered.common.interfaces.world.gen.IFlaggedPopulator; import org.spongepowered.common.util.StaticMixinHelper; import org.spongepowered.common.util.gen.ByteArrayMutableBiomeBuffer; import org.spongepowered.common.util.gen.ChunkPrimerBuffer; import org.spongepowered.common.world.CaptureType; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; /** * Similar class to {@link ChunkProviderGenerate}, but instead gets its blocks * from a custom chunk generator. */ public class SpongeChunkProvider implements WorldGenerator, IChunkProvider { private static final Vector2i CHUNK_AREA = new Vector2i(16, 16); protected BiomeGenerator biomeGenerator; protected GenerationPopulator baseGenerator; protected List<GenerationPopulator> genpop; protected List<Populator> pop; protected Map<BiomeType, BiomeGenerationSettings> biomeSettings; protected final World world; private final ByteArrayMutableBiomeBuffer cachedBiomes; protected Random rand; private NoiseGeneratorPerlin noise4; private double[] stoneNoise; public SpongeChunkProvider(World world, GenerationPopulator base, BiomeGenerator biomegen) { this.world = checkNotNull(world, "world"); this.baseGenerator = checkNotNull(base, "baseGenerator"); this.biomeGenerator = checkNotNull(biomegen, "biomeGenerator"); // Make initially empty biome cache this.cachedBiomes = new ByteArrayMutableBiomeBuffer(Vector2i.ZERO, CHUNK_AREA); this.cachedBiomes.detach(); this.genpop = Lists.newArrayList(); this.pop = Lists.newArrayList(); this.biomeSettings = Maps.newHashMap(); this.rand = new Random(world.getSeed()); this.noise4 = new NoiseGeneratorPerlin(this.rand, 4); this.stoneNoise = new double[256]; this.world.provider.worldChunkMgr = CustomWorldChunkManager.of(this.biomeGenerator); if (this.baseGenerator instanceof IChunkProviderGenerate) { ((IChunkProviderGenerate) this.baseGenerator).setBiomeGenerator(this.biomeGenerator); } } @Override public GenerationPopulator getBaseGenerationPopulator() { return this.baseGenerator; } @Override public void setBaseGenerationPopulator(GenerationPopulator baseGenerationPopulator) { this.baseGenerator = baseGenerationPopulator; if (this.baseGenerator instanceof IChunkProviderGenerate) { ((IChunkProviderGenerate) this.baseGenerator).setBiomeGenerator(this.biomeGenerator); } } @Override public List<GenerationPopulator> getGenerationPopulators() { return this.genpop; } public void setGenerationPopulators(List<GenerationPopulator> generationPopulators) { this.genpop = Lists.newArrayList(generationPopulators); } @Override public List<Populator> getPopulators() { return this.pop; } public void setPopulators(List<Populator> populators) { this.pop = Lists.newArrayList(populators); } public Map<BiomeType, BiomeGenerationSettings> getBiomeOverrides() { return this.biomeSettings; } public void setBiomeOverrides(Map<BiomeType, BiomeGenerationSettings> biomeOverrides) { this.biomeSettings = Maps.newHashMap(biomeOverrides); } @Override public BiomeGenerator getBiomeGenerator() { return this.biomeGenerator; } @Override public void setBiomeGenerator(BiomeGenerator biomeGenerator) { this.biomeGenerator = biomeGenerator; this.world.provider.worldChunkMgr = CustomWorldChunkManager.of(biomeGenerator); if (this.baseGenerator instanceof IChunkProviderGenerate) { ((IChunkProviderGenerate) this.baseGenerator).setBiomeGenerator(biomeGenerator); } } @Override public BiomeGenerationSettings getBiomeSettings(BiomeType type) { if (!this.biomeSettings.containsKey(type)) { this.biomeSettings.put(type, ((IBiomeGenBase) type).initPopulators(this.world)); } return this.biomeSettings.get(type); } @Override public List<GenerationPopulator> getGenerationPopulators(Class<? extends GenerationPopulator> type) { return this.genpop.stream().filter((p) -> { return type.isAssignableFrom(p.getClass()); }).collect(Collectors.toList()); } @Override public List<Populator> getPopulators(Class<? extends Populator> type) { return this.pop.stream().filter((p) -> { return type.isAssignableFrom(p.getClass()); }).collect(Collectors.toList()); } @Override public Chunk provideChunk(int chunkX, int chunkZ) { this.rand.setSeed((long) chunkX * 341873128712L + (long) chunkZ * 132897987541L); this.cachedBiomes.reuse(new Vector2i(chunkX * 16, chunkZ * 16)); this.biomeGenerator.generateBiomes(this.cachedBiomes); // Generate base terrain ChunkPrimer chunkprimer = new ChunkPrimer(); MutableBlockVolume blockBuffer = new ChunkPrimerBuffer(chunkprimer, chunkX, chunkZ); ImmutableBiomeArea biomeBuffer = this.cachedBiomes.getImmutableBiomeCopy(); this.baseGenerator.populate((org.spongepowered.api.world.World) this.world, blockBuffer, biomeBuffer); replaceBiomeBlocks(this.world, this.rand, chunkX, chunkZ, chunkprimer, biomeBuffer); // Apply the generator populators to complete the blockBuffer for (GenerationPopulator populator : this.genpop) { populator.populate((org.spongepowered.api.world.World) this.world, blockBuffer, biomeBuffer); } // Get unique biomes to determine what generator populators to run List<BiomeType> uniqueBiomes = Lists.newArrayList(); BiomeType biome; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { biome = this.cachedBiomes.getBiome(chunkX * 16 + x, chunkZ * 16 + z); if (!uniqueBiomes.contains(biome)) { uniqueBiomes.add(biome); } } } // run our generator populators for (BiomeType type : uniqueBiomes) { if (!this.biomeSettings.containsKey(type)) { this.biomeSettings.put(type, ((IBiomeGenBase) type).initPopulators(this.world)); } for (GenerationPopulator populator : this.biomeSettings.get(type).getGenerationPopulators()) { populator.populate((org.spongepowered.api.world.World) this.world, blockBuffer, biomeBuffer); } } // Assemble chunk Chunk chunk = new Chunk(this.world, chunkprimer, chunkX, chunkZ); byte[] biomeArray = chunk.getBiomeArray(); System.arraycopy(this.cachedBiomes.detach(), 0, biomeArray, 0, biomeArray.length); chunk.generateSkylightMap(); return chunk; } @Override public void populate(IChunkProvider chunkProvider, int chunkX, int chunkZ) { IMixinWorld world = (IMixinWorld) this.world; world.setProcessingCaptureCause(true); world.setCapturingTerrainGen(true); Cause populateCause = Cause.of(NamedCause.source(this), NamedCause.of("ChunkProvider", chunkProvider)); this.rand.setSeed(this.world.getSeed()); long i1 = this.rand.nextLong() / 2L * 2L + 1L; long j1 = this.rand.nextLong() / 2L * 2L + 1L; this.rand.setSeed((long) chunkX * i1 + (long) chunkZ * j1 ^ this.world.getSeed()); BlockFalling.fallInstantly = true; BlockPos blockpos = new BlockPos(chunkX * 16, 0, chunkZ * 16); BiomeType biome = (BiomeType) this.world.getBiomeGenForCoords(blockpos.add(16, 0, 16)); org.spongepowered.api.world.Chunk chunk = (org.spongepowered.api.world.Chunk) this.world.getChunkFromChunkCoords(chunkX, chunkZ); if (!this.biomeSettings.containsKey(biome)) { this.biomeSettings.put(biome, ((IBiomeGenBase) biome).initPopulators(this.world)); } List<Populator> populators = Lists.newArrayList(this.pop); populators.addAll(this.biomeSettings.get(biome).getPopulators()); Sponge.getGame().getEventManager().post(SpongeEventFactory.createPopulateChunkEventPre(populateCause, populators, chunk)); List<String> flags = Lists.newArrayList(); for (Populator populator : populators) { if(Sponge.getGame().getEventManager().post(SpongeEventFactory.createPopulateChunkEventPopulate(populateCause, populator, chunk))) { continue; } StaticMixinHelper.runningGenerator = populator.getType(); if (populator instanceof IFlaggedPopulator) { ((IFlaggedPopulator) populator).populate(chunkProvider, chunk, this.rand, flags); } else { populator.populate(chunk, this.rand); } StaticMixinHelper.runningGenerator = null; } // If we wrapped a custom chunk provider then we should call its // populate method so that its particular changes are used. if (this.baseGenerator instanceof SpongeGenerationPopulator) { ((SpongeGenerationPopulator) this.baseGenerator).getHandle(this.world).populate(chunkProvider, chunkX, chunkZ); } ImmutableMap.Builder<PopulatorType, List<Transaction<BlockSnapshot>>> populatorChanges = ImmutableMap.builder(); for (Map.Entry<PopulatorType, LinkedHashMap<Vector3i, Transaction<BlockSnapshot>>> entry : world.getCapturedPopulatorChanges().entrySet()) { populatorChanges.put(entry.getKey(), ImmutableList.copyOf(entry.getValue().values())); } PopulateChunkEvent.Post event = SpongeEventFactory.createPopulateChunkEventPost(populateCause, populatorChanges.build(), chunk); SpongeImpl.postEvent(event); for (List<Transaction<BlockSnapshot>> transactions : event.getPopulatedTransactions().values()) { world.markAndNotifyBlockPost(transactions, CaptureType.POPULATE, populateCause); } world.setCapturingTerrainGen(false); world.setProcessingCaptureCause(false); world.getCapturedPopulatorChanges().clear(); BlockFalling.fallInstantly = false; } @Override public boolean func_177460_a(IChunkProvider chunkProvider, Chunk chunk, int chunkX, int chunkZ) { boolean flag = false; if (chunk.getInhabitedTime() < 3600L) { for (Populator populator : this.pop) { if (populator instanceof StructureOceanMonument) { flag |= ((StructureOceanMonument) populator).generateStructure(this.world, this.rand, new ChunkCoordIntPair(chunkX, chunkZ)); } } } return flag; } @Override public List<SpawnListEntry> getPossibleCreatures(EnumCreatureType creatureType, BlockPos pos) { BiomeGenBase biome = this.world.getBiomeGenForCoords(pos); @SuppressWarnings("unchecked") List<SpawnListEntry> creatures = biome.getSpawnableList(creatureType); return creatures; } @Override public BlockPos getStrongholdGen(World worldIn, String structureName, BlockPos position) { if ("Stronghold".equals(structureName)) { for (GenerationPopulator gen : this.genpop) { if (gen instanceof MapGenStronghold) { return ((MapGenStronghold) gen).getClosestStrongholdPos(worldIn, position); } } } return null; } @Override public void recreateStructures(Chunk chunk, int chunkX, int chunkZ) { // TODO No structure support } // Methods below are simply mirrors of the methods in ChunkProviderGenerate @Override public Chunk provideChunk(BlockPos blockPosIn) { return provideChunk(blockPosIn.getX() >> 4, blockPosIn.getZ() >> 4); } @Override public int getLoadedChunkCount() { return 0; } @Override public String makeString() { return "RandomLevelSource"; } @Override public boolean canSave() { return true; } @Override public boolean saveChunks(boolean bool, IProgressUpdate progressUpdate) { return true; } @Override public void saveExtraData() { } @Override public boolean unloadQueuedChunks() { return false; } @Override public boolean chunkExists(int x, int z) { return true; } public void replaceBiomeBlocks(World world, Random rand, int x, int z, ChunkPrimer chunk, ImmutableBiomeArea biomes) { double d0 = 0.03125D; this.stoneNoise = this.noise4.func_151599_a(this.stoneNoise, (double) (x * 16), (double) (z * 16), 16, 16, d0 * 2.0D, d0 * 2.0D, 1.0D); Vector2i min = biomes.getBiomeMin(); for (int k = 0; k < 16; ++k) { for (int l = 0; l < 16; ++l) { BiomeType biomegenbase = biomes.getBiome(min.getX() + l, min.getY() + k); generateBiomeTerrain(world, rand, chunk, x * 16 + k, z * 16 + l, this.stoneNoise[l + k * 16], getBiomeSettings(biomegenbase).getGroundCoverLayers()); } } } public void generateBiomeTerrain(World worldIn, Random rand, ChunkPrimer chunk, int x, int z, double stoneNoise, List<GroundCoverLayer> groundcover) { if (groundcover.isEmpty()) { return; } int seaLevel = worldIn.getSeaLevel(); IBlockState currentPlacement = null; int k = -1; int relativeX = x & 15; int relativeZ = z & 15; int i = 0; for (int currentY = 255; currentY >= 0; --currentY) { IBlockState nextBlock = chunk.getBlockState(relativeZ, currentY, relativeX); if (nextBlock.getBlock().getMaterial() == Material.air) { k = -1; } else if (nextBlock.getBlock() == Blocks.stone) { if (k == -1) { if (groundcover.isEmpty()) { k = 0; continue; } i = 0; GroundCoverLayer layer = groundcover.get(i); currentPlacement = (IBlockState) layer.getBlockState().apply(stoneNoise); k = layer.getDepth().getFlooredAmount(rand, stoneNoise); if (k <= 0) { continue; } if (currentY >= seaLevel-1) { chunk.setBlockState(relativeZ, currentY, relativeX, currentPlacement); ++i; if (i < groundcover.size()) { layer = groundcover.get(i); k = layer.getDepth().getFlooredAmount(rand, stoneNoise); currentPlacement = (IBlockState) layer.getBlockState().apply(stoneNoise); } } else if (currentY < seaLevel - 7 - k) { k = 0; chunk.setBlockState(relativeZ, currentY, relativeX, Blocks.gravel.getDefaultState()); } else { ++i; if (i < groundcover.size()) { layer = groundcover.get(i); k = layer.getDepth().getFlooredAmount(rand, stoneNoise); currentPlacement = (IBlockState) layer.getBlockState().apply(stoneNoise); chunk.setBlockState(relativeZ, currentY, relativeX, currentPlacement); } } } else if (k > 0) { --k; chunk.setBlockState(relativeZ, currentY, relativeX, currentPlacement); if (k == 0) { ++i; if (i < groundcover.size()) { GroundCoverLayer layer = groundcover.get(i); k = layer.getDepth().getFlooredAmount(rand, stoneNoise); currentPlacement = (IBlockState) layer.getBlockState().apply(stoneNoise); } } } } } } }
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.restapi.project; import static com.google.gerrit.reviewdb.client.RefNames.isConfigRef; import com.google.common.base.Strings; import com.google.common.flogger.FluentLogger; import com.google.gerrit.extensions.api.projects.BranchInfo; import com.google.gerrit.extensions.api.projects.BranchInput; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.BadRequestException; import com.google.gerrit.extensions.restapi.IdString; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.RestCollectionCreateView; import com.google.gerrit.reviewdb.client.Branch; import com.google.gerrit.reviewdb.client.RefNames; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.extensions.events.GitReferenceUpdated; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.permissions.PermissionBackend; import com.google.gerrit.server.permissions.PermissionBackendException; import com.google.gerrit.server.permissions.RefPermission; import com.google.gerrit.server.project.BranchResource; import com.google.gerrit.server.project.CreateRefControl; import com.google.gerrit.server.project.NoSuchProjectException; import com.google.gerrit.server.project.ProjectResource; import com.google.gerrit.server.project.RefUtil; import com.google.gerrit.server.project.RefValidationHelper; import com.google.gerrit.server.util.MagicBranch; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import java.io.IOException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevObject; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.ReceiveCommand; @Singleton public class CreateBranch implements RestCollectionCreateView<ProjectResource, BranchResource, BranchInput> { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Provider<IdentifiedUser> identifiedUser; private final PermissionBackend permissionBackend; private final GitRepositoryManager repoManager; private final GitReferenceUpdated referenceUpdated; private final RefValidationHelper refCreationValidator; private final CreateRefControl createRefControl; @Inject CreateBranch( Provider<IdentifiedUser> identifiedUser, PermissionBackend permissionBackend, GitRepositoryManager repoManager, GitReferenceUpdated referenceUpdated, RefValidationHelper.Factory refHelperFactory, CreateRefControl createRefControl) { this.identifiedUser = identifiedUser; this.permissionBackend = permissionBackend; this.repoManager = repoManager; this.referenceUpdated = referenceUpdated; this.refCreationValidator = refHelperFactory.create(ReceiveCommand.Type.CREATE); this.createRefControl = createRefControl; } @Override public BranchInfo apply(ProjectResource rsrc, IdString id, BranchInput input) throws BadRequestException, AuthException, ResourceConflictException, IOException, PermissionBackendException, NoSuchProjectException { String ref = id.get(); if (input == null) { input = new BranchInput(); } if (input.ref != null && !ref.equals(input.ref)) { throw new BadRequestException("ref must match URL"); } if (input.revision != null) { input.revision = input.revision.trim(); } if (Strings.isNullOrEmpty(input.revision)) { input.revision = Constants.HEAD; } while (ref.startsWith("/")) { ref = ref.substring(1); } ref = RefNames.fullName(ref); if (!Repository.isValidRefName(ref)) { throw new BadRequestException("invalid branch name \"" + ref + "\""); } if (MagicBranch.isMagicBranch(ref)) { throw new BadRequestException( "not allowed to create branches under \"" + MagicBranch.getMagicRefNamePrefix(ref) + "\""); } final Branch.NameKey name = new Branch.NameKey(rsrc.getNameKey(), ref); try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) { ObjectId revid = RefUtil.parseBaseRevision(repo, rsrc.getNameKey(), input.revision); RevWalk rw = RefUtil.verifyConnected(repo, revid); RevObject object = rw.parseAny(revid); if (ref.startsWith(Constants.R_HEADS)) { // Ensure that what we start the branch from is a commit. If we // were given a tag, deference to the commit instead. // try { object = rw.parseCommit(object); } catch (IncorrectObjectTypeException notCommit) { throw new BadRequestException("\"" + input.revision + "\" not a commit", notCommit); } } createRefControl.checkCreateRef(identifiedUser, repo, name, object); try { final RefUpdate u = repo.updateRef(ref); u.setExpectedOldObjectId(ObjectId.zeroId()); u.setNewObjectId(object.copy()); u.setRefLogIdent(identifiedUser.get().newRefLogIdent()); u.setRefLogMessage("created via REST from " + input.revision, false); refCreationValidator.validateRefOperation(rsrc.getName(), identifiedUser.get(), u); final RefUpdate.Result result = u.update(rw); switch (result) { case FAST_FORWARD: case NEW: case NO_CHANGE: referenceUpdated.fire( name.getParentKey(), u, ReceiveCommand.Type.CREATE, identifiedUser.get().state()); break; case LOCK_FAILURE: if (repo.getRefDatabase().exactRef(ref) != null) { throw new ResourceConflictException("branch \"" + ref + "\" already exists"); } String refPrefix = RefUtil.getRefPrefix(ref); while (!Constants.R_HEADS.equals(refPrefix)) { if (repo.getRefDatabase().exactRef(refPrefix) != null) { throw new ResourceConflictException( "Cannot create branch \"" + ref + "\" since it conflicts with branch \"" + refPrefix + "\"."); } refPrefix = RefUtil.getRefPrefix(refPrefix); } // fall through // $FALL-THROUGH$ case FORCED: case IO_FAILURE: case NOT_ATTEMPTED: case REJECTED: case REJECTED_CURRENT_BRANCH: case RENAMED: case REJECTED_MISSING_OBJECT: case REJECTED_OTHER_REASON: default: { throw new IOException(result.name()); } } BranchInfo info = new BranchInfo(); info.ref = ref; info.revision = revid.getName(); if (isConfigRef(name.get())) { // Never allow to delete the meta config branch. info.canDelete = null; } else { info.canDelete = permissionBackend.currentUser().ref(name).testOrFalse(RefPermission.DELETE) && rsrc.getProjectState().statePermitsWrite() ? true : null; } return info; } catch (IOException err) { logger.atSevere().withCause(err).log("Cannot create branch \"%s\"", name); throw err; } } catch (RefUtil.InvalidRevisionException e) { throw new BadRequestException("invalid revision \"" + input.revision + "\"", e); } } }
/* * Copyright (c) 2010-2017 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.prism.impl.lex.dom; import com.evolveum.midpoint.prism.impl.PrismContextImpl; import com.evolveum.midpoint.prism.impl.marshaller.ItemPathHolder; import com.evolveum.midpoint.prism.schema.SchemaRegistry; import com.evolveum.midpoint.prism.xml.DynamicNamespacePrefixMapper; import com.evolveum.midpoint.prism.xml.XsdTypeMapper; import com.evolveum.midpoint.prism.impl.xnode.ListXNodeImpl; import com.evolveum.midpoint.prism.impl.xnode.MapXNodeImpl; import com.evolveum.midpoint.prism.impl.xnode.PrimitiveXNodeImpl; import com.evolveum.midpoint.prism.impl.xnode.RootXNodeImpl; import com.evolveum.midpoint.prism.impl.xnode.SchemaXNodeImpl; import com.evolveum.midpoint.prism.impl.xnode.XNodeImpl; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import static com.evolveum.midpoint.util.MiscUtil.emptyIfNull; /** * @author semancik * */ public class DomLexicalWriter { private Document doc; private boolean serializeCompositeObjects = false; private SchemaRegistry schemaRegistry; DomLexicalWriter(SchemaRegistry schemaRegistry) { super(); this.schemaRegistry = schemaRegistry; } public boolean isSerializeCompositeObjects() { return serializeCompositeObjects; } public void setSerializeCompositeObjects(boolean serializeCompositeObjects) { this.serializeCompositeObjects = serializeCompositeObjects; } private DynamicNamespacePrefixMapper getNamespacePrefixMapper() { if (schemaRegistry == null) { return null; } return schemaRegistry.getNamespacePrefixMapper(); } private void initialize() { doc = DOMUtil.getDocument(); } private void initializeWithExistingDocument(Document document) { doc = document; document.getDocumentElement(); } @NotNull public Element serialize(@NotNull RootXNodeImpl rootxnode) throws SchemaException { initialize(); return serializeInternal(rootxnode, null); } public Element serialize(@NotNull List<RootXNodeImpl> roots, @Nullable QName aggregateElementName) throws SchemaException { initialize(); if (aggregateElementName == null) { aggregateElementName = schemaRegistry.getPrismContext().getObjectsElementName(); if (aggregateElementName == null) { throw new IllegalStateException("Couldn't serialize list of objects because the aggregated element name is not set"); } } Element aggregateElement = createElement(aggregateElementName, null); for (RootXNodeImpl root : roots) { serializeInternal(root, aggregateElement); } return aggregateElement; } // this one is used only from within JaxbDomHack.toAny(..) - hopefully it will disappear soon @Deprecated public Element serialize(RootXNodeImpl rootxnode, Document document) throws SchemaException { initializeWithExistingDocument(document); return serializeInternal(rootxnode, null); } public Element serializeUnderElement(RootXNodeImpl rootxnode, Element parentElement) throws SchemaException { initializeWithExistingDocument(parentElement.getOwnerDocument()); return serializeInternal(rootxnode, parentElement); } @NotNull private Element serializeInternal(@NotNull RootXNodeImpl rootxnode, Element parentElement) throws SchemaException { QName rootElementName = rootxnode.getRootElementName(); Element topElement = createElement(rootElementName, parentElement); if (parentElement != null) { parentElement.appendChild(topElement); } QName typeQName = rootxnode.getTypeQName(); if (typeQName != null && rootxnode.isExplicitTypeDeclaration()) { DOMUtil.setXsiType(topElement, setQNamePrefixExplicitIfNeeded(typeQName)); } XNodeImpl subnode = rootxnode.getSubnode(); if (subnode instanceof PrimitiveXNodeImpl){ serializePrimitiveElementOrAttribute((PrimitiveXNodeImpl) subnode, topElement, rootElementName, false); return DOMUtil.getFirstChildElement(topElement); } if (subnode instanceof MapXNodeImpl) { // at this point we can put frequently used namespaces (e.g. c, t, q, ri) into the document to eliminate their use // on many places inside the doc (MID-2198) DOMUtil.setNamespaceDeclarations(topElement, getNamespacePrefixMapper().getNamespacesDeclaredByDefault()); serializeMap((MapXNodeImpl) subnode, topElement); } else if (subnode.isHeterogeneousList()) { DOMUtil.setNamespaceDeclarations(topElement, getNamespacePrefixMapper().getNamespacesDeclaredByDefault()); serializeExplicitList((ListXNodeImpl) subnode, topElement); } else { throw new SchemaException("Sub-root xnode is not a map nor an explicit list, cannot serialize to XML (it is "+subnode+")"); } addDefaultNamespaceDeclaration(topElement); return topElement; } /** * Adds xmlns='...common-3' if needed. * In fact, this is VERY ugly hack to avoid putting common-3 declarations all over the elements in bulk actions response. * e.getNamespaceURI returns something only if it was present during node creation. * So, in fact, this code is more than fragile. Seems to work with the current XNode->DOM serialization, though. */ private void addDefaultNamespaceDeclaration(Element top) { List<Element> prefixless = DOMUtil.getElementsWithoutNamespacePrefix(top); if (prefixless.size() < 2) { return; // nothing to do here } Set<String> namespaces = prefixless.stream().map(e -> emptyIfNull(e.getNamespaceURI())).collect(Collectors.toSet()); if (namespaces.size() != 1 || StringUtils.isEmpty(namespaces.iterator().next())) { return; } DOMUtil.setNamespaceDeclaration(top, "", namespaces.iterator().next()); } Element serializeToElement(MapXNodeImpl xmap, QName elementName) throws SchemaException { initialize(); Element element = createElement(elementName, null); serializeMap(xmap, element); return element; } private void serializeMap(MapXNodeImpl xmap, Element topElement) throws SchemaException { for (Entry<QName, XNodeImpl> entry: xmap.entrySet()) { QName elementQName = entry.getKey(); XNodeImpl xsubnode = entry.getValue(); serializeSubnode(xsubnode, topElement, elementQName); } } private void serializeSubnode(XNodeImpl xsubnode, Element parentElement, QName elementName) throws SchemaException { if (xsubnode == null) { return; } if (xsubnode instanceof RootXNodeImpl) { Element element = createElement(elementName, parentElement); appendCommentIfPresent(element, xsubnode); parentElement.appendChild(element); serializeSubnode(((RootXNodeImpl) xsubnode).getSubnode(), element, ((RootXNodeImpl) xsubnode).getRootElementName()); } else if (xsubnode instanceof MapXNodeImpl) { Element element = createElement(elementName, parentElement); appendCommentIfPresent(element, xsubnode); if (xsubnode.isExplicitTypeDeclaration() && xsubnode.getTypeQName() != null){ DOMUtil.setXsiType(element, setQNamePrefixExplicitIfNeeded(xsubnode.getTypeQName())); } parentElement.appendChild(element); serializeMap((MapXNodeImpl)xsubnode, element); } else if (xsubnode instanceof PrimitiveXNodeImpl<?>) { PrimitiveXNodeImpl<?> xprim = (PrimitiveXNodeImpl<?>)xsubnode; if (xprim.isAttribute()) { serializePrimitiveElementOrAttribute(xprim, parentElement, elementName, true); } else { serializePrimitiveElementOrAttribute(xprim, parentElement, elementName, false); } } else if (xsubnode instanceof ListXNodeImpl) { ListXNodeImpl xlist = (ListXNodeImpl)xsubnode; if (xlist.isHeterogeneousList()) { Element element = createElement(elementName, parentElement); serializeExplicitList(xlist, element); parentElement.appendChild(element); } else { for (XNodeImpl xsubsubnode : xlist) { serializeSubnode(xsubsubnode, parentElement, elementName); } } } else if (xsubnode instanceof SchemaXNodeImpl) { serializeSchema((SchemaXNodeImpl)xsubnode, parentElement); } else { throw new IllegalArgumentException("Unknown subnode "+xsubnode); } } private void serializeExplicitList(ListXNodeImpl list, Element parent) throws SchemaException { for (XNodeImpl node : list) { if (node.getElementName() == null) { throw new SchemaException("In a list, there are both nodes with element names and nodes without them: " + list); } serializeSubnode(node, parent, node.getElementName()); } DOMUtil.setAttributeValue(parent, DOMUtil.IS_LIST_ATTRIBUTE_NAME, "true"); } Element serializeXPrimitiveToElement(PrimitiveXNodeImpl<?> xprim, QName elementName) throws SchemaException { initialize(); Element parent = DOMUtil.createElement(doc, new QName("fake","fake")); serializePrimitiveElementOrAttribute(xprim, parent, elementName, false); return DOMUtil.getFirstChildElement(parent); } private void serializePrimitiveElementOrAttribute(PrimitiveXNodeImpl<?> xprim, Element parentElement, QName elementOrAttributeName, boolean asAttribute) throws SchemaException { QName typeQName = xprim.getTypeQName(); // if typeQName is not explicitly specified, we try to determine it from parsed value // TODO we should probably set typeQName when parsing the value... if (typeQName == null && xprim.isParsed()) { Object v = xprim.getValue(); if (v != null) { typeQName = XsdTypeMapper.toXsdType(v.getClass()); } } if (typeQName == null) { // this means that either xprim is unparsed or it is empty if (PrismContextImpl.isAllowSchemalessSerialization()) { // We cannot correctly serialize without a type. But this is needed // sometimes. So just default to string String stringValue = xprim.getStringValue(); if (stringValue != null) { if (asAttribute) { DOMUtil.setAttributeValue(parentElement, elementOrAttributeName.getLocalPart(), stringValue); DOMUtil.setNamespaceDeclarations(parentElement, xprim.getRelevantNamespaceDeclarations()); } else { Element element; try { element = createElement(elementOrAttributeName, parentElement); appendCommentIfPresent(element, xprim); } catch (DOMException e) { throw new DOMException(e.code, e.getMessage() + "; creating element "+elementOrAttributeName+" in element "+DOMUtil.getQName(parentElement)); } parentElement.appendChild(element); DOMUtil.setElementTextContent(element, stringValue); DOMUtil.setNamespaceDeclarations(element, xprim.getRelevantNamespaceDeclarations()); } } return; } else { throw new IllegalStateException("No type for primitive element "+elementOrAttributeName+", cannot serialize (schemaless serialization is disabled)"); } } // typeName != null after this point if (StringUtils.isBlank(typeQName.getNamespaceURI())) { typeQName = XsdTypeMapper.determineQNameWithNs(typeQName); } Element element = null; if (ItemPathType.COMPLEX_TYPE.equals(typeQName)) { //ItemPathType itemPathType = //ItemPathType.asItemPathType(xprim.getValue()); // TODO fix this hack ItemPathType itemPathType = (ItemPathType) xprim.getValue(); if (itemPathType != null) { if (asAttribute) { throw new UnsupportedOperationException("Serializing ItemPath as an attribute is not supported yet"); } element = serializeItemPathTypeToElement(itemPathType, elementOrAttributeName, parentElement.getOwnerDocument()); parentElement.appendChild(element); } } else { // not an ItemPathType if (!asAttribute) { try { element = createElement(elementOrAttributeName, parentElement); } catch (DOMException e) { throw new DOMException(e.code, e.getMessage() + "; creating element "+elementOrAttributeName+" in element "+DOMUtil.getQName(parentElement)); } appendCommentIfPresent(element, xprim); parentElement.appendChild(element); } if (DOMUtil.XSD_QNAME.equals(typeQName)) { QName value = (QName) xprim.getParsedValueWithoutRecording(DOMUtil.XSD_QNAME); value = setQNamePrefixExplicitIfNeeded(value); if (asAttribute) { try { DOMUtil.setQNameAttribute(parentElement, elementOrAttributeName.getLocalPart(), value); } catch (DOMException e) { throw new DOMException(e.code, e.getMessage() + "; setting attribute "+elementOrAttributeName.getLocalPart()+" in element "+DOMUtil.getQName(parentElement)+" to QName value "+value); } } else { DOMUtil.setQNameValue(element, value); } } else { // not ItemType nor QName String value = xprim.getGuessedFormattedValue(); if (asAttribute) { DOMUtil.setAttributeValue(parentElement, elementOrAttributeName.getLocalPart(), value); } else { DOMUtil.setElementTextContent(element, value); } } } if (!asAttribute && xprim.isExplicitTypeDeclaration()) { DOMUtil.setXsiType(element, setQNamePrefixExplicitIfNeeded(typeQName)); } } private void appendCommentIfPresent(Element element, XNodeImpl xnode) { String text = xnode.getComment(); if (StringUtils.isNotEmpty(text)) { DOMUtil.createComment(element, text); } } private void serializeSchema(SchemaXNodeImpl xschema, Element parentElement) { Element schemaElement = xschema.getSchemaElement(); if (schemaElement == null){ return; } Element clonedSchema = (Element) schemaElement.cloneNode(true); doc.adoptNode(clonedSchema); parentElement.appendChild(clonedSchema); } /** * Create XML element with the correct namespace prefix and namespace definition. * @param qname element QName * @return created DOM element */ @NotNull private Element createElement(QName qname, Element parentElement) { String namespaceURI = qname.getNamespaceURI(); if (!StringUtils.isBlank(namespaceURI)) { qname = setQNamePrefix(qname); } if (parentElement != null) { return DOMUtil.createElement(doc, qname, parentElement, parentElement); } else { // This is needed otherwise the root element itself could not be created // Caller of this method is responsible for setting the topElement return DOMUtil.createElement(doc, qname); } } private QName setQNamePrefix(QName qname) { DynamicNamespacePrefixMapper namespacePrefixMapper = getNamespacePrefixMapper(); if (namespacePrefixMapper == null) { return qname; } return namespacePrefixMapper.setQNamePrefix(qname); } private QName setQNamePrefixExplicitIfNeeded(QName name) { if (name != null && StringUtils.isNotBlank(name.getNamespaceURI()) && StringUtils.isBlank(name.getPrefix())) { return setQNamePrefixExplicit(name); } else { return name; } } private QName setQNamePrefixExplicit(QName qname) { DynamicNamespacePrefixMapper namespacePrefixMapper = getNamespacePrefixMapper(); if (namespacePrefixMapper == null) { return qname; } return namespacePrefixMapper.setQNamePrefixExplicit(qname); } public Element serializeItemPathTypeToElement(ItemPathType itemPathType, QName elementName, Document ownerDocument) { return ItemPathHolder.serializeToElement(itemPathType.getItemPath(), elementName, ownerDocument); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.functionscore; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.lucene.search.function.CombineFunction; import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery; import org.elasticsearch.index.fielddata.ScriptDocValues; import org.elasticsearch.index.query.MatchAllQueryBuilder; import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder.FilterFunctionBuilder; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.script.MockScriptPlugin; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptType; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESTestCase; import java.io.IOException; 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.concurrent.ExecutionException; import java.util.function.Function; import static org.elasticsearch.client.Requests.searchRequest; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.scriptFunction; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; public class FunctionScoreIT extends ESIntegTestCase { static final String TYPE = "type"; static final String INDEX = "index"; @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singleton(CustomScriptPlugin.class); } public static class CustomScriptPlugin extends MockScriptPlugin { @Override protected Map<String, Function<Map<String, Object>, Object>> pluginScripts() { Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>(); scripts.put("1", vars -> 1.0d); scripts.put("get score value", vars -> ((Number) vars.get("_score")).doubleValue()); scripts.put("return (doc['num'].value)", vars -> { Map<?, ?> doc = (Map) vars.get("doc"); ScriptDocValues.Longs num = (ScriptDocValues.Longs) doc.get("num"); return num.getValue(); }); scripts.put("doc['random_score']", vars -> { Map<?, ?> doc = (Map) vars.get("doc"); ScriptDocValues.Doubles randomScore = (ScriptDocValues.Doubles) doc.get("random_score"); return randomScore.getValue(); }); return scripts; } } public void testScriptScoresNested() throws IOException { createIndex(INDEX); index(INDEX, TYPE, "1", jsonBuilder().startObject().field("dummy_field", 1).endObject()); refresh(); Script scriptOne = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "1", Collections.emptyMap()); Script scriptTwo = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "get score value", Collections.emptyMap()); SearchResponse response = client().search( searchRequest().source( searchSource().query( functionScoreQuery( functionScoreQuery( functionScoreQuery(scriptFunction(scriptOne)), scriptFunction(scriptTwo)), scriptFunction(scriptTwo) ) ) ) ).actionGet(); assertSearchResponse(response); assertThat(response.getHits().getAt(0).getScore(), equalTo(1.0f)); } public void testScriptScoresWithAgg() throws IOException { createIndex(INDEX); index(INDEX, TYPE, "1", jsonBuilder().startObject().field("dummy_field", 1).endObject()); refresh(); Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "get score value", Collections.emptyMap()); SearchResponse response = client().search( searchRequest().source( searchSource() .query(functionScoreQuery(scriptFunction(script))) .aggregation(terms("score_agg").script(script)) ) ).actionGet(); assertSearchResponse(response); assertThat(response.getHits().getAt(0).getScore(), equalTo(1.0f)); assertThat(((Terms) response.getAggregations().asMap().get("score_agg")).getBuckets().get(0).getKeyAsString(), equalTo("1.0")); assertThat(((Terms) response.getAggregations().asMap().get("score_agg")).getBuckets().get(0).getDocCount(), is(1L)); } public void testMinScoreFunctionScoreBasic() throws IOException { float score = randomValueOtherThanMany((f) -> Float.compare(f, 0) < 0, ESTestCase::randomFloat); float minScore = randomValueOtherThanMany((f) -> Float.compare(f, 0) < 0, ESTestCase::randomFloat); index(INDEX, TYPE, jsonBuilder().startObject() .field("num", 2) .field("random_score", score) // Pass the random score as a document field so that it can be extracted in the script .endObject()); refresh(); ensureYellow(); Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['random_score']", Collections.emptyMap()); SearchResponse searchResponse = client().search( searchRequest().source(searchSource().query(functionScoreQuery(scriptFunction(script)).setMinScore(minScore))) ).actionGet(); if (score < minScore) { assertThat(searchResponse.getHits().getTotalHits().value, is(0L)); } else { assertThat(searchResponse.getHits().getTotalHits().value, is(1L)); } searchResponse = client().search( searchRequest().source(searchSource().query(functionScoreQuery(new MatchAllQueryBuilder(), new FilterFunctionBuilder[] { new FilterFunctionBuilder(scriptFunction(script)), new FilterFunctionBuilder(scriptFunction(script)) }).scoreMode(FunctionScoreQuery.ScoreMode.AVG).setMinScore(minScore))) ).actionGet(); if (score < minScore) { assertThat(searchResponse.getHits().getTotalHits().value, is(0L)); } else { assertThat(searchResponse.getHits().getTotalHits().value, is(1L)); } } public void testMinScoreFunctionScoreManyDocsAndRandomMinScore() throws IOException, ExecutionException, InterruptedException { List<IndexRequestBuilder> docs = new ArrayList<>(); int numDocs = randomIntBetween(1, 100); int scoreOffset = randomIntBetween(0, 2 * numDocs); int minScore = randomIntBetween(0, 2 * numDocs); for (int i = 0; i < numDocs; i++) { docs.add(client().prepareIndex(INDEX, TYPE, Integer.toString(i)).setSource("num", i + scoreOffset)); } indexRandom(true, docs); Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "return (doc['num'].value)", Collections.emptyMap()); int numMatchingDocs = numDocs + scoreOffset - minScore; if (numMatchingDocs < 0) { numMatchingDocs = 0; } if (numMatchingDocs > numDocs) { numMatchingDocs = numDocs; } SearchResponse searchResponse = client().search( searchRequest().source(searchSource().query(functionScoreQuery(scriptFunction(script)) .setMinScore(minScore)).size(numDocs))).actionGet(); assertMinScoreSearchResponses(numDocs, searchResponse, numMatchingDocs); searchResponse = client().search( searchRequest().source(searchSource().query(functionScoreQuery(new MatchAllQueryBuilder(), new FilterFunctionBuilder[] { new FilterFunctionBuilder(scriptFunction(script)), new FilterFunctionBuilder(scriptFunction(script)) }).scoreMode(FunctionScoreQuery.ScoreMode.AVG).setMinScore(minScore)).size(numDocs))).actionGet(); assertMinScoreSearchResponses(numDocs, searchResponse, numMatchingDocs); } protected void assertMinScoreSearchResponses(int numDocs, SearchResponse searchResponse, int numMatchingDocs) { assertSearchResponse(searchResponse); assertThat((int) searchResponse.getHits().getTotalHits().value, is(numMatchingDocs)); int pos = 0; for (int hitId = numDocs - 1; (numDocs - hitId) < searchResponse.getHits().getTotalHits().value; hitId--) { assertThat(searchResponse.getHits().getAt(pos).getId(), equalTo(Integer.toString(hitId))); pos++; } } /** make sure min_score works if functions is empty, see https://github.com/elastic/elasticsearch/issues/10253 */ public void testWithEmptyFunctions() throws IOException, ExecutionException, InterruptedException { assertAcked(prepareCreate("test")); index("test", "testtype", "1", jsonBuilder().startObject().field("text", "test text").endObject()); refresh(); SearchResponse termQuery = client().search( searchRequest().source( searchSource().explain(true).query( termQuery("text", "text")))).get(); assertSearchResponse(termQuery); assertThat(termQuery.getHits().getTotalHits().value, equalTo(1L)); float termQueryScore = termQuery.getHits().getAt(0).getScore(); for (CombineFunction combineFunction : CombineFunction.values()) { testMinScoreApplied(combineFunction, termQueryScore); } } protected void testMinScoreApplied(CombineFunction boostMode, float expectedScore) throws InterruptedException, ExecutionException { SearchResponse response = client().search( searchRequest().source( searchSource().explain(true).query( functionScoreQuery(termQuery("text", "text")).boostMode(boostMode).setMinScore(0.1f)))).get(); assertSearchResponse(response); assertThat(response.getHits().getTotalHits().value, equalTo(1L)); assertThat(response.getHits().getAt(0).getScore(), equalTo(expectedScore)); response = client().search( searchRequest().source( searchSource().explain(true).query( functionScoreQuery(termQuery("text", "text")).boostMode(boostMode).setMinScore(2f)))).get(); assertSearchResponse(response); assertThat(response.getHits().getTotalHits().value, equalTo(0L)); } }
/** * * murmurhash - Pure Java implementation of the Murmur Hash algorithms. * Copyright (c) 2014, Sandeep Gupta * * http://sangupta.com/projects/murmur * * 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.ogcs.utilities.math.murmur; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; /** * A pure Java implementation of the Murmur 3 hashing algorithm as presented * at <a href="https://sites.google.com/site/murmurhash/">Murmur Project</a> * * Code is ported from original C++ source at * <a href="https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp"> * MurmurHash3.cpp</a> * * @author sangupta * @since 1.0 */ public class Murmur3 implements MurmurConstants { private static final int X86_32_C1 = 0xcc9e2d51; private static final int X86_32_C2 = 0x1b873593; private static long X64_128_C1 = 0x87c37b91114253d5L; private static long X64_128_C2 = 0x4cf5ad432745937fL; public static long hash_x86_32(final String data) { return hash_x86_32(data, Charset.forName("utf-8"), DEFAULT_SEED); } public static long hash_x86_32(final String data, Charset charset, long seed) { byte[] bytes = data.getBytes(charset); return hash_x86_32(bytes, bytes.length, seed); } /** * Compute the Murmur3 hash as described in the original source code. * * @param data * the data that needs to be hashed * * @param length * the length of the data that needs to be hashed * * @param seed * the seed to use to compute the hash * * @return the computed hash value */ public static long hash_x86_32(final byte[] data, int length, long seed) { final int nblocks = length >> 2; long hash = seed; //---------- // body for(int i = 0; i < nblocks; i++) { final int i4 = i << 2; long k1 = (data[i4] & UNSIGNED_MASK); k1 |= (data[i4 + 1] & UNSIGNED_MASK) << 8; k1 |= (data[i4 + 2] & UNSIGNED_MASK) << 16; k1 |= (data[i4 + 3] & UNSIGNED_MASK) << 24; // int k1 = (data[i4] & 0xff) + ((data[i4 + 1] & 0xff) << 8) + ((data[i4 + 2] & 0xff) << 16) + ((data[i4 + 3] & 0xff) << 24); k1 = (k1 * X86_32_C1) & UINT_MASK; k1 = rotl32(k1, 15); k1 = (k1 * X86_32_C2) & UINT_MASK; hash ^= k1; hash = rotl32(hash,13); hash = (((hash * 5) & UINT_MASK) + 0xe6546b64l) & UINT_MASK; } //---------- // tail // Advance offset to the unprocessed tail of the data. int offset = (nblocks << 2); // nblocks * 2; long k1 = 0; switch (length & 3) { case 3: k1 ^= (data[offset + 2] << 16) & UINT_MASK; case 2: k1 ^= (data[offset + 1] << 8) & UINT_MASK; case 1: k1 ^= data[offset]; k1 = (k1 * X86_32_C1) & UINT_MASK; k1 = rotl32(k1, 15); k1 = (k1 * X86_32_C2) & UINT_MASK; hash ^= k1; } // ---------- // finalization hash ^= length; hash = fmix32(hash); return hash; } public static long[] hash_x64_128(final String data) { return hash_x64_128(data, Charset.forName("utf-8"), DEFAULT_SEED); } public static long[] hash_x64_128(final String data, Charset charset, long seed) { byte[] bytes = data.getBytes(charset); return hash_x64_128(bytes, bytes.length, seed); } /** * Compute the Murmur3 hash (128-bit version) as described in the original source code. * * @param data * the data that needs to be hashed * * @param length * the length of the data that needs to be hashed * * @param seed * the seed to use to compute the hash * * @return the computed hash value */ public static long[] hash_x64_128(final byte[] data, final int length, final long seed) { long h1 = seed; long h2 = seed; ByteBuffer buffer = ByteBuffer.wrap(data); buffer.order(ByteOrder.LITTLE_ENDIAN); while(buffer.remaining() >= 16) { long k1 = buffer.getLong(); long k2 = buffer.getLong(); h1 ^= mixK1(k1); h1 = Long.rotateLeft(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729; h2 ^= mixK2(k2); h2 = Long.rotateLeft(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5; } // ---------- // tail // Advance offset to the unprocessed tail of the data. // offset += (nblocks << 4); // nblocks * 16; buffer.compact(); buffer.flip(); final int remaining = buffer.remaining(); if(remaining > 0) { long k1 = 0; long k2 = 0; switch (buffer.remaining()) { case 15: k2 ^= (long) (buffer.get(14) & UNSIGNED_MASK) << 48; case 14: k2 ^= (long) (buffer.get(13) & UNSIGNED_MASK) << 40; case 13: k2 ^= (long) (buffer.get(12) & UNSIGNED_MASK) << 32; case 12: k2 ^= (long) (buffer.get(11) & UNSIGNED_MASK) << 24; case 11: k2 ^= (long) (buffer.get(10) & UNSIGNED_MASK) << 16; case 10: k2 ^= (long) (buffer.get(9) & UNSIGNED_MASK) << 8; case 9: k2 ^= (long) (buffer.get(8) & UNSIGNED_MASK); case 8: k1 ^= buffer.getLong(); break; case 7: k1 ^= (long) (buffer.get(6) & UNSIGNED_MASK) << 48; case 6: k1 ^= (long) (buffer.get(5) & UNSIGNED_MASK) << 40; case 5: k1 ^= (long) (buffer.get(4) & UNSIGNED_MASK) << 32; case 4: k1 ^= (long) (buffer.get(3) & UNSIGNED_MASK) << 24; case 3: k1 ^= (long) (buffer.get(2) & UNSIGNED_MASK) << 16; case 2: k1 ^= (long) (buffer.get(1) & UNSIGNED_MASK) << 8; case 1: k1 ^= (long) (buffer.get(0) & UNSIGNED_MASK); break; default: throw new AssertionError("Code should not reach here!"); } // mix h1 ^= mixK1(k1); h2 ^= mixK2(k2); } // ---------- // finalization h1 ^= length; h2 ^= length; h1 += h2; h2 += h1; h1 = fmix64(h1); h2 = fmix64(h2); h1 += h2; h2 += h1; return (new long[] { h1, h2 }); } private static long mixK1(long k1) { k1 *= X64_128_C1; k1 = Long.rotateLeft(k1, 31); k1 *= X64_128_C2; return k1; } private static long mixK2(long k2) { k2 *= X64_128_C2; k2 = Long.rotateLeft(k2, 33); k2 *= X64_128_C1; return k2; } /** * Rotate left for 32 bits. * * @param original * @param shift * @return */ private static long rotl32(long original, int shift) { return ((original << shift) & UINT_MASK) | ((original >>> (32 - shift)) & UINT_MASK); } /** * Rotate left for 64 bits. * * @param original * @param shift * @return */ /** * fmix function for 32 bits. * * @param h * @return */ private static long fmix32(long h) { h ^= (h >> 16) & UINT_MASK; h = (h * 0x85ebca6bl) & UINT_MASK; h ^= (h >> 13) & UINT_MASK; h = (h * 0xc2b2ae35) & UINT_MASK; h ^= (h >> 16) & UINT_MASK; return h; } /** * fmix function for 64 bits. * * @param k * @return */ private static long fmix64(long k) { k ^= k >>> 33; k *= 0xff51afd7ed558ccdL; k ^= k >>> 33; k *= 0xc4ceb9fe1a85ec53L; k ^= k >>> 33; return k; } }
/* * Copyright (C) 2015-2017 akha, a.k.a. Alexander Kharitonov * * 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 akha.yakhont.callback.lifecycle; import akha.yakhont.Core; import akha.yakhont.Core.Utils; import akha.yakhont.CoreLogger; import akha.yakhont.callback.BaseCallbacks.BaseCacheCallbacks; import akha.yakhont.callback.BaseCallbacks.BaseLifecycleProceed; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import android.view.inputmethod.InputMethodManager; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /** * Extends the {@link BaseLifecycleProceed} class to provide the {@link Activity} lifecycle support. * For the moment supported lifecycle is similar to the {@link android.app.Application.ActivityLifecycleCallbacks} * but will likely expand in future releases. * * @see BaseActivityCallbacks * * @author akha */ public abstract class BaseActivityLifecycleProceed extends BaseLifecycleProceed { private static final String FORMAT_VALUE = "%s == %d (%s)"; private static final AtomicInteger sResumed = new AtomicInteger(); private static final AtomicInteger sPaused = new AtomicInteger(); private static final AtomicInteger sStarted = new AtomicInteger(); private static final AtomicInteger sStopped = new AtomicInteger(); private static final CurrentActivityHelper sActivity = new CurrentActivityHelper(); /** * Initialises a newly created {@code BaseActivityLifecycleProceed} object. */ @SuppressWarnings("WeakerAccess") public BaseActivityLifecycleProceed() { } /** * Returns the current {@code Activity} (if any). * * @return The current {@code Activity} (or null) */ public static Activity getCurrentActivity() { return sActivity.get(); } private static String getActivityName(@NonNull final Activity activity) { return Utils.getActivityName(activity); } private static void log(@NonNull final String info, final int value, @NonNull final String name) { CoreLogger.log(String.format(CoreLogger.getLocale(), FORMAT_VALUE, info, value, name)); } /** @exclude */ @SuppressWarnings({"JavaDoc", "WeakerAccess"}) protected static void log(@NonNull final Activity activity, @NonNull final String info) { log(getActivityName(activity), info); } /** @exclude */ @SuppressWarnings({"JavaDoc", "WeakerAccess"}) protected static void update(@NonNull final Activity activity, @NonNull final AtomicInteger value, @NonNull final String info) { log(info, value.incrementAndGet(), getActivityName(activity)); } /** @exclude */ @SuppressWarnings("JavaDoc") public static boolean isVisible() { return sStarted.get() > sStopped.get(); } /** @exclude */ @SuppressWarnings("JavaDoc") public static boolean isInForeground() { return sResumed.get() > sPaused.get(); } //////////////////////////////////////////////////////////////////////////////////////////// /** * The {@link Activity} lifecycle. */ public enum ActivityLifecycle { /** The activity is first created. */ CREATED, /** The activity is becoming visible to the user. */ STARTED, /** The activity will start interacting with the user. */ RESUMED, /** The system is about to start resuming a previous activity. */ PAUSED, /** The activity is no longer visible to the user. */ STOPPED, /** The activity is destroyed. */ DESTROYED, /** Called to retrieve per-instance state from an activity before being killed. */ SAVE_INSTANCE_STATE } private static final Map<String, ActivityLifecycle> CALLBACKS; static { final Map<String, ActivityLifecycle> callbacks = new HashMap<>(); callbacks.put("onActivityCreated", ActivityLifecycle.CREATED); callbacks.put("onActivityStarted", ActivityLifecycle.STARTED); callbacks.put("onActivityResumed", ActivityLifecycle.RESUMED); callbacks.put("onActivityPaused", ActivityLifecycle.PAUSED); callbacks.put("onActivityStopped", ActivityLifecycle.STOPPED); callbacks.put("onActivityDestroyed", ActivityLifecycle.DESTROYED); callbacks.put("onActivitySaveInstanceState", ActivityLifecycle.SAVE_INSTANCE_STATE); CALLBACKS = Collections.unmodifiableMap(callbacks); } private static final Map<BaseActivityCallbacks, Set<ActivityLifecycle>> sCallbacks = Utils.newMap(); /** * Returns the collection of registered callbacks handlers. * * @return The registered callbacks handlers */ public static Collection<BaseActivityCallbacks> getCallbacks() { return sCallbacks.keySet(); } /** * Registers the callbacks handler. * * @param callbacks * The callbacks handler to register * * @return {@code true} if the callbacks handler was successfully registered, {@code false} otherwise */ @SuppressWarnings({"UnusedReturnValue", "ConstantConditions", "SameReturnValue"}) public static boolean register(@NonNull final BaseActivityCallbacks callbacks) { return register(sCallbacks, callbacks, ActivityLifecycle.class, CALLBACKS); } /** * Unregisters the callbacks handler. * * @param callbacksClass * The class of the callbacks handler to unregister * * @return {@code true} if the callbacks handler was successfully unregistered, {@code false} otherwise */ @SuppressWarnings("unused") public static boolean unregister(@NonNull final Class<? extends BaseActivityCallbacks> callbacksClass) { return unregister(sCallbacks, callbacksClass); } /** * Applies registered callbacks to the given activity. * * @param lifeCycle * The activity state * * @param activity * The activity to apply callbacks to * * @param state * The additional information concerning the activity state */ @SuppressWarnings("WeakerAccess") protected static void apply(@NonNull final ActivityLifecycle lifeCycle, @NonNull final Activity activity, final Bundle state) { switch (lifeCycle) { case STARTED: case RESUMED: sActivity.set(activity); break; case DESTROYED: sActivity.clear(activity); break; } final Boolean created; switch (lifeCycle) { case CREATED: created = Boolean.TRUE; break; case DESTROYED: created = Boolean.FALSE; break; default: created = null; break; } for (final BaseActivityCallbacks callbacks: sCallbacks.keySet()) apply(sCallbacks, callbacks, created, lifeCycle, activity, new Runnable() { @Override public void run() { apply(callbacks, lifeCycle, activity, state); } }); } private static void apply(@NonNull final BaseActivityCallbacks callbacks, @NonNull final ActivityLifecycle lifeCycle, @NonNull final Activity activity, final Bundle state) { CoreLogger.log(CoreLogger.Level.INFO, "proceeding: lifeCycle " + lifeCycle + ", " + callbacks.getClass().getName()); switch (lifeCycle) { case CREATED: callbacks.onActivityCreated (activity, state); break; case STARTED: callbacks.onActivityStarted (activity ); break; case RESUMED: callbacks.onActivityResumed (activity ); break; case PAUSED: callbacks.onActivityPaused (activity ); break; case STOPPED: callbacks.onActivityStopped (activity ); break; case DESTROYED: callbacks.onActivityDestroyed (activity ); break; case SAVE_INSTANCE_STATE: callbacks.onActivitySaveInstanceState(activity, state); break; default: // should never happen CoreLogger.logError("unknown lifeCycle state " + lifeCycle); break; } } //////////////////////////////////////////////////////////////////////////////////////////////// private static final String PREFIX = "subject to call by weaver - "; private static boolean sActive; /** * Activates Yakhont Weaver (normally on devices with API version &lt; * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH ICE_CREAM_SANDWICH}). * * @param active * {@code true} to activate Yakhont Weaver, {@code false} otherwise */ @SuppressWarnings("SameParameterValue") public static void setActive(final boolean active) { sActive = active; } /** * Called by the Yakhont Weaver to apply registered callbacks to the given activity. * The lifecycle state is {@link ActivityLifecycle#CREATED CREATED}. * * @param activity * The activity to apply callbacks to * * @param savedInstanceState * The additional information concerning the activity state */ @SuppressWarnings("unused") public static void onCreated(@NonNull final Activity activity, final Bundle savedInstanceState) { if (!sActive) return; log(activity, PREFIX + "onCreated callback"); apply(ActivityLifecycle.CREATED, activity, savedInstanceState); } /** * Called by the Yakhont Weaver to apply registered callbacks to the given activity. * The lifecycle state is {@link ActivityLifecycle#DESTROYED DESTROYED}. * * @param activity * The activity to apply callbacks to */ @SuppressWarnings("unused") public static void onDestroyed(@NonNull final Activity activity) { if (!sActive) return; log(activity, PREFIX + "onDestroyed callback"); apply(ActivityLifecycle.DESTROYED, activity, null /* ignored */); } /** * Called by the Yakhont Weaver to apply registered callbacks to the given activity. * The lifecycle state is {@link ActivityLifecycle#SAVE_INSTANCE_STATE SAVE_INSTANCE_STATE}. * * @param activity * The activity to apply callbacks to * * @param outState * The additional information concerning the activity state */ @SuppressWarnings("unused") public static void onSaveInstanceState(@NonNull final Activity activity, final Bundle outState) { if (!sActive) return; log(activity, PREFIX + "onSaveInstanceState callback"); apply(ActivityLifecycle.SAVE_INSTANCE_STATE, activity, outState); } /** * Called by the Yakhont Weaver to apply registered callbacks to the given activity. * The lifecycle state is {@link ActivityLifecycle#RESUMED RESUMED}. * * @param activity * The activity to apply callbacks to */ @SuppressWarnings("unused") public static void onResumed(@NonNull final Activity activity) { if (!sActive) return; update(activity, sResumed, PREFIX + "sResumed"); apply(ActivityLifecycle.RESUMED, activity, null /* ignored */); } /** * Called by the Yakhont Weaver to apply registered callbacks to the given activity. * The lifecycle state is {@link ActivityLifecycle#PAUSED PAUSED}. * * @param activity * The activity to apply callbacks to */ @SuppressWarnings("unused") public static void onPaused(@NonNull final Activity activity) { if (!sActive) return; update(activity, sPaused, PREFIX + "sPaused"); apply(ActivityLifecycle.PAUSED, activity, null /* ignored */); } /** * Called by the Yakhont Weaver to apply registered callbacks to the given activity. * The lifecycle state is {@link ActivityLifecycle#STARTED STARTED}. * * @param activity * The activity to apply callbacks to */ @SuppressWarnings("unused") public static void onStarted(@NonNull final Activity activity) { if (!sActive) return; update(activity, sStarted, PREFIX + "sStarted"); apply(ActivityLifecycle.STARTED, activity, null /* ignored */); } /** * Called by the Yakhont Weaver to apply registered callbacks to the given activity. * The lifecycle state is {@link ActivityLifecycle#STOPPED STOPPED}. * * @param activity * The activity to apply callbacks to */ @SuppressWarnings("unused") public static void onStopped(@NonNull final Activity activity) { if (!sActive) return; update(activity, sStopped, PREFIX + "sStopped"); apply(ActivityLifecycle.STOPPED, activity, null /* ignored */); } //////////////////////////////////////////////////////////////////////////////////////////////// /** * Extends the {@link BaseActivityLifecycleProceed} class to use on devices with * API version >= {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static class ActivityLifecycleProceed extends BaseActivityLifecycleProceed implements Application.ActivityLifecycleCallbacks { /** * Initialises a newly created {@code ActivityLifecycleProceed} object. */ public ActivityLifecycleProceed() { } /** * Please refer to the base method description. */ @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { log(activity, "onActivityCreated callback"); apply(ActivityLifecycle.CREATED, activity, savedInstanceState); } /** * Please refer to the base method description. */ @Override public void onActivityDestroyed(Activity activity) { log(activity, "onActivityDestroyed callback"); apply(ActivityLifecycle.DESTROYED, activity, null /* ignored */); } /** * Please refer to the base method description. */ @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { log(activity, "onActivitySaveInstanceState callback"); apply(ActivityLifecycle.SAVE_INSTANCE_STATE, activity, outState); } /** * Please refer to the base method description. */ @Override public void onActivityResumed(Activity activity) { update(activity, sResumed, "sResumed"); apply(ActivityLifecycle.RESUMED, activity, null /* ignored */); } /** * Please refer to the base method description. */ @Override public void onActivityPaused(Activity activity) { update(activity, sPaused, "sPaused"); apply(ActivityLifecycle.PAUSED, activity, null /* ignored */); } /** * Please refer to the base method description. */ @Override public void onActivityStarted(Activity activity) { update(activity, sStarted, "sStarted"); apply(ActivityLifecycle.STARTED, activity, null /* ignored */); } /** * Please refer to the base method description. */ @Override public void onActivityStopped(Activity activity) { update(activity, sStopped, "sStopped"); apply(ActivityLifecycle.STOPPED, activity, null /* ignored */); } } //////////////////////////////////////////////////////////////////////////////////////////////// /** * Extends the {@link BaseCacheCallbacks} class to provide the activity life cycle callbacks support. * For the moment supported callbacks are similar to the {@link android.app.Application.ActivityLifecycleCallbacks} * but will likely expand in future releases. * <br>By default all callbacks are empty. * * <p>Usage example (for more examples please refer to {@link akha.yakhont.callback.BaseCallbacks general Activity}, * {@yakhont.link BaseFragmentLifecycleProceed.BaseFragmentCallbacks Fragment} * and {@link akha.yakhont.callback.BaseCallbacks#proceed(Object, Class) simple Activity} ones): * * <p><pre style="background-color: silver; border: thin solid black;"> * package com.mypackage; * * public class MyActivityCallbacks extends BaseCallbacks.BaseActivityCallbacks { * * &#064;Override * public void onActivityCreated(Activity activity, Bundle savedInstanceState) { * * // your code here (NOTE: you don't have to call activity.onActivityCreated() - * // it's already done by the Weaver) * } * } * </pre> * * Annotate necessary Activities: * * <p><pre style="background-color: silver; border: thin solid black;"> * import akha.yakhont.callback.annotation.CallbacksInherited; * * &#064;CallbacksInherited(com.mypackage.MyActivityCallbacks.class) * public class MyActivity extends Activity { * ... * } * </pre> * * And register your callbacks handler (see also {@link akha.yakhont.Core}): * * <p><pre style="background-color: silver; border: thin solid black;"> * import akha.yakhont.Core; * * import com.mypackage.MyActivityCallbacks; * * public class MyApplication extends Application { * * &#064;Override * public void onCreate() { * super.onCreate(); * ... * Core.init(this); * * BaseActivityLifecycleProceed.register(new MyActivityCallbacks()); * // OR * // BaseActivityLifecycleProceed.register( * // (BaseActivityCallbacks) new MyActivityCallbacks().setForceProceed(true)); * // to apply callback handlers to ALL activities (annotated or not) * } * } * </pre> * * Please refer to the {@link akha.yakhont.callback.BaseCallbacks} for more details. * * @see ActivityLifecycle */ public static abstract class BaseActivityCallbacks extends BaseCacheCallbacks<Activity> { /** * Initialises a newly created {@code BaseActivityCallbacks} object. */ public BaseActivityCallbacks() { } /** The callback for {@link Activity#onCreate}. */ @SuppressWarnings({"EmptyMethod", "UnusedParameters", "WeakerAccess"}) public void onActivityCreated (@NonNull final Activity activity, final Bundle savedInstanceState) {} /** The callback for {@link Activity#onStart}. */ @SuppressWarnings({"EmptyMethod", "UnusedParameters", "WeakerAccess"}) public void onActivityStarted (@NonNull final Activity activity ) {} /** The callback for {@link Activity#onResume}. */ @SuppressWarnings({"EmptyMethod", "UnusedParameters", "WeakerAccess"}) public void onActivityResumed (@NonNull final Activity activity ) {} /** The callback for {@link Activity#onPause}. */ @SuppressWarnings({"EmptyMethod", "UnusedParameters", "WeakerAccess"}) public void onActivityPaused (@NonNull final Activity activity ) {} /** The callback for {@link Activity#onStop}. */ @SuppressWarnings({"EmptyMethod", "UnusedParameters", "WeakerAccess"}) public void onActivityStopped (@NonNull final Activity activity ) {} /** The callback for {@link Activity#onDestroy}. */ @SuppressWarnings({"EmptyMethod", "UnusedParameters", "WeakerAccess"}) public void onActivityDestroyed (@NonNull final Activity activity ) {} /** The callback for {@link Activity#onSaveInstanceState}. */ @SuppressWarnings({"EmptyMethod", "UnusedParameters", "WeakerAccess"}) public void onActivitySaveInstanceState(@NonNull final Activity activity, final Bundle outState ) {} } /** @exclude */@SuppressWarnings("JavaDoc") public static class ValidateActivityCallbacks extends BaseActivityCallbacks { } /** * Hides the keyboard when activity paused. */ public static class HideKeyboardCallbacks extends BaseActivityCallbacks { /** * Initialises a newly created {@code HideKeyboardCallbacks} object. */ public HideKeyboardCallbacks() { } /** * Please refer to the base method description. */ @Override public void onActivityPaused(@NonNull final Activity activity) { hideKeyboard(activity); } /** @exclude */ @SuppressWarnings({"JavaDoc", "WeakerAccess"}) public static void hideKeyboard(@NonNull final Activity activity) { final InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager == null) { CoreLogger.logWarning("can not get InputMethodManager"); return; } View currentFocus = activity.getWindow().getCurrentFocus(); if (currentFocus == null) currentFocus = activity.getWindow().getDecorView().findFocus(); if (currentFocus != null) inputMethodManager.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0); else CoreLogger.logWarning("can not get current focus"); } } /** * Sets the screen orientation. */ public static class OrientationCallbacks extends BaseActivityCallbacks { /** * Initialises a newly created {@code OrientationCallbacks} object. */ public OrientationCallbacks() { } /** * Please refer to the base method description. */ @Override public void onActivityCreated(@NonNull final Activity activity, final Bundle savedInstanceState) { setOrientation(activity); } /** @exclude */ @SuppressWarnings({"JavaDoc", "WeakerAccess"}) public static void setOrientation(@NonNull final Activity activity) { final Core.Orientation orientation = Utils.getOrientation(activity); switch (orientation) { case LANDSCAPE: CoreLogger.log("about to set orientation to " + orientation.name()); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; case PORTRAIT: CoreLogger.log("about to set orientation to " + orientation.name()); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; case UNSPECIFIED: CoreLogger.logWarning("unspecified orientation " + orientation.name()); break; default: CoreLogger.logError("unknown orientation " + orientation.name()); break; } } } /** @exclude */ @SuppressWarnings("JavaDoc") public static class CurrentActivityHelper { private final AtomicReference<WeakReference<Activity>> mActivity = new AtomicReference<>(); private void setActivity(final Activity activity) { mActivity.set(new WeakReference<>(activity)); } public void set(final Activity activity) { if (!check(activity)) return; if (get(true) != activity) setActivity(activity); } public void clear(final Activity activity) { if (!check(activity)) return; if (get(true) == activity) setActivity(null); } public Activity get() { return get(false); } private Activity get(final boolean silent) { final WeakReference<Activity> weakReference = mActivity.get(); final Activity activity = weakReference == null ? null: weakReference.get(); if (!silent) check(activity); return activity; } private boolean check(final Activity activity) { if (activity == null) CoreLogger.logError("activity == null"); return activity != null; } } }
/* * Copyright (c) 2015, University of Oslo * * 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 the HISP project 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 org.hisp.dhis.android.sdk.ui.adapters.rows.dataentry; import android.app.DatePickerDialog; import android.content.Context; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.DatePicker; import android.widget.ImageButton; import android.widget.TextView; import org.hisp.dhis.android.sdk.R; import org.hisp.dhis.android.sdk.persistence.Dhis2Application; import org.hisp.dhis.android.sdk.persistence.models.DataValue; import org.hisp.dhis.android.sdk.persistence.models.Enrollment; import org.hisp.dhis.android.sdk.ui.adapters.rows.events.OnDetailedInfoButtonClick; import org.hisp.dhis.android.sdk.ui.fragments.dataentry.RowValueChangedEvent; import org.joda.time.DateTime; import org.joda.time.LocalDate; import static android.text.TextUtils.isEmpty; public class EnrollmentDatePickerRow extends Row { private static final String EMPTY_FIELD = ""; private static final String DATE_FORMAT = "YYYY-MM-dd"; private final Enrollment mEnrollment; private final String mEnrollmentDate; private final String mIncidentDate; public EnrollmentDatePickerRow(String label, Enrollment enrollment, String enrollmentDate, String incidentDate) { if(enrollmentDate == null && incidentDate == null) throw new IllegalArgumentException("Enrollment date or incident date needs to be supplied for this row"); else if(enrollmentDate != null && incidentDate != null) throw new IllegalArgumentException("You should only supply either enrollment date or incident date"); mLabel = label; mEnrollment = enrollment; this.mEnrollmentDate = enrollmentDate; this.mIncidentDate = incidentDate; checkNeedsForDescriptionButton(); } @Override public View getView(FragmentManager fragmentManager, LayoutInflater inflater, View convertView, ViewGroup container) { View view; DatePickerRowHolder holder; if (convertView != null && convertView.getTag() instanceof DatePickerRowHolder) { view = convertView; holder = (DatePickerRowHolder) view.getTag(); } else { View root = inflater.inflate( R.layout.listview_row_event_datepicker, container, false); detailedInfoButton = root.findViewById(R.id.detailed_info_button_layout); // need to keep reference holder = new DatePickerRowHolder(root, inflater.getContext(), detailedInfoButton); root.setTag(holder); view = root; } if (!isEditable()) { holder.clearButton.setEnabled(false); holder.textLabel.setEnabled(false); //change color holder.pickerInvoker.setEnabled(false); } else { holder.clearButton.setEnabled(true); holder.textLabel.setEnabled(true); holder.pickerInvoker.setEnabled(true); } holder.detailedInfoButton.setOnClickListener(new OnDetailedInfoButtonClick(this)); holder.updateViews(mLabel, mEnrollment, mEnrollmentDate, mIncidentDate); if(isDetailedInfoButtonHidden()) holder.detailedInfoButton.setVisibility(View.INVISIBLE); return view; } @Override public int getViewType() { return DataEntryRowTypes.ENROLLMENT_DATE.ordinal(); } private class DatePickerRowHolder { final TextView textLabel; final TextView pickerInvoker; final ImageButton clearButton; final View detailedInfoButton; final DateSetListener dateSetListener; final OnEditTextClickListener invokerListener; final ClearButtonListener clearButtonListener; public DatePickerRowHolder(View root, Context context, View detailedInfoButton) { textLabel = (TextView) root.findViewById(R.id.text_label); pickerInvoker = (TextView) root.findViewById(R.id.date_picker_text_view); clearButton = (ImageButton) root.findViewById(R.id.clear_text_view); this.detailedInfoButton = detailedInfoButton; dateSetListener = new DateSetListener(pickerInvoker); invokerListener = new OnEditTextClickListener(context, dateSetListener); clearButtonListener = new ClearButtonListener(pickerInvoker); clearButton.setOnClickListener(clearButtonListener); pickerInvoker.setOnClickListener(invokerListener); } public void updateViews(String label, Enrollment enrollment, String enrollmentDate, String incidentDate ) { dateSetListener.setEnrollment(enrollment); clearButtonListener.setEnrollment(enrollment); String eventDate = null; if(enrollment != null && enrollmentDate != null && !isEmpty(enrollmentDate)) { dateSetListener.setEnrollmentDate(enrollmentDate); clearButtonListener.setEnrollmentDate(enrollmentDate); DateTime enrollmentDateTime = DateTime.parse(enrollmentDate); eventDate = enrollmentDateTime.toString(DATE_FORMAT); } else if(enrollment != null && incidentDate != null && !isEmpty(incidentDate)) { dateSetListener.setIncidentDate(incidentDate); clearButtonListener.setIncidentDate(incidentDate); DateTime incidentDateTime= DateTime.parse(incidentDate); eventDate = incidentDateTime.toString(DATE_FORMAT); } textLabel.setText(label); pickerInvoker.setText(eventDate); } } private static class OnEditTextClickListener implements View.OnClickListener { private final Context context; private final DateSetListener listener; public OnEditTextClickListener(Context context, DateSetListener listener) { this.context = context; this.listener = listener; } @Override public void onClick(View view) { LocalDate currentDate = new LocalDate(); DatePickerDialog picker = new DatePickerDialog(context, listener, currentDate.getYear(), currentDate.getMonthOfYear() - 1, currentDate.getDayOfMonth()); picker.getDatePicker().setMaxDate(DateTime.now().getMillis()); picker.show(); } } private static class ClearButtonListener implements View.OnClickListener { private final TextView textView; private Enrollment enrollment; private String enrollmentDate; private String incidentDate; public ClearButtonListener(TextView textView) { this.textView = textView; } public void setEnrollment(Enrollment enrollment) { this.enrollment = enrollment; } public void setEnrollmentDate(String enrollmentDate) { this.enrollmentDate = enrollmentDate; } public void setIncidentDate(String incidentDate) { this.incidentDate = incidentDate; } @Override public void onClick(View view) { textView.setText(EMPTY_FIELD); if(enrollmentDate != null) enrollment.setDateOfEnrollment(EMPTY_FIELD); else if(incidentDate != null) enrollment.setDateOfIncident(EMPTY_FIELD); } } private class DateSetListener implements DatePickerDialog.OnDateSetListener { private static final String DATE_FORMAT = "YYYY-MM-dd"; private final TextView textView; private Enrollment enrollment; private DataValue value; private String enrollmentDate; private String incidentDate; public DateSetListener(TextView textView) { this.textView = textView; } public void setEnrollment(Enrollment enrollment) { this.enrollment = enrollment; } public void setEnrollmentDate(String enrollmentDate) { this.enrollmentDate = enrollmentDate; } public void setIncidentDate(String incidentDate) { this.incidentDate = incidentDate; } @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { LocalDate date = new LocalDate(year, monthOfYear + 1, dayOfMonth); if (value == null) value = new DataValue(); if (enrollmentDate != null) value.setValue(enrollmentDate); else if(incidentDate != null) value.setValue(incidentDate); String newValue = date.toString(DATE_FORMAT); textView.setText(newValue); if (!newValue.equals(value.getValue())) { value.setValue(newValue); if(enrollmentDate != null) enrollment.setDateOfEnrollment(value.getValue()); else if(incidentDate != null) enrollment.setDateOfIncident(value.getValue()); Dhis2Application.getEventBus().post(new RowValueChangedEvent(value, DataEntryRowTypes.ENROLLMENT_DATE.toString())); } } } }
/* * JBoss, Home of Professional Open Source * Copyright 2009 Red Hat Inc. and/or its affiliates and other contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.arquillian.container.impl.client.deployment; import java.io.File; import java.util.List; import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor; import org.jboss.arquillian.container.spi.client.container.DeployableContainer; import org.jboss.arquillian.container.spi.client.deployment.DeploymentDescription; import org.jboss.arquillian.container.spi.client.deployment.TargetDescription; import org.jboss.arquillian.container.spi.event.container.BeforeDeploy; import org.jboss.arquillian.container.test.AbstractContainerTestBase; import org.jboss.arquillian.core.api.annotation.ApplicationScoped; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.descriptor.api.Descriptors; import org.jboss.shrinkwrap.descriptor.api.webapp30.WebAppDescriptor; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; /** * Verify the behavior of the ArchiveDeploymentExporter * * @author <a href="mailto:aslak@redhat.com">Aslak Knutsen</a> * @version $Revision: $ */ @RunWith(MockitoJUnitRunner.class) public class ArchiveDeploymentExporterTestCase extends AbstractContainerTestBase { /** * */ private static final String ARQUILLIAN_DEPLOYMENT_EXPORT_PATH = "arquillian.deploymentExportPath"; private static final String ARQUILLIAN_DEPLOYMENT_EXPORT_EXPLODED = "arquillian.deploymentExportExploded"; private static final String TARGET_NAME = "test.jar"; private static final String DEPLOYMENT_NAME = "test.jar"; private static final String ARCHIVE_NAME = "test.jar"; private static final String EXPORT_PATH = "target/"; @Mock private DeployableContainer<?> deployableContainer; private DeploymentDescription deployment; @Override protected void addExtensions(List<Class<?>> extensions) { extensions.add(ArchiveDeploymentExporter.class); } @Before public void createDeployment() { Archive<?> archive = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME).addClass(getClass()); deployment = new DeploymentDescription(DEPLOYMENT_NAME, archive); deployment.setTarget(new TargetDescription(TARGET_NAME)); deployment.setTestableArchive(archive); } @Test public void shouldHandleNoConfigurationInContext() throws Exception { fire(new BeforeDeploy(deployableContainer, deployment)); fileShouldExist(false); } @Test public void shouldExportIfExportPathSystemPropertyIsSet() throws Exception { System.setProperty(ARQUILLIAN_DEPLOYMENT_EXPORT_PATH, EXPORT_PATH); try { bind(ApplicationScoped.class, ArquillianDescriptor.class, Descriptors.create(ArquillianDescriptor.class)); fire(new BeforeDeploy(deployableContainer, deployment)); fileShouldExist(true); } finally { System.setProperty(ARQUILLIAN_DEPLOYMENT_EXPORT_PATH, ""); } } @Test public void shouldNotExportIfDeploymentExportPathNotSet() throws Exception { bind(ApplicationScoped.class, ArquillianDescriptor.class, Descriptors.create(ArquillianDescriptor.class)); fire(new BeforeDeploy(deployableContainer, deployment)); fileShouldExist(false); } @Test public void shouldNotExportedIfDeploymentIsNotArchive() throws Exception { bind(ApplicationScoped.class, ArquillianDescriptor.class, Descriptors.create(ArquillianDescriptor.class).engine() .deploymentExportPath(EXPORT_PATH)); deployment = new DeploymentDescription(DEPLOYMENT_NAME, Descriptors.create(WebAppDescriptor.class)); deployment.setTarget(new TargetDescription(TARGET_NAME)); fire(new BeforeDeploy(deployableContainer, deployment)); fileShouldExist(false); } @Test public void shouldBeExportedWhenDeploymentExportPathIsSet() throws Exception { bind(ApplicationScoped.class, ArquillianDescriptor.class, Descriptors.create(ArquillianDescriptor.class).engine() .deploymentExportPath(EXPORT_PATH)); fire(new BeforeDeploy(deployableContainer, deployment)); fileShouldExist(true); } @Test public void shouldBeExportedExplodedWhenDeploymentExportExplodedIsSet() throws Exception { bind(ApplicationScoped.class, ArquillianDescriptor.class, Descriptors.create(ArquillianDescriptor.class).engine() .deploymentExportPath(EXPORT_PATH) .deploymentExportExploded(true)); fire(new BeforeDeploy(deployableContainer, deployment)); directoryShouldExist(); } @Test public void shouldBeDeleteAlreadyExportedDeploymentAndExportExplodedWhenDeploymentExportExplodedIsSet() throws Exception { // given - To create exploded deployment bind(ApplicationScoped.class, ArquillianDescriptor.class, Descriptors.create(ArquillianDescriptor.class).engine() .deploymentExportPath(EXPORT_PATH) .deploymentExportExploded(false)); fire(new BeforeDeploy(deployableContainer, deployment)); // when bind(ApplicationScoped.class, ArquillianDescriptor.class, Descriptors.create(ArquillianDescriptor.class).engine() .deploymentExportPath(EXPORT_PATH) .deploymentExportExploded(true)); fire(new BeforeDeploy(deployableContainer, deployment)); // then directoryShouldExist(); } @Test public void shouldBeDeleteAlreadyExplodedDeploymentAndExportDeploymentWhenDeploymentExportIsNotSet() throws Exception { // given - To export deployment archive bind(ApplicationScoped.class, ArquillianDescriptor.class, Descriptors.create(ArquillianDescriptor.class).engine() .deploymentExportPath(EXPORT_PATH) .deploymentExportExploded(true)); fire(new BeforeDeploy(deployableContainer, deployment)); // when bind(ApplicationScoped.class, ArquillianDescriptor.class, Descriptors.create(ArquillianDescriptor.class).engine() .deploymentExportPath(EXPORT_PATH) .deploymentExportExploded(false)); fire(new BeforeDeploy(deployableContainer, deployment)); // then fileShouldExist(true); } @Test public void shouldExportExplodedIfExportExplodedSystemPropertyIsSet() throws Exception { System.setProperty(ARQUILLIAN_DEPLOYMENT_EXPORT_PATH, EXPORT_PATH); System.setProperty(ARQUILLIAN_DEPLOYMENT_EXPORT_EXPLODED, "true"); try { bind(ApplicationScoped.class, ArquillianDescriptor.class, Descriptors.create(ArquillianDescriptor.class)); fire(new BeforeDeploy(deployableContainer, deployment)); fileShouldExist(true); } finally { System.setProperty(ARQUILLIAN_DEPLOYMENT_EXPORT_PATH, ""); System.setProperty(ARQUILLIAN_DEPLOYMENT_EXPORT_EXPLODED, ""); } } private void fileShouldExist(boolean bol) { File file = new File(EXPORT_PATH + TARGET_NAME + "_" + DEPLOYMENT_NAME + "_" + ARCHIVE_NAME); try { Assert.assertEquals("File exists", bol, file.exists()); if (bol) { Assert.assertTrue("File is a file", file.isFile()); } } finally { delete(file); } } private void directoryShouldExist() { File file = new File(EXPORT_PATH + TARGET_NAME + "_" + DEPLOYMENT_NAME + "_" + ARCHIVE_NAME); try { Assert.assertTrue("File exists", file.exists()); Assert.assertTrue("File is a directory", file.isDirectory()); } finally { delete(file); } } private void delete(File file) { if (!file.exists()) { return; } if (file.isDirectory()) { for (File sub : file.listFiles()) { delete(sub); } } file.delete(); } }
package li.strolch.utils; import static java.util.Collections.emptySet; import static li.strolch.utils.collections.SynchronizedCollections.synchronizedMapOfSets; import static li.strolch.utils.helper.ExceptionHelper.formatException; import static li.strolch.utils.helper.ExceptionHelper.getExceptionMessageWithCauses; import static li.strolch.utils.helper.StringHelper.EMPTY; import static li.strolch.utils.helper.StringHelper.isEmpty; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.CodeSource; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import li.strolch.utils.collections.MapOfMaps; import li.strolch.utils.collections.MapOfSets; import li.strolch.utils.collections.TypedTuple; import li.strolch.utils.dbc.DBC; import li.strolch.utils.helper.StringHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class I18nMessage { private static final Logger logger = LoggerFactory.getLogger(I18nMessage.class); private static MapOfMaps<String, Locale, ResourceBundle> bundleMap; private static final MapOfSets<String, String> missingKeysMap = synchronizedMapOfSets(new MapOfSets<>()); private final String bundleName; private final String key; private final Properties values; private final ResourceBundle bundle; private String message; protected Throwable exception; protected String stackTrace; public I18nMessage(ResourceBundle bundle, String key) { DBC.INTERIM.assertNotNull("bundle may not be null!", bundle); DBC.INTERIM.assertNotEmpty("key must be set!", key); this.key = key; this.values = new Properties(); this.bundle = bundle; this.bundleName = bundle.getBaseBundleName(); } public I18nMessage(String bundle, String key, Properties values, String message) { DBC.INTERIM.assertNotNull("bundle must not be empty!", bundle); DBC.INTERIM.assertNotEmpty("key must be set!", key); DBC.INTERIM.assertNotEmpty("message must be set!", message); this.key = key; this.values = values == null ? new Properties() : values; this.message = message; this.bundle = findBundle(bundle); this.bundleName = this.bundle == null ? bundle : this.bundle.getBaseBundleName(); } public I18nMessage(I18nMessage other) { this.key = other.key; this.values = other.values; this.bundle = other.bundle; this.bundleName = other.bundleName; this.message = other.message; } public String getKey() { return this.key; } public String getBundle() { if (this.bundle == null) return ""; return this.bundle.getBaseBundleName(); } public Properties getValues() { return this.values; } public Object getValue(String key) { return this.values.get(key); } private ResourceBundle getBundle(Locale locale) { if (this.bundle == null) return null; if (this.bundle.getLocale() == locale) return this.bundle; String baseName = this.bundle.getBaseBundleName(); try { ClassLoader classLoader = this.bundle.getClass().getClassLoader(); if (classLoader == null) return ResourceBundle.getBundle(baseName, locale); return ResourceBundle.getBundle(baseName, locale, classLoader); } catch (MissingResourceException e) { if (!missingKeysMap.containsSet(baseName + "_" + locale.toLanguageTag())) { logger.error("Failed to find resource bundle " + baseName + " " + locale.toLanguageTag() + ", returning current bundle " + this.bundle.getLocale().toLanguageTag()); missingKeysMap.addSet(baseName + "_" + locale.toLanguageTag(), emptySet()); } return this.bundle; } } public String getMessage(ResourceBundle bundle) { DBC.INTERIM.assertNotNull("bundle may not be null!", bundle); return formatMessage(bundle); } public String getMessage(Locale locale) { ResourceBundle bundle = getBundle(locale); if (bundle == null) { if (isEmpty(this.bundleName)) return getMessage(); if (!missingKeysMap.containsSet(this.bundleName + "_" + locale.toLanguageTag())) { logger.warn("No bundle found for " + this.bundleName + " " + locale + ". Available are: "); getBundleMap().forEach((s, map) -> { logger.info(" " + s); map.forEach((l, resourceBundle) -> logger.info(" " + l + ": " + map.keySet())); }); missingKeysMap.addSet(this.bundleName + "_" + locale.toLanguageTag(), emptySet()); } return getMessage(); } return formatMessage(bundle); } public String getMessage() { return formatMessage(); } public I18nMessage value(String key, Object value) { DBC.INTERIM.assertNotEmpty("key must be set!", key); this.values.setProperty(key, value == null ? "(null)" : value.toString()); return this; } public I18nMessage value(String key, Throwable t) { this.exception = t; this.stackTrace = formatException(t); value(key, getExceptionMessageWithCauses(t)); return this; } public I18nMessage withException(Throwable t) { this.exception = t; this.stackTrace = formatException(t); return this; } public boolean hasException() { return this.exception != null; } public Throwable getException() { return exception; } public String getStackTrace() { return this.stackTrace; } public String formatMessage() { if (this.message != null) return this.message; if (this.bundle == null) { this.message = this.key; return this.message; } this.message = formatMessage(this.bundle); return this.message; } public String formatMessage(ResourceBundle bundle) { try { String string = bundle.getString(this.key); return StringHelper.replacePropertiesIn(this.values, EMPTY, string); } catch (MissingResourceException e) { String baseName = bundle.getBaseBundleName(); String languageTag = bundle.getLocale().toLanguageTag(); String bundleKey = baseName + "_" + languageTag; if (!missingKeysMap.containsElement(bundleKey, this.key)) { logger.error("Key " + this.key + " is missing in bundle " + baseName + " for locale " + languageTag); missingKeysMap.addElement(bundleKey, this.key); } return this.key; } } public <T> T accept(I18nMessageVisitor<T> visitor) { return visitor.visit(this); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.key == null) ? 0 : this.key.hashCode()); result = prime * result + ((this.values == null) ? 0 : this.values.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; I18nMessage other = (I18nMessage) obj; if (this.key == null) { if (other.key != null) return false; } else if (!this.key.equals(other.key)) return false; if (this.values == null) { if (other.values != null) return false; } else if (!this.values.equals(other.values)) return false; return true; } private ResourceBundle findBundle(String baseName) { if (baseName.isEmpty()) return null; Map<Locale, ResourceBundle> bundlesByLocale = getBundleMap().getMap(baseName); if (bundlesByLocale == null || bundlesByLocale.isEmpty()) return null; ResourceBundle bundle = bundlesByLocale.get(Locale.getDefault()); if (bundle != null) return bundle; return bundlesByLocale.values().iterator().next(); } private static MapOfMaps<String, Locale, ResourceBundle> getBundleMap() { if (bundleMap == null) { synchronized (I18nMessage.class) { bundleMap = findAllBundles(); } } return bundleMap; } private static MapOfMaps<String, Locale, ResourceBundle> findAllBundles() { try { CodeSource src = I18nMessage.class.getProtectionDomain().getCodeSource(); if (src == null) { logger.error( "Failed to find CodeSource for ProtectionDomain " + I18nMessage.class.getProtectionDomain()); return new MapOfMaps<>(); } File jarLocationF = new File(src.getLocation().toURI()); if (!(jarLocationF.exists() && jarLocationF.getParentFile().isDirectory())) { logger.info("Found JAR repository at " + jarLocationF.getParentFile()); return new MapOfMaps<>(); } MapOfMaps<String, Locale, ResourceBundle> bundleMap = new MapOfMaps<>(); File jarD = jarLocationF.getParentFile(); File[] jarFiles = jarD.listFiles((dir, name) -> name.endsWith(".jar")); if (jarFiles == null) return new MapOfMaps<>(); for (File file : jarFiles) { if (shouldIgnoreFile(file)) continue; try (JarFile jarFile = new JarFile(file)) { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry je = entries.nextElement(); String entryName = je.getName(); if (entryName.startsWith("META-INF") // || entryName.equals("ENV.properties") // || entryName.equals("agentVersion.properties") // || entryName.equals("appVersion.properties") // || entryName.equals("componentVersion.properties") // || entryName.equals("strolch_db_version.properties")) continue; if (!entryName.endsWith(".properties")) continue; TypedTuple<String, Locale> tuple = parsePropertyName(entryName); if (tuple == null) continue; String baseName = tuple.getFirst(); Locale locale = tuple.getSecond(); ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, new CustomControl(jarFile.getInputStream(je))); bundleMap.addElement(bundle.getBaseBundleName(), bundle.getLocale(), bundle); String propertyName = entryName.replace('/', '.'); logger.info( " Loaded bundle " + bundle.getBaseBundleName() + " " + bundle.getLocale() + " from " + propertyName + " from JAR " + file.getName()); } } } File classesD = new File(jarD.getParentFile(), "classes"); if (classesD.isDirectory()) { File[] propertyFiles = classesD.listFiles( (dir, name) -> name.endsWith(".properties") && !(name.equals("appVersion.properties") || name.equals("ENV.properties"))); if (propertyFiles != null && propertyFiles.length > 0) { for (File propertyFile : propertyFiles) { logger.info(" Found property file " + propertyFile.getName() + " in classes " + classesD.getAbsolutePath()); TypedTuple<String, Locale> tuple = parsePropertyName(propertyFile.getName()); if (tuple == null) continue; String baseName = tuple.getFirst(); Locale locale = tuple.getSecond(); ResourceBundle bundle; try (FileInputStream in = new FileInputStream(propertyFile)) { bundle = ResourceBundle.getBundle(baseName, locale, new CustomControl(in)); } bundleMap.addElement(bundle.getBaseBundleName(), bundle.getLocale(), bundle); logger.info(" Loaded bundle " + bundle.getBaseBundleName() + " " + bundle.getLocale() + " from file " + propertyFile.getName()); } } } logger.info("Done."); return bundleMap; } catch (Exception e) { logger.error("Failed to find all property files!", e); return new MapOfMaps<>(); } } private static TypedTuple<String, Locale> parsePropertyName(String entryName) { String propertyName = entryName.replace('/', '.'); String bundleName = propertyName.substring(0, propertyName.lastIndexOf(".")); String baseName; Locale locale; int i = bundleName.indexOf('_'); if (i > 0) { baseName = bundleName.substring(0, i); String localeS = bundleName.substring(i + 1); String[] parts = localeS.split("_"); if (parts.length == 2) { String language = parts[0]; String country = parts[1]; int languageI = Arrays.binarySearch(Locale.getISOLanguages(), language); int countryI = Arrays.binarySearch(Locale.getISOCountries(), country); if (languageI >= 0 && countryI >= 0) locale = new Locale(language, country); else { logger.warn("Ignoring bad bundle locale for " + entryName); return null; } } else { int languageI = Arrays.binarySearch(Locale.getISOLanguages(), localeS); if (languageI >= 0) locale = new Locale(localeS); else { logger.warn("Ignoring bad bundle locale for " + entryName); return null; } } } else { baseName = bundleName; locale = Locale.getDefault(); } return new TypedTuple<>(baseName, locale); } private static class CustomControl extends ResourceBundle.Control { private final InputStream stream; public CustomControl(InputStream stream) { this.stream = stream; } @Override public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IOException { return new PropertyResourceBundle(this.stream); } } private static boolean shouldIgnoreFile(File file) { return file.getName().contains("aopalliance") // || file.getName().contains("activation") // || file.getName().contains("antlr") // || file.getName().contains("assertj-core") // || file.getName().startsWith("com.sun") // || file.getName().startsWith("commonj.") // || file.getName().startsWith("commons-") // || file.getName().startsWith("jackson-") // || file.getName().startsWith("hapi-") // || file.getName().startsWith("jaxb-") // || file.getName().startsWith("org.hl7.") // || file.getName().startsWith("listenablefuture-") // || file.getName().startsWith("j2objc-annotations") // || file.getName().startsWith("failureaccess-") // || file.getName().startsWith("error_prone_") // || file.getName().startsWith("guava-") // || file.getName().startsWith("org.eclipse") // || file.getName().contains("jsr305") // || file.getName().contains("c3p0") // || file.getName().contains("camel") // || file.getName().contains("checker-qual") // || file.getName().contains("cron") // || file.getName().contains("FastInfoset") // || file.getName().contains("gmbal") // || file.getName().contains("grizzly") // || file.getName().contains("gson") // || file.getName().contains("ha-api") // || file.getName().contains("HikariCP") // || file.getName().contains("hk2") // || file.getName().contains("icu4j") // || file.getName().contains("jakarta") // || file.getName().contains("javassist") // || file.getName().contains("javax") // || file.getName().contains("jaxb-api") // || file.getName().contains("jaxb-core") // || file.getName().contains("jaxb-impl") // || file.getName().contains("jaxrs-ri") // || file.getName().contains("jaxws-rt") // || file.getName().contains("jaxws-rt") // || file.getName().contains("jersey") // || file.getName().contains("joda-time") // || file.getName().contains("logback") // || file.getName().contains("management-api") // || file.getName().contains("mchange-commons-java") // || file.getName().contains("mimepull") // || file.getName().contains("org.abego.treelayout") // || file.getName().contains("osgi") // || file.getName().contains("pfl-basic") // || file.getName().contains("pfl-tf") // || file.getName().contains("policy-2.7.10") // || file.getName().contains("postgresql") // || file.getName().contains("quartz") // || file.getName().contains("saaj-impl") // || file.getName().contains("sax") // || file.getName().contains("slf4j") // || file.getName().contains("ST4") // || file.getName().contains("stax-ex") // || file.getName().contains("stax2-api") // || file.getName().contains("streambuffer") // || file.getName().contains("tyrus") // || file.getName().contains("validation-api") // || file.getName().contains("yasson"); } }
/* * * * 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.yarn.server.nodemanager.containermanager.linux.runtime; import com.google.common.annotations.VisibleForTesting; import org.apache.hadoop.yarn.server.nodemanager.Context; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker.DockerVolumeCommand; import org.apache.hadoop.yarn.server.nodemanager.containermanager.resourceplugin.DockerCommandPlugin; import org.apache.hadoop.yarn.server.nodemanager.containermanager.resourceplugin.ResourcePlugin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.registry.client.api.RegistryConstants; import org.apache.hadoop.registry.client.binding.RegistryPathUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.util.Shell; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; import org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.CGroupsHandler; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerModule; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker.DockerClient; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker.DockerInspectCommand; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker.DockerRunCommand; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker.DockerStopCommand; import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException; import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntime; import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeConstants; import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntimeConstants.*; /** * <p>This class is a {@link ContainerRuntime} implementation that uses the * native {@code container-executor} binary via a * {@link PrivilegedOperationExecutor} instance to launch processes inside * Docker containers.</p> * * <p>The following environment variables are used to configure the Docker * engine:</p> * * <ul> * <li> * {@code YARN_CONTAINER_RUNTIME_TYPE} ultimately determines whether a * Docker container will be used. If the value is {@code docker}, a Docker * container will be used. Otherwise a regular process tree container will * be used. This environment variable is checked by the * {@link #isDockerContainerRequested} method, which is called by the * {@link DelegatingLinuxContainerRuntime}. * </li> * <li> * {@code YARN_CONTAINER_RUNTIME_DOCKER_IMAGE} names which image * will be used to launch the Docker container. * </li> * <li> * {@code YARN_CONTAINER_RUNTIME_DOCKER_IMAGE_FILE} is currently ignored. * </li> * <li> * {@code YARN_CONTAINER_RUNTIME_DOCKER_RUN_OVERRIDE_DISABLE} controls * whether the Docker container's default command is overridden. When set * to {@code true}, the Docker container's command will be * {@code bash <path_to_launch_script>}. When unset or set to {@code false} * the Docker container's default command is used. * </li> * <li> * {@code YARN_CONTAINER_RUNTIME_DOCKER_CONTAINER_NETWORK} sets the * network type to be used by the Docker container. It must be a valid * value as determined by the * {@code yarn.nodemanager.runtime.linux.docker.allowed-container-networks} * property. * </li> * <li> * {@code YARN_CONTAINER_RUNTIME_DOCKER_CONTAINER_HOSTNAME} sets the * hostname to be used by the Docker container. If not specified, a * hostname will be derived from the container ID. * </li> * <li> * {@code YARN_CONTAINER_RUNTIME_DOCKER_RUN_PRIVILEGED_CONTAINER} * controls whether the Docker container is a privileged container. In order * to use privileged containers, the * {@code yarn.nodemanager.runtime.linux.docker.privileged-containers.allowed} * property must be set to {@code true}, and the application owner must * appear in the value of the * {@code yarn.nodemanager.runtime.linux.docker.privileged-containers.acl} * property. If this environment variable is set to {@code true}, a * privileged Docker container will be used if allowed. No other value is * allowed, so the environment variable should be left unset rather than * setting it to false. * </li> * <li> * {@code YARN_CONTAINER_RUNTIME_DOCKER_LOCAL_RESOURCE_MOUNTS} adds * additional volume mounts to the Docker container. The value of the * environment variable should be a comma-separated list of mounts. * All such mounts must be given as {@code source:dest}, where the * source is an absolute path that is not a symlink and that points to a * localized resource. * </li> * </ul> */ @InterfaceAudience.Private @InterfaceStability.Unstable public class DockerLinuxContainerRuntime implements LinuxContainerRuntime { private static final Logger LOG = LoggerFactory.getLogger(DockerLinuxContainerRuntime.class); // This validates that the image is a proper docker image public static final String DOCKER_IMAGE_PATTERN = "^(([a-zA-Z0-9.-]+)(:\\d+)?/)?([a-z0-9_./-]+)(:[\\w.-]+)?$"; private static final Pattern dockerImagePattern = Pattern.compile(DOCKER_IMAGE_PATTERN); public static final String HOSTNAME_PATTERN = "^[a-zA-Z0-9][a-zA-Z0-9_.-]+$"; private static final Pattern hostnamePattern = Pattern.compile( HOSTNAME_PATTERN); @InterfaceAudience.Private public static final String ENV_DOCKER_CONTAINER_IMAGE = "YARN_CONTAINER_RUNTIME_DOCKER_IMAGE"; @InterfaceAudience.Private public static final String ENV_DOCKER_CONTAINER_IMAGE_FILE = "YARN_CONTAINER_RUNTIME_DOCKER_IMAGE_FILE"; @InterfaceAudience.Private public static final String ENV_DOCKER_CONTAINER_RUN_OVERRIDE_DISABLE = "YARN_CONTAINER_RUNTIME_DOCKER_RUN_OVERRIDE_DISABLE"; @InterfaceAudience.Private public static final String ENV_DOCKER_CONTAINER_NETWORK = "YARN_CONTAINER_RUNTIME_DOCKER_CONTAINER_NETWORK"; @InterfaceAudience.Private public static final String ENV_DOCKER_CONTAINER_HOSTNAME = "YARN_CONTAINER_RUNTIME_DOCKER_CONTAINER_HOSTNAME"; @InterfaceAudience.Private public static final String ENV_DOCKER_CONTAINER_RUN_PRIVILEGED_CONTAINER = "YARN_CONTAINER_RUNTIME_DOCKER_RUN_PRIVILEGED_CONTAINER"; @InterfaceAudience.Private public static final String ENV_DOCKER_CONTAINER_RUN_ENABLE_USER_REMAPPING = "YARN_CONTAINER_RUNTIME_DOCKER_RUN_ENABLE_USER_REMAPPING"; @InterfaceAudience.Private public static final String ENV_DOCKER_CONTAINER_LOCAL_RESOURCE_MOUNTS = "YARN_CONTAINER_RUNTIME_DOCKER_LOCAL_RESOURCE_MOUNTS"; private Configuration conf; private Context nmContext; private DockerClient dockerClient; private PrivilegedOperationExecutor privilegedOperationExecutor; private Set<String> allowedNetworks = new HashSet<>(); private String defaultNetwork; private String cgroupsRootDirectory; private CGroupsHandler cGroupsHandler; private AccessControlList privilegedContainersAcl; private boolean enableUserReMapping; private int userRemappingUidThreshold; private int userRemappingGidThreshold; private Set<String> capabilities; /** * Return whether the given environment variables indicate that the operation * is requesting a Docker container. If the environment contains a key * called {@code YARN_CONTAINER_RUNTIME_TYPE} whose value is {@code docker}, * this method will return true. Otherwise it will return false. * * @param env the environment variable settings for the operation * @return whether a Docker container is requested */ public static boolean isDockerContainerRequested( Map<String, String> env) { if (env == null) { return false; } String type = env.get(ContainerRuntimeConstants.ENV_CONTAINER_TYPE); return type != null && type.equals("docker"); } /** * Create an instance using the given {@link PrivilegedOperationExecutor} * instance for performing operations. * * @param privilegedOperationExecutor the {@link PrivilegedOperationExecutor} * instance */ public DockerLinuxContainerRuntime(PrivilegedOperationExecutor privilegedOperationExecutor) { this(privilegedOperationExecutor, ResourceHandlerModule.getCGroupsHandler()); } /** * Create an instance using the given {@link PrivilegedOperationExecutor} * instance for performing operations and the given {@link CGroupsHandler} * instance. This constructor is intended for use in testing. * @param privilegedOperationExecutor the {@link PrivilegedOperationExecutor} * instance * @param cGroupsHandler the {@link CGroupsHandler} instance */ @VisibleForTesting public DockerLinuxContainerRuntime( PrivilegedOperationExecutor privilegedOperationExecutor, CGroupsHandler cGroupsHandler) { this.privilegedOperationExecutor = privilegedOperationExecutor; if (cGroupsHandler == null) { LOG.info("cGroupsHandler is null - cgroups not in use."); } else { this.cGroupsHandler = cGroupsHandler; this.cgroupsRootDirectory = cGroupsHandler.getCGroupMountPath(); } } @Override public void initialize(Configuration conf, Context nmContext) throws ContainerExecutionException { this.nmContext = nmContext; this.conf = conf; dockerClient = new DockerClient(conf); allowedNetworks.clear(); allowedNetworks.addAll(Arrays.asList( conf.getTrimmedStrings( YarnConfiguration.NM_DOCKER_ALLOWED_CONTAINER_NETWORKS, YarnConfiguration.DEFAULT_NM_DOCKER_ALLOWED_CONTAINER_NETWORKS))); defaultNetwork = conf.getTrimmed( YarnConfiguration.NM_DOCKER_DEFAULT_CONTAINER_NETWORK, YarnConfiguration.DEFAULT_NM_DOCKER_DEFAULT_CONTAINER_NETWORK); if(!allowedNetworks.contains(defaultNetwork)) { String message = "Default network: " + defaultNetwork + " is not in the set of allowed networks: " + allowedNetworks; if (LOG.isWarnEnabled()) { LOG.warn(message + ". Please check " + "configuration"); } throw new ContainerExecutionException(message); } privilegedContainersAcl = new AccessControlList(conf.getTrimmed( YarnConfiguration.NM_DOCKER_PRIVILEGED_CONTAINERS_ACL, YarnConfiguration.DEFAULT_NM_DOCKER_PRIVILEGED_CONTAINERS_ACL)); enableUserReMapping = conf.getBoolean( YarnConfiguration.NM_DOCKER_ENABLE_USER_REMAPPING, YarnConfiguration.DEFAULT_NM_DOCKER_ENABLE_USER_REMAPPING); userRemappingUidThreshold = conf.getInt( YarnConfiguration.NM_DOCKER_USER_REMAPPING_UID_THRESHOLD, YarnConfiguration.DEFAULT_NM_DOCKER_USER_REMAPPING_UID_THRESHOLD); userRemappingGidThreshold = conf.getInt( YarnConfiguration.NM_DOCKER_USER_REMAPPING_GID_THRESHOLD, YarnConfiguration.DEFAULT_NM_DOCKER_USER_REMAPPING_GID_THRESHOLD); capabilities = getDockerCapabilitiesFromConf(); } private Set<String> getDockerCapabilitiesFromConf() throws ContainerExecutionException { Set<String> caps = new HashSet<>(Arrays.asList( conf.getTrimmedStrings( YarnConfiguration.NM_DOCKER_CONTAINER_CAPABILITIES, YarnConfiguration.DEFAULT_NM_DOCKER_CONTAINER_CAPABILITIES))); if(caps.contains("none") || caps.contains("NONE")) { if(caps.size() > 1) { String msg = "Mixing capabilities with the none keyword is" + " not supported"; throw new ContainerExecutionException(msg); } caps = Collections.emptySet(); } return caps; } public Set<String> getCapabilities() { return capabilities; } @Override public boolean useWhitelistEnv(Map<String, String> env) { // Avoid propagating nodemanager environment variables into the container // so those variables can be picked up from the Docker image instead. return false; } private void runDockerVolumeCommand(DockerVolumeCommand dockerVolumeCommand, Container container) throws ContainerExecutionException { try { String commandFile = dockerClient.writeCommandToTempFile( dockerVolumeCommand, container.getContainerId().toString()); PrivilegedOperation privOp = new PrivilegedOperation( PrivilegedOperation.OperationType.RUN_DOCKER_CMD); privOp.appendArgs(commandFile); String output = privilegedOperationExecutor .executePrivilegedOperation(null, privOp, null, null, true, false); LOG.info("ContainerId=" + container.getContainerId() + ", docker volume output for " + dockerVolumeCommand + ": " + output); } catch (ContainerExecutionException e) { LOG.error("Error when writing command to temp file, command=" + dockerVolumeCommand, e); throw e; } catch (PrivilegedOperationException e) { LOG.error("Error when executing command, command=" + dockerVolumeCommand, e); throw new ContainerExecutionException(e); } } @Override public void prepareContainer(ContainerRuntimeContext ctx) throws ContainerExecutionException { Container container = ctx.getContainer(); // Create volumes when needed. if (nmContext != null && nmContext.getResourcePluginManager().getNameToPlugins() != null) { for (ResourcePlugin plugin : nmContext.getResourcePluginManager() .getNameToPlugins().values()) { DockerCommandPlugin dockerCommandPlugin = plugin.getDockerCommandPluginInstance(); if (dockerCommandPlugin != null) { DockerVolumeCommand dockerVolumeCommand = dockerCommandPlugin.getCreateDockerVolumeCommand(ctx.getContainer()); if (dockerVolumeCommand != null) { runDockerVolumeCommand(dockerVolumeCommand, container); } } } } } private void validateContainerNetworkType(String network) throws ContainerExecutionException { if (allowedNetworks.contains(network)) { return; } String msg = "Disallowed network: '" + network + "' specified. Allowed networks: are " + allowedNetworks .toString(); throw new ContainerExecutionException(msg); } public static void validateHostname(String hostname) throws ContainerExecutionException { if (hostname != null && !hostname.isEmpty()) { if (!hostnamePattern.matcher(hostname).matches()) { throw new ContainerExecutionException("Hostname '" + hostname + "' doesn't match docker hostname pattern"); } } } /** Set a DNS friendly hostname. */ private void setHostname(DockerRunCommand runCommand, String containerIdStr, String name) throws ContainerExecutionException { if (name == null || name.isEmpty()) { name = RegistryPathUtils.encodeYarnID(containerIdStr); String domain = conf.get(RegistryConstants.KEY_DNS_DOMAIN); if (domain != null) { name += ("." + domain); } validateHostname(name); } LOG.info("setting hostname in container to: " + name); runCommand.setHostname(name); } /** * If CGROUPS in enabled and not set to none, then set the CGROUP parent for * the command instance. * * @param resourcesOptions the resource options to check for "cgroups=none" * @param containerIdStr the container ID * @param runCommand the command to set with the CGROUP parent */ @VisibleForTesting protected void addCGroupParentIfRequired(String resourcesOptions, String containerIdStr, DockerRunCommand runCommand) { if (cGroupsHandler == null) { if (LOG.isDebugEnabled()) { LOG.debug("cGroupsHandler is null. cgroups are not in use. nothing to" + " do."); } return; } if (resourcesOptions.equals(PrivilegedOperation.CGROUP_ARG_PREFIX + PrivilegedOperation.CGROUP_ARG_NO_TASKS)) { if (LOG.isDebugEnabled()) { LOG.debug("no resource restrictions specified. not using docker's " + "cgroup options"); } } else { if (LOG.isDebugEnabled()) { LOG.debug("using docker's cgroups options"); } String cGroupPath = "/" + cGroupsHandler.getRelativePathForCGroup(containerIdStr); if (LOG.isDebugEnabled()) { LOG.debug("using cgroup parent: " + cGroupPath); } runCommand.setCGroupParent(cGroupPath); } } /** * Return whether the YARN container is allowed to run in a privileged * Docker container. For a privileged container to be allowed all of the * following three conditions must be satisfied: * * <ol> * <li>Submitting user must request for a privileged container</li> * <li>Privileged containers must be enabled on the cluster</li> * <li>Submitting user must be white-listed to run a privileged * container</li> * </ol> * * @param container the target YARN container * @return whether privileged container execution is allowed * @throws ContainerExecutionException if privileged container execution * is requested but is not allowed */ private boolean allowPrivilegedContainerExecution(Container container) throws ContainerExecutionException { Map<String, String> environment = container.getLaunchContext() .getEnvironment(); String runPrivilegedContainerEnvVar = environment .get(ENV_DOCKER_CONTAINER_RUN_PRIVILEGED_CONTAINER); if (runPrivilegedContainerEnvVar == null) { return false; } if (!runPrivilegedContainerEnvVar.equalsIgnoreCase("true")) { LOG.warn("NOT running a privileged container. Value of " + ENV_DOCKER_CONTAINER_RUN_PRIVILEGED_CONTAINER + "is invalid: " + runPrivilegedContainerEnvVar); return false; } LOG.info("Privileged container requested for : " + container .getContainerId().toString()); //Ok, so we have been asked to run a privileged container. Security // checks need to be run. Each violation is an error. //check if privileged containers are enabled. boolean privilegedContainersEnabledOnCluster = conf.getBoolean( YarnConfiguration.NM_DOCKER_ALLOW_PRIVILEGED_CONTAINERS, YarnConfiguration.DEFAULT_NM_DOCKER_ALLOW_PRIVILEGED_CONTAINERS); if (!privilegedContainersEnabledOnCluster) { String message = "Privileged container being requested but privileged " + "containers are not enabled on this cluster"; LOG.warn(message); throw new ContainerExecutionException(message); } //check if submitting user is in the whitelist. String submittingUser = container.getUser(); UserGroupInformation submitterUgi = UserGroupInformation .createRemoteUser(submittingUser); if (!privilegedContainersAcl.isUserAllowed(submitterUgi)) { String message = "Cannot launch privileged container. Submitting user (" + submittingUser + ") fails ACL check."; LOG.warn(message); throw new ContainerExecutionException(message); } LOG.info("All checks pass. Launching privileged container for : " + container.getContainerId().toString()); return true; } @VisibleForTesting protected String validateMount(String mount, Map<Path, List<String>> localizedResources) throws ContainerExecutionException { for (Entry<Path, List<String>> resource : localizedResources.entrySet()) { if (resource.getValue().contains(mount)) { java.nio.file.Path path = Paths.get(resource.getKey().toString()); if (!path.isAbsolute()) { throw new ContainerExecutionException("Mount must be absolute: " + mount); } if (Files.isSymbolicLink(path)) { throw new ContainerExecutionException("Mount cannot be a symlink: " + mount); } return path.toString(); } } throw new ContainerExecutionException("Mount must be a localized " + "resource: " + mount); } private String getUserIdInfo(String userName) throws ContainerExecutionException { String id = ""; Shell.ShellCommandExecutor shexec = new Shell.ShellCommandExecutor( new String[]{"id", "-u", userName}); try { shexec.execute(); id = shexec.getOutput().replaceAll("[^0-9]", ""); } catch (Exception e) { throw new ContainerExecutionException(e); } return id; } private String[] getGroupIdInfo(String userName) throws ContainerExecutionException { String[] id = null; Shell.ShellCommandExecutor shexec = new Shell.ShellCommandExecutor( new String[]{"id", "-G", userName}); try { shexec.execute(); id = shexec.getOutput().replace("\n", "").split(" "); } catch (Exception e) { throw new ContainerExecutionException(e); } return id; } @Override public void launchContainer(ContainerRuntimeContext ctx) throws ContainerExecutionException { Container container = ctx.getContainer(); Map<String, String> environment = container.getLaunchContext() .getEnvironment(); String imageName = environment.get(ENV_DOCKER_CONTAINER_IMAGE); String network = environment.get(ENV_DOCKER_CONTAINER_NETWORK); String hostname = environment.get(ENV_DOCKER_CONTAINER_HOSTNAME); if(network == null || network.isEmpty()) { network = defaultNetwork; } validateContainerNetworkType(network); validateHostname(hostname); validateImageName(imageName); String containerIdStr = container.getContainerId().toString(); String runAsUser = ctx.getExecutionAttribute(RUN_AS_USER); String dockerRunAsUser = runAsUser; Path containerWorkDir = ctx.getExecutionAttribute(CONTAINER_WORK_DIR); String[] groups = null; if (enableUserReMapping) { String uid = getUserIdInfo(runAsUser); groups = getGroupIdInfo(runAsUser); String gid = groups[0]; if(Integer.parseInt(uid) < userRemappingUidThreshold) { String message = "uid: " + uid + " below threshold: " + userRemappingUidThreshold; throw new ContainerExecutionException(message); } for(int i = 0; i < groups.length; i++) { String group = groups[i]; if (Integer.parseInt(group) < userRemappingGidThreshold) { String message = "gid: " + group + " below threshold: " + userRemappingGidThreshold; throw new ContainerExecutionException(message); } } dockerRunAsUser = uid + ":" + gid; } //List<String> -> stored as List -> fetched/converted to List<String> //we can't do better here thanks to type-erasure @SuppressWarnings("unchecked") List<String> filecacheDirs = ctx.getExecutionAttribute(FILECACHE_DIRS); @SuppressWarnings("unchecked") List<String> containerLocalDirs = ctx.getExecutionAttribute( CONTAINER_LOCAL_DIRS); @SuppressWarnings("unchecked") List<String> containerLogDirs = ctx.getExecutionAttribute( CONTAINER_LOG_DIRS); @SuppressWarnings("unchecked") Map<Path, List<String>> localizedResources = ctx.getExecutionAttribute( LOCALIZED_RESOURCES); @SuppressWarnings("unchecked") List<String> userLocalDirs = ctx.getExecutionAttribute(USER_LOCAL_DIRS); @SuppressWarnings("unchecked") DockerRunCommand runCommand = new DockerRunCommand(containerIdStr, dockerRunAsUser, imageName) .detachOnRun() .setContainerWorkDir(containerWorkDir.toString()) .setNetworkType(network); setHostname(runCommand, containerIdStr, hostname); runCommand.setCapabilities(capabilities); if(cgroupsRootDirectory != null) { runCommand.addReadOnlyMountLocation(cgroupsRootDirectory, cgroupsRootDirectory, false); } List<String> allDirs = new ArrayList<>(containerLocalDirs); allDirs.addAll(filecacheDirs); allDirs.add(containerWorkDir.toString()); allDirs.addAll(containerLogDirs); allDirs.addAll(userLocalDirs); for (String dir: allDirs) { runCommand.addMountLocation(dir, dir, true); } if (environment.containsKey(ENV_DOCKER_CONTAINER_LOCAL_RESOURCE_MOUNTS)) { String mounts = environment.get( ENV_DOCKER_CONTAINER_LOCAL_RESOURCE_MOUNTS); if (!mounts.isEmpty()) { for (String mount : StringUtils.split(mounts)) { String[] dir = StringUtils.split(mount, ':'); if (dir.length != 2) { throw new ContainerExecutionException("Invalid mount : " + mount); } String src = validateMount(dir[0], localizedResources); String dst = dir[1]; runCommand.addReadOnlyMountLocation(src, dst, true); } } } if (allowPrivilegedContainerExecution(container)) { runCommand.setPrivileged(); } String resourcesOpts = ctx.getExecutionAttribute(RESOURCES_OPTIONS); addCGroupParentIfRequired(resourcesOpts, containerIdStr, runCommand); String disableOverride = environment.get( ENV_DOCKER_CONTAINER_RUN_OVERRIDE_DISABLE); if (disableOverride != null && disableOverride.equals("true")) { LOG.info("command override disabled"); } else { List<String> overrideCommands = new ArrayList<>(); Path launchDst = new Path(containerWorkDir, ContainerLaunch.CONTAINER_SCRIPT); overrideCommands.add("bash"); overrideCommands.add(launchDst.toUri().getPath()); runCommand.setOverrideCommandWithArgs(overrideCommands); } if(enableUserReMapping) { runCommand.groupAdd(groups); } // use plugins to update docker run command. if (nmContext != null && nmContext.getResourcePluginManager().getNameToPlugins() != null) { for (ResourcePlugin plugin : nmContext.getResourcePluginManager() .getNameToPlugins().values()) { DockerCommandPlugin dockerCommandPlugin = plugin.getDockerCommandPluginInstance(); if (dockerCommandPlugin != null) { dockerCommandPlugin.updateDockerRunCommand(runCommand, container); } } } String commandFile = dockerClient.writeCommandToTempFile(runCommand, containerIdStr); PrivilegedOperation launchOp = buildLaunchOp(ctx, commandFile, runCommand); try { privilegedOperationExecutor.executePrivilegedOperation(null, launchOp, null, null, false, false); } catch (PrivilegedOperationException e) { LOG.warn("Launch container failed. Exception: ", e); LOG.info("Docker command used: " + runCommand); throw new ContainerExecutionException("Launch container failed", e .getExitCode(), e.getOutput(), e.getErrorOutput()); } } @Override public void signalContainer(ContainerRuntimeContext ctx) throws ContainerExecutionException { ContainerExecutor.Signal signal = ctx.getExecutionAttribute(SIGNAL); PrivilegedOperation privOp = null; // Handle liveliness checks, send null signal to pid if(ContainerExecutor.Signal.NULL.equals(signal)) { privOp = new PrivilegedOperation( PrivilegedOperation.OperationType.SIGNAL_CONTAINER); privOp.appendArgs(ctx.getExecutionAttribute(RUN_AS_USER), ctx.getExecutionAttribute(USER), Integer.toString(PrivilegedOperation.RunAsUserCommand .SIGNAL_CONTAINER.getValue()), ctx.getExecutionAttribute(PID), Integer.toString(ctx.getExecutionAttribute(SIGNAL).getValue())); // All other signals handled as docker stop } else { String containerId = ctx.getContainer().getContainerId().toString(); DockerStopCommand stopCommand = new DockerStopCommand(containerId); String commandFile = dockerClient.writeCommandToTempFile(stopCommand, containerId); privOp = new PrivilegedOperation( PrivilegedOperation.OperationType.RUN_DOCKER_CMD); privOp.appendArgs(commandFile); } //Some failures here are acceptable. Let the calling executor decide. privOp.disableFailureLogging(); try { privilegedOperationExecutor.executePrivilegedOperation(null, privOp, null, null, false, false); } catch (PrivilegedOperationException e) { throw new ContainerExecutionException("Signal container failed", e .getExitCode(), e.getOutput(), e.getErrorOutput()); } } @Override public void reapContainer(ContainerRuntimeContext ctx) throws ContainerExecutionException { // Cleanup volumes when needed. if (nmContext != null && nmContext.getResourcePluginManager().getNameToPlugins() != null) { for (ResourcePlugin plugin : nmContext.getResourcePluginManager() .getNameToPlugins().values()) { DockerCommandPlugin dockerCommandPlugin = plugin.getDockerCommandPluginInstance(); if (dockerCommandPlugin != null) { DockerVolumeCommand dockerVolumeCommand = dockerCommandPlugin.getCleanupDockerVolumesCommand( ctx.getContainer()); if (dockerVolumeCommand != null) { runDockerVolumeCommand(dockerVolumeCommand, ctx.getContainer()); } } } } } // ipAndHost[0] contains comma separated list of IPs // ipAndHost[1] contains the hostname. @Override public String[] getIpAndHost(Container container) { String containerId = container.getContainerId().toString(); DockerInspectCommand inspectCommand = new DockerInspectCommand(containerId).getIpAndHost(); try { String commandFile = dockerClient.writeCommandToTempFile(inspectCommand, containerId); PrivilegedOperation privOp = new PrivilegedOperation( PrivilegedOperation.OperationType.RUN_DOCKER_CMD); privOp.appendArgs(commandFile); String output = privilegedOperationExecutor .executePrivilegedOperation(null, privOp, null, null, true, false); LOG.info("Docker inspect output for " + containerId + ": " + output); // strip off quotes if any output = output.replaceAll("['\"]", ""); int index = output.lastIndexOf(','); if (index == -1) { LOG.error("Incorrect format for ip and host"); return null; } String ips = output.substring(0, index).trim(); String host = output.substring(index+1).trim(); String[] ipAndHost = new String[2]; ipAndHost[0] = ips; ipAndHost[1] = host; return ipAndHost; } catch (ContainerExecutionException e) { LOG.error("Error when writing command to temp file", e); } catch (PrivilegedOperationException e) { LOG.error("Error when executing command.", e); } return null; } private PrivilegedOperation buildLaunchOp(ContainerRuntimeContext ctx, String commandFile, DockerRunCommand runCommand) { String runAsUser = ctx.getExecutionAttribute(RUN_AS_USER); String containerIdStr = ctx.getContainer().getContainerId().toString(); Path nmPrivateContainerScriptPath = ctx.getExecutionAttribute( NM_PRIVATE_CONTAINER_SCRIPT_PATH); Path containerWorkDir = ctx.getExecutionAttribute(CONTAINER_WORK_DIR); //we can't do better here thanks to type-erasure @SuppressWarnings("unchecked") List<String> localDirs = ctx.getExecutionAttribute(LOCAL_DIRS); @SuppressWarnings("unchecked") List<String> logDirs = ctx.getExecutionAttribute(LOG_DIRS); String resourcesOpts = ctx.getExecutionAttribute(RESOURCES_OPTIONS); PrivilegedOperation launchOp = new PrivilegedOperation( PrivilegedOperation.OperationType.LAUNCH_DOCKER_CONTAINER); launchOp.appendArgs(runAsUser, ctx.getExecutionAttribute(USER), Integer.toString(PrivilegedOperation .RunAsUserCommand.LAUNCH_DOCKER_CONTAINER.getValue()), ctx.getExecutionAttribute(APPID), containerIdStr, containerWorkDir.toString(), nmPrivateContainerScriptPath.toUri().getPath(), ctx.getExecutionAttribute(NM_PRIVATE_TOKENS_PATH).toUri().getPath(), ctx.getExecutionAttribute(PID_FILE_PATH).toString(), StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR, localDirs), StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR, logDirs), commandFile, resourcesOpts); String tcCommandFile = ctx.getExecutionAttribute(TC_COMMAND_FILE); if (tcCommandFile != null) { launchOp.appendArgs(tcCommandFile); } if (LOG.isDebugEnabled()) { LOG.debug("Launching container with cmd: " + runCommand); } return launchOp; } public static void validateImageName(String imageName) throws ContainerExecutionException { if (imageName == null || imageName.isEmpty()) { throw new ContainerExecutionException( ENV_DOCKER_CONTAINER_IMAGE + " not set!"); } if (!dockerImagePattern.matcher(imageName).matches()) { throw new ContainerExecutionException("Image name '" + imageName + "' doesn't match docker image name pattern"); } } }
package graphene.dao.es.impl; import graphene.dao.UserDAO; import graphene.dao.UserWorkspaceDAO; import graphene.dao.WorkspaceDAO; import graphene.dao.es.BasicESDAO; import graphene.dao.es.ESRestAPIConnection; import graphene.dao.es.JestModule; import graphene.model.idl.G_SymbolConstants; import graphene.model.idl.G_User; import graphene.model.idl.G_UserSpaceRelationshipType; import graphene.model.idl.G_UserWorkspace; import graphene.model.idl.G_Workspace; import graphene.util.validator.ValidationUtils; import io.searchbox.core.Count; import io.searchbox.core.CountResult; import io.searchbox.core.Delete; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.ioc.annotations.PostInjection; import org.apache.tapestry5.ioc.annotations.Symbol; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.slf4j.Logger; import com.fasterxml.jackson.databind.ObjectMapper; public class UserWorkspaceDAOESImpl extends BasicESDAO implements UserWorkspaceDAO { private static final String TYPE = "userworkspace"; @Inject @Symbol(JestModule.ES_USERWORKSPACE_INDEX) private String indexName; @Inject private UserDAO userDAO; @Inject private WorkspaceDAO workspaceDAO; @Inject @Symbol(G_SymbolConstants.ENABLE_DELETE_USER_WORKSPACES) private boolean enableDelete; public UserWorkspaceDAOESImpl(final ESRestAPIConnection c, final Logger logger) { auth = null; this.c = c; mapper = new ObjectMapper(); // can reuse, share globally this.logger = logger; setType(TYPE); } @Override public boolean addRelationToWorkspace(final String userId, final G_UserSpaceRelationshipType rel, final String workspaceid) { final G_UserWorkspace ug = save(new G_UserWorkspace(null, workspaceid, userId, getModifiedTime(), rel)); if (ug != null) { logger.debug("Added user " + userId + " as " + rel.name() + " of workspace " + workspaceid); return true; } else { logger.error("Could not create relationship for user " + userId + " as " + rel.name() + " of workspace " + workspaceid); return false; } } @Override public int countUsersForWorkspace(final String workspaceId) { final String query = new SearchSourceBuilder().query(QueryBuilders.matchQuery("id", workspaceId)).toString(); try { final CountResult result = c.getClient().execute( new Count.Builder().query(query).addIndex(indexName).addType(type) .setParameter("timeout", defaultESTimeout).build()); return (int) result.getCount().longValue(); } catch (final Exception e) { logger.error("Count users for workspace: " + e.getMessage()); } return 0; } @Override public boolean delete(final String id) { if (enableDelete) { return super.delete(id); } else { logger.debug("Delete disabled."); return false; } } @Override public boolean deleteWorkspaceRelations(final String workspaceId) { boolean success = false; try { c.getClient().execute( (new Delete.Builder(QueryBuilders.matchQuery("workspaceId", workspaceId).toString())) .index(getIndex()).type(type).setParameter("timeout", defaultESTimeout).build()); success = true; } catch (final Exception e) { logger.error("Delete workspace relations: " + e.getMessage()); } return success; } @Override public List<G_UserWorkspace> getAll() { return getAllResults().getSourceAsObjectList(G_UserWorkspace.class); } @Override public G_UserWorkspace getById(final String id) { return getResultsById(id).getSourceAsObject(G_UserWorkspace.class); } @Override public List<G_UserWorkspace> getByUserId(final String id) { return getByField("userId", id).getSourceAsObjectList(G_UserWorkspace.class); } @Override public List<G_UserWorkspace> getByUserIdAndWorkspaceId(final String userId, final String workspaceId) { final List<G_UserWorkspace> memberships = getByJoinFields("userId", userId, "workspaceId", workspaceId) .getSourceAsObjectList(G_UserWorkspace.class); return memberships; } @Override public List<G_UserWorkspace> getByWorkspaceId(final String id) { return getByField("workspaceId", id).getSourceAsObjectList(G_UserWorkspace.class); } @Override public List<G_Workspace> getMostRecentWorkspacesForUser(final String userId, final int quantity) { if (quantity == 0) { return new ArrayList<G_Workspace>(); } final List<G_Workspace> returnValue = getWorkspacesForUser(userId); Collections.sort(returnValue, new Comparator<G_Workspace>() { @Override public int compare(final G_Workspace o1, final G_Workspace o2) { return o1.getModified().compareTo(o2.getModified()); } }); if (returnValue.size() < quantity) { return returnValue; } else { return returnValue.subList(0, quantity); } } @Override public List<G_User> getUsersForWorkspace(final String workspaceId) { final List<G_User> returnValue = new ArrayList<G_User>(0); for (final G_UserWorkspace r : getByWorkspaceId(workspaceId)) { final G_User foundObject = userDAO.getById(r.getUserId()); if (foundObject != null) { returnValue.add(foundObject); } } return returnValue; } @Override public List<G_Workspace> getWorkspacesForUser(final String userId) { final List<G_Workspace> returnValue = new ArrayList<G_Workspace>(0); /* * The reason for this is because we may have several relationships to * the same workspace, but we only want to return the unique set of * workspaces (no duplicates). So collect the workspace ids in a set * first. */ final Set<String> workspaceIds = new HashSet<String>(); for (final G_UserWorkspace r : getByUserId(userId)) { workspaceIds.add(r.getWorkspaceId()); } if (workspaceIds.isEmpty()) { logger.warn("User " + userId + " does not appear to have any workspaces. This may be ok."); } else { for (final String id : workspaceIds) { final G_Workspace foundObject = workspaceDAO.getById(id); if (foundObject != null) { returnValue.add(foundObject); } } } return returnValue; } @Override public boolean hasRelationship(final String userId, final String workspaceId, final G_UserSpaceRelationshipType... relations) { boolean success = false; final List<G_UserWorkspace> resultObject = getByUserIdAndWorkspaceId(userId, workspaceId); for (final G_UserWorkspace r : resultObject) { for (final G_UserSpaceRelationshipType relation : relations) { if (r.getRole().equals(relation)) { success = true; } } } return success; } @Override @PostInjection public void initialize() { setIndex(indexName); setType(TYPE); super.initialize(); } @Override public boolean removeUserFromWorkspace(final String userId, final String workspaceId) { boolean success = false; for (final G_UserWorkspace r : getByUserIdAndWorkspaceId(userId, workspaceId)) { // remove each user binding that matched, should only be one or // two. // FIXME: There is a possible bug here if the id was not valid. logger.debug("Deleting user-workspace relation " + r.getId()); success = delete(r.getId()); } return success; } @Override public boolean removeUserPermissionFromWorkspace(final String userId, final String permission, final String workspaceId) { boolean success = false; for (final G_UserWorkspace r : getByUserIdAndWorkspaceId(userId, workspaceId)) { if (r.getRole().name().equals(permission)) { // FIXME: There is a possible bug here if the id was not valid. success = delete(r.getId()); } } return success; } @Override public G_UserWorkspace save(final G_UserWorkspace g) { G_UserWorkspace returnVal = null; if (ValidationUtils.isValid(g)) { g.setModified(getModifiedTime()); if (g.getId() == null) { g.setId(saveObject(g, g.getId(), indexName, type, false)); } saveObject(g, g.getId(), indexName, type, true); returnVal = g; } else { logger.error("Attempted to save a null user workspace object!"); } return returnVal; } }
/* * The Gemma project * * Copyright (c) 2011 University of British Columbia * * 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 ubic.gemma.core.analysis.expression.diff; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import ubic.gemma.core.analysis.expression.diff.DifferentialExpressionAnalyzerServiceImpl.AnalysisType; import ubic.gemma.core.loader.expression.simple.ExperimentalDesignImporter; import ubic.gemma.core.loader.expression.simple.SimpleExpressionDataLoaderService; import ubic.gemma.core.loader.expression.simple.model.SimpleExpressionExperimentMetaData; import ubic.gemma.core.util.test.BaseSpringContextTest; import ubic.gemma.model.analysis.expression.diff.DifferentialExpressionAnalysis; import ubic.gemma.model.analysis.expression.diff.DifferentialExpressionAnalysisResult; import ubic.gemma.model.analysis.expression.diff.ExpressionAnalysisResultSet; import ubic.gemma.model.common.quantitationtype.ScaleType; import ubic.gemma.model.expression.arrayDesign.ArrayDesign; import ubic.gemma.model.expression.arrayDesign.TechnologyType; import ubic.gemma.model.expression.designElement.CompositeSequence; import ubic.gemma.model.expression.experiment.ExperimentalFactor; import ubic.gemma.model.expression.experiment.ExpressionExperiment; import ubic.gemma.persistence.service.analysis.expression.diff.DifferentialExpressionAnalysisService; import ubic.gemma.persistence.service.analysis.expression.diff.DifferentialExpressionResultService; import ubic.gemma.persistence.service.expression.experiment.ExpressionExperimentService; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import static org.junit.Assert.*; /** * Test based on GSE8441 * * @author paul */ public class TwoWayAnovaWithInteractionTest2 extends BaseSpringContextTest { @Autowired private SimpleExpressionDataLoaderService dataLoaderService; @Autowired private ExperimentalDesignImporter designImporter; @Autowired private ExpressionExperimentService expressionExperimentService; @Autowired private DiffExAnalyzer analyzer; @Autowired private AnalysisSelectionAndExecutionService analysisService = null; @Autowired private DifferentialExpressionAnalyzerService differentialExpressionAnalyzerService; @Autowired private DifferentialExpressionAnalysisService differentialExpressionAnalysisService; @Autowired private DifferentialExpressionResultService differentialExpressionResultService = null; private ExpressionExperiment ee; @Before public void setup() throws IOException { try (InputStream io = this.getClass() .getResourceAsStream( "/data/analysis/expression/GSE8441_expmat_8probes.txt" )) { SimpleExpressionExperimentMetaData metaData = new SimpleExpressionExperimentMetaData(); metaData.setShortName( RandomStringUtils.randomAlphabetic( 10 ) ); metaData.setTaxon( taxonService.findByCommonName( "mouse" ) ); metaData.setQuantitationTypeName( "whatever" ); // metaData.setScale( ScaleType.LOG2 ); // this is actually wrong! metaData.setScale( ScaleType.LINEAR ); ArrayDesign f = ArrayDesign.Factory.newInstance(); f.setShortName( "GSE8441_test" ); f.setTechnologyType( TechnologyType.ONECOLOR ); f.setPrimaryTaxon( metaData.getTaxon() ); metaData.getArrayDesigns().add( f ); ee = dataLoaderService.create( metaData, io ); designImporter.importDesign( ee, this.getClass().getResourceAsStream( "/data/analysis/expression/606_GSE8441_expdesign.data.txt" ) ); ee = expressionExperimentService.thaw( ee ); } } /* * NOTE I added a constant probe to this data after I set this up. * * <pre> * expMatFile &lt;- "GSE8441_expmat_8probes.txt" * expDesignFile &lt;- "606_GSE8441_expdesign.data.txt" * expMat &lt;- log2(read.table(expMatFile, header = TRUE, row.names = 1, sep = "\t", quote="")) * expDesign &lt;- read.table(expDesignFile, header = TRUE, row.names = 1, sep = "\t", quote="") * * expData &lt;- expMat[rownames(expDesign)] * * names(expData) == row.names(expDesign) * attach(expDesign) * lf&lt;-lm(unlist(expData["217757_at",])~Treatment*Sex ) * summary(lf) * anova(lf) * * summary(lm(unlist(expData["202851_at",])~Treatment*Sex )) * anova(lm(unlist(expData["202851_at",])~Treatment*Sex )) * * # etc. * </pre> */ @Test public void test() { AnalysisType aa = analysisService .determineAnalysis( ee, ee.getExperimentalDesign().getExperimentalFactors(), null, true ); assertEquals( AnalysisType.TWO_WAY_ANOVA_WITH_INTERACTION, aa ); DifferentialExpressionAnalysisConfig config = new DifferentialExpressionAnalysisConfig(); Collection<ExperimentalFactor> factors = ee.getExperimentalDesign().getExperimentalFactors(); assertEquals( 2, factors.size() ); config.setAnalysisType( aa ); config.setFactorsToInclude( factors ); config.getInteractionsToInclude().add( factors ); analyzer = this.getBean( DiffExAnalyzer.class ); Collection<DifferentialExpressionAnalysis> result = analyzer.run( ee, config ); assertEquals( 1, result.size() ); DifferentialExpressionAnalysis analysis = result.iterator().next(); this.checkResults( analysis ); Collection<DifferentialExpressionAnalysis> persistent = differentialExpressionAnalyzerService .runDifferentialExpressionAnalyses( ee, config ); DifferentialExpressionAnalysis refetched = differentialExpressionAnalysisService .load( persistent.iterator().next().getId() ); differentialExpressionAnalysisService.thaw( refetched ); for ( ExpressionAnalysisResultSet ears : refetched.getResultSets() ) { differentialExpressionResultService.thaw( ears ); } this.checkResults( refetched ); differentialExpressionAnalyzerService.redoAnalysis( ee, refetched, true ); } public void checkResults( DifferentialExpressionAnalysis analysis ) { Collection<ExpressionAnalysisResultSet> resultSets = analysis.getResultSets(); assertEquals( 3, resultSets.size() ); boolean found1 = false, found2 = false, found3 = false, found4 = false; for ( ExpressionAnalysisResultSet rs : resultSets ) { boolean interaction = false; boolean sexFactor = false; Collection<DifferentialExpressionAnalysisResult> results = rs.getResults(); if ( rs.getExperimentalFactors().size() == 1 ) { ExperimentalFactor factor = rs.getExperimentalFactors().iterator().next(); sexFactor = factor.getName().equals( "Sex" ); } else { interaction = true; } assertEquals( 8, results.size() ); /* * Test values here are computed in R, using anova(lm(unlist(expData["205969_at",])~Treatment*Sex )) etc. */ for ( DifferentialExpressionAnalysisResult r : results ) { CompositeSequence probe = r.getProbe(); Double pvalue = r.getPvalue(); switch ( probe.getName() ) { case "205969_at": if ( sexFactor ) { found1 = true; assertEquals( 0.3333, pvalue, 0.001 ); } else if ( interaction ) { found2 = true; assertEquals( 0.8480, pvalue, 0.001 ); } else { found3 = true; assertEquals( 0.1323, pvalue, 0.001 ); } break; case "217757_at": if ( interaction ) { found4 = true; assertEquals( 0.7621, pvalue, 0.001 ); } break; case "constant": fail( "Should not have found a result for constant probe" ); break; } } } assertTrue( found1 && found2 && found3 && found4 ); } }
package com.ravidev.restclient; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import android.support.v4.util.ArrayMap; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Created by ravishankeryadav on 8/27/2016. */ public class RestClientHelper { private static final String LOG_TAG = "RestClientHelper"; public static String defaultBaseUrl = ""; private static final Object lockObject = new Object(); private static RestClientHelper restClientHelper; private final Handler handler = new Handler(Looper.getMainLooper()); private RestClientHelper() { } public interface RestClientListener { void onSuccess(String response); void onError(String error); } public static RestClientHelper getInstance() { if (restClientHelper == null) synchronized (lockObject) { if (restClientHelper == null) restClientHelper = new RestClientHelper(); } return restClientHelper; } private final Executor executor; { ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { @Override public Thread newThread(@NonNull final Runnable r) { return new Thread(r, LOG_TAG + "Thread"); } }); executor.allowCoreThreadTimeOut(true); this.executor = executor; } private void addHeaders(Request.Builder builder, @NonNull ArrayMap<String, String> headers) { for (String key : headers.keySet()) { builder.addHeader(key, headers.get(key)); } } public void get(@NonNull String serviceUrl, @NonNull RestClientListener restClientListener) { get(serviceUrl, null, null, restClientListener); } public void get(@NonNull String serviceUrl, ArrayMap<String, Object> params, @NonNull RestClientListener restClientListener) { get(serviceUrl, null, params, restClientListener); } public void get(@NonNull String serviceUrl, ArrayMap<String, String> headers, ArrayMap<String, Object> params, RestClientListener restClientListener) { final Request.Builder builder = new Request.Builder(); if (headers != null) addHeaders(builder, headers); builder.url(generateUrlParams(serviceUrl, params)); execute(builder, restClientListener); } public void post(@NonNull String serviceUrl, @NonNull ArrayMap<String, Object> params, @NonNull RestClientListener restClientListener) { post(serviceUrl, null, params, restClientListener); } public void post(@NonNull String serviceUrl, ArrayMap<String, String> headers, @NonNull ArrayMap<String, Object> params, @NonNull RestClientListener restClientListener) { final Request.Builder builder = new Request.Builder(); if (headers != null) addHeaders(builder, headers); StringBuffer urls = new StringBuffer(); if (defaultBaseUrl.length() > 0) urls.append(defaultBaseUrl); urls.append(serviceUrl); builder.url(urls.toString()); builder.post(generateRequestBody(params)); execute(builder, restClientListener); } public void put(@NonNull String serviceUrl, @NonNull ArrayMap<String, Object> params, @NonNull RestClientListener restClientListener) { put(serviceUrl, null, params, restClientListener); } public void put(@NonNull String serviceUrl, ArrayMap<String, String> headers, @NonNull ArrayMap<String, Object> params, @NonNull RestClientListener restClientListener) { final Request.Builder builder = new Request.Builder(); if (headers != null) addHeaders(builder, headers); StringBuffer urls = new StringBuffer(); if (defaultBaseUrl.length() > 0) urls.append(defaultBaseUrl); urls.append(serviceUrl); builder.url(urls.toString()); builder.put(generateRequestBody(params)); execute(builder, restClientListener); } public void delete(@NonNull String serviceUrl, @NonNull ArrayMap<String, Object> params, @NonNull RestClientListener restClientListener) { delete(serviceUrl, null, params, restClientListener); } public void delete(@NonNull String serviceUrl, ArrayMap<String, String> headers, @NonNull ArrayMap<String, Object> params, @NonNull RestClientListener restClientListener) { final Request.Builder builder = new Request.Builder(); if (headers != null) addHeaders(builder, headers); StringBuffer urls = new StringBuffer(); if (defaultBaseUrl.length() > 0) urls.append(defaultBaseUrl); urls.append(serviceUrl); builder.url(urls.toString()); builder.delete(generateRequestBody(params)); execute(builder, restClientListener); } public void postMultipart(@NonNull String serviceUrl, @NonNull ArrayMap<String, File> files, @NonNull RestClientListener restClientListener) { postMultipart(serviceUrl, null, null, files, restClientListener); } public void postMultipart(@NonNull String serviceUrl, ArrayMap<String, Object> params, @NonNull ArrayMap<String, File> files, @NonNull RestClientListener restClientListener) { postMultipart(serviceUrl, null, params, files, restClientListener); } public void postMultipart(@NonNull String serviceUrl, ArrayMap<String, String> headers, ArrayMap<String, Object> params, @NonNull ArrayMap<String, File> files, @NonNull RestClientListener restClientListener) { final Request.Builder builder = new Request.Builder(); if (headers != null) addHeaders(builder, headers); StringBuffer urls = new StringBuffer(); if (defaultBaseUrl.length() > 0) urls.append(defaultBaseUrl); urls.append(serviceUrl); builder.url(urls.toString()); builder.post(generateMultipartBody(params, files)); execute(builder, restClientListener); } private void execute(final Request.Builder builder, final RestClientListener restClientListener) { executor.execute(new Runnable() { @Override public void run() { final OkHttpClient client = new OkHttpClient.Builder().connectTimeout(2, TimeUnit.MINUTES).writeTimeout(2, TimeUnit.MINUTES).readTimeout(2, TimeUnit.MINUTES).build(); try { System.setProperty("http.keepAlive", "false"); final Response response = client.newCall(builder.build()).execute(); final String responseData = response.body().string(); handler.post(new Runnable() { @Override public void run() { if (response.code() == 200) { restClientListener.onSuccess(responseData); } else { restClientListener.onError(responseData); } } }); } catch (IOException e) { e.printStackTrace(); handler.post(new Runnable() { @Override public void run() { restClientListener.onError("APIs not working..."); } }); } } }); } private String generateUrlParams(String serviceUrl, ArrayMap<String, Object> params) { final StringBuffer urls = new StringBuffer(); if (defaultBaseUrl.length() > 0) urls.append(defaultBaseUrl); urls.append(serviceUrl); if (params != null) { int i = 0; for (String key : params.keySet()) { if (i == 0) { urls.append("?" + key + "=" + params.get(key)); } else { urls.append("&" + key + "=" + params.get(key)); } i++; } } return urls.toString(); } private RequestBody generateRequestBody(ArrayMap<String, Object> params) { final JSONObject jsonObj = new JSONObject(); if (params != null) { for (String key : params.keySet()) { try { jsonObj.put(key, params.get(key)); } catch (JSONException e) { e.printStackTrace(); } } } RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), String.valueOf(jsonObj)); return requestBody; } private RequestBody generateMultipartBody(ArrayMap<String, Object> params, ArrayMap<String, File> files) { final MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM); if (params != null) { for (String key : params.keySet()) { builder.addFormDataPart(key, String.valueOf(params.get(key))); } } if (files != null) { for (String key : files.keySet()) { builder.addFormDataPart(key, key, RequestBody.create(MediaType.parse("image/png"), files.get(key))); } } return builder.build(); } }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.infobar; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import org.chromium.chrome.R; import org.chromium.chrome.browser.infobar.InfoBarContainer.InfoBarAnimationListener; import java.util.ArrayList; /** * Layout that displays infobars in a stack. Handles all the animations when adding or removing * infobars and when swapping infobar contents. * * The first infobar to be added is visible at the front of the stack. Later infobars peek up just * enough behind the front infobar to signal their existence; their contents aren't visible at all. * The stack has a max depth of three infobars. If additional infobars are added beyond this, they * won't be visible at all until infobars in front of them are dismissed. * * Animation details: * - Newly added infobars slide up from the bottom and then their contents fade in. * - Disappearing infobars slide down and away. The remaining infobars, if any, resize to the * new front infobar's size, then the content of the new front infobar fades in. * - When swapping the front infobar's content, the old content fades out, the infobar resizes to * the new content's size, then the new content fades in. * - Only a single animation happens at a time. If several infobars are added and/or removed in * quick succession, the animations will be queued and run sequentially. * * Note: this class depends only on Android view code; it intentionally does not depend on any other * infobar code. This is an explicit design decision and should remain this way. * * TODO(newt): what happens when detached from window? Do animations run? Do animations jump to end * values? Should they jump to end values? Does requestLayout() get called when detached * from window? Probably not; it probably just gets called later when reattached. * * TODO(newt): use hardware acceleration? See * http://blog.danlew.net/2015/10/20/using-hardware-layers-to-improve-animation-performance/ * and http://developer.android.com/guide/topics/graphics/hardware-accel.html#layers * * TODO(newt): handle tall infobars on small devices. Use a ScrollView inside the InfoBarWrapper? * Make sure InfoBarContainerLayout doesn't extend into tabstrip on tablet. * * TODO(newt): Disable key events during animations, perhaps by overriding dispatchKeyEvent(). * Or can we just call setEnabled() false on the infobar wrapper? Will this cause the buttons * visual state to change (i.e. to turn gray)? * * TODO(newt): finalize animation timings and interpolators. */ class InfoBarContainerLayout extends FrameLayout { /** * An interface for items that can be added to an InfoBarContainerLayout. */ interface Item { /** * Returns the View that represents this infobar. This should have no background or borders; * a background and shadow will be added by a wrapper view. */ View getView(); /** * Returns whether controls for this View should be clickable. If false, all input events on * this item will be ignored. */ boolean areControlsEnabled(); /** * Sets whether or not controls for this View should be clickable. This does not affect the * visual state of the infobar. * @param state If false, all input events on this Item will be ignored. */ void setControlsEnabled(boolean state); /** * Returns the accessibility text to announce when this infobar is first shown. */ CharSequence getAccessibilityText(); } /** * Creates an empty InfoBarContainerLayout. */ InfoBarContainerLayout(Context context) { super(context); Resources res = context.getResources(); mBackInfobarHeight = res.getDimensionPixelSize(R.dimen.infobar_peeking_height); mFloatingBehavior = new FloatingBehavior(this); } /** * Adds an infobar to the container. The infobar appearing animation will happen after the * current animation, if any, finishes. */ void addInfoBar(Item item) { mItems.add(item); processPendingAnimations(); } /** * Removes an infobar from the container. The infobar will be animated off the screen if it's * currently visible. */ void removeInfoBar(Item item) { mItems.remove(item); processPendingAnimations(); } /** * Notifies that an infobar's View ({@link Item#getView}) has changed. If the * infobar is visible in the front of the stack, the infobar will fade out the old contents, * resize, then fade in the new contents. */ void notifyInfoBarViewChanged() { processPendingAnimations(); } /** * Returns true if any animations are pending or in progress. */ boolean isAnimating() { return mAnimation != null; } /** * Sets a listener to receive updates when each animation is complete. */ void setAnimationListener(InfoBarAnimationListener listener) { mAnimationListener = listener; } ///////////////////////////////////////// // Implementation details ///////////////////////////////////////// /** The maximum number of infobars visible at any time. */ private static final int MAX_STACK_DEPTH = 3; // Animation durations. private static final int DURATION_SLIDE_UP_MS = 250; private static final int DURATION_SLIDE_DOWN_MS = 250; private static final int DURATION_FADE_MS = 100; private static final int DURATION_FADE_OUT_MS = 200; /** * Base class for animations inside the InfoBarContainerLayout. * * Provides a standardized way to prepare for, run, and clean up after animations. Each subclass * should implement prepareAnimation(), createAnimator(), and onAnimationEnd() as needed. */ private abstract class InfoBarAnimation { private Animator mAnimator; final boolean isStarted() { return mAnimator != null; } final void start() { Animator.AnimatorListener listener = new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mAnimation = null; InfoBarAnimation.this.onAnimationEnd(); if (mAnimationListener != null) { mAnimationListener.notifyAnimationFinished(getAnimationType()); } processPendingAnimations(); } }; mAnimator = createAnimator(); mAnimator.addListener(listener); mAnimator.start(); } /** * Returns an animator that animates an InfoBarWrapper's y-translation from its current * value to endValue and updates the side shadow positions on each frame. */ ValueAnimator createTranslationYAnimator(final InfoBarWrapper wrapper, float endValue) { ValueAnimator animator = ValueAnimator.ofFloat(wrapper.getTranslationY(), endValue); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { wrapper.setTranslationY((float) animation.getAnimatedValue()); mFloatingBehavior.updateShadowPosition(); } }); return animator; } /** * Called before the animation begins. This is the time to add views to the hierarchy and * adjust layout parameters. */ void prepareAnimation() {} /** * Called to create an Animator which will control the animation. Called after * prepareAnimation() and after a subsequent layout has happened. */ abstract Animator createAnimator(); /** * Called after the animation completes. This is the time to do post-animation cleanup, such * as removing views from the hierarchy. */ void onAnimationEnd() {} /** * Returns the InfoBarAnimationListener.ANIMATION_TYPE_* constant that corresponds to this * type of animation (showing, swapping, etc). */ abstract int getAnimationType(); } /** * The animation to show the first infobar. The infobar slides up from the bottom; then its * content fades in. */ private class FrontInfoBarAppearingAnimation extends InfoBarAnimation { private Item mFrontItem; private InfoBarWrapper mFrontWrapper; private View mFrontContents; FrontInfoBarAppearingAnimation(Item frontItem) { mFrontItem = frontItem; } @Override void prepareAnimation() { mFrontContents = mFrontItem.getView(); mFrontWrapper = new InfoBarWrapper(getContext(), mFrontItem); mFrontWrapper.addView(mFrontContents); addWrapper(mFrontWrapper); } @Override Animator createAnimator() { mFrontWrapper.setTranslationY(mFrontWrapper.getHeight()); mFrontContents.setAlpha(0f); AnimatorSet animator = new AnimatorSet(); animator.playSequentially( createTranslationYAnimator(mFrontWrapper, 0f) .setDuration(DURATION_SLIDE_UP_MS), ObjectAnimator.ofFloat(mFrontContents, View.ALPHA, 1f) .setDuration(DURATION_FADE_MS)); return animator; } @Override void onAnimationEnd() { announceForAccessibility(mFrontItem.getAccessibilityText()); } @Override int getAnimationType() { return InfoBarAnimationListener.ANIMATION_TYPE_SHOW; } } /** * The animation to show a back infobar. The infobar slides up behind the existing infobars, so * its top edge peeks out just a bit. */ private class BackInfoBarAppearingAnimation extends InfoBarAnimation { private InfoBarWrapper mAppearingWrapper; BackInfoBarAppearingAnimation(Item appearingItem) { mAppearingWrapper = new InfoBarWrapper(getContext(), appearingItem); } @Override void prepareAnimation() { addWrapper(mAppearingWrapper); } @Override Animator createAnimator() { mAppearingWrapper.setTranslationY(mAppearingWrapper.getHeight()); return createTranslationYAnimator(mAppearingWrapper, 0f) .setDuration(DURATION_SLIDE_UP_MS); } @Override int getAnimationType() { return InfoBarAnimationListener.ANIMATION_TYPE_SHOW; } } /** * The animation to hide the front infobar and reveal the second-to-front infobar. The front * infobar slides down and off the screen. The back infobar(s) will adjust to the size of the * new front infobar, and then the new front infobar's contents will fade in. */ private class FrontInfoBarDisappearingAndRevealingAnimation extends InfoBarAnimation { private InfoBarWrapper mOldFrontWrapper; private InfoBarWrapper mNewFrontWrapper; private View mNewFrontContents; @Override void prepareAnimation() { mOldFrontWrapper = mInfoBarWrappers.get(0); mNewFrontWrapper = mInfoBarWrappers.get(1); mNewFrontContents = mNewFrontWrapper.getItem().getView(); mNewFrontWrapper.addView(mNewFrontContents); } @Override Animator createAnimator() { // The amount by which mNewFrontWrapper will grow (negative value indicates shrinking). int deltaHeight = (mNewFrontWrapper.getHeight() - mBackInfobarHeight) - mOldFrontWrapper.getHeight(); int startTranslationY = Math.max(deltaHeight, 0); int endTranslationY = Math.max(-deltaHeight, 0); // Slide the front infobar down and away. AnimatorSet animator = new AnimatorSet(); mOldFrontWrapper.setTranslationY(startTranslationY); animator.play(createTranslationYAnimator(mOldFrontWrapper, startTranslationY + mOldFrontWrapper.getHeight()) .setDuration(DURATION_SLIDE_UP_MS)); // Slide the other infobars to their new positions. // Note: animator.play() causes these animations to run simultaneously. for (int i = 1; i < mInfoBarWrappers.size(); i++) { mInfoBarWrappers.get(i).setTranslationY(startTranslationY); animator.play(createTranslationYAnimator(mInfoBarWrappers.get(i), endTranslationY).setDuration(DURATION_SLIDE_UP_MS)); } mNewFrontContents.setAlpha(0f); animator.play(ObjectAnimator.ofFloat(mNewFrontContents, View.ALPHA, 1f) .setDuration(DURATION_FADE_MS)).after(DURATION_SLIDE_UP_MS); return animator; } @Override void onAnimationEnd() { mOldFrontWrapper.removeAllViews(); removeWrapper(mOldFrontWrapper); for (int i = 0; i < mInfoBarWrappers.size(); i++) { mInfoBarWrappers.get(i).setTranslationY(0); } announceForAccessibility(mNewFrontWrapper.getItem().getAccessibilityText()); } @Override int getAnimationType() { return InfoBarAnimationListener.ANIMATION_TYPE_HIDE; } } /** * The animation to hide the backmost infobar, or the front infobar if there's only one infobar. * The infobar simply slides down out of the container. */ private class InfoBarDisappearingAnimation extends InfoBarAnimation { private InfoBarWrapper mDisappearingWrapper; @Override void prepareAnimation() { mDisappearingWrapper = mInfoBarWrappers.get(mInfoBarWrappers.size() - 1); } @Override Animator createAnimator() { return createTranslationYAnimator(mDisappearingWrapper, mDisappearingWrapper.getHeight()) .setDuration(DURATION_SLIDE_DOWN_MS); } @Override void onAnimationEnd() { mDisappearingWrapper.removeAllViews(); removeWrapper(mDisappearingWrapper); } @Override int getAnimationType() { return InfoBarAnimationListener.ANIMATION_TYPE_HIDE; } } /** * The animation to swap the contents of the front infobar. The current contents fade out, * then the infobar resizes to fit the new contents, then the new contents fade in. */ private class FrontInfoBarSwapContentsAnimation extends InfoBarAnimation { private InfoBarWrapper mFrontWrapper; private View mOldContents; private View mNewContents; @Override void prepareAnimation() { mFrontWrapper = mInfoBarWrappers.get(0); mOldContents = mFrontWrapper.getChildAt(0); mNewContents = mFrontWrapper.getItem().getView(); mFrontWrapper.addView(mNewContents); } @Override Animator createAnimator() { int deltaHeight = mNewContents.getHeight() - mOldContents.getHeight(); InfoBarContainerLayout.this.setTranslationY(Math.max(0, deltaHeight)); mNewContents.setAlpha(0f); AnimatorSet animator = new AnimatorSet(); animator.playSequentially( ObjectAnimator.ofFloat(mOldContents, View.ALPHA, 0f) .setDuration(DURATION_FADE_OUT_MS), ObjectAnimator.ofFloat(InfoBarContainerLayout.this, View.TRANSLATION_Y, Math.max(0, -deltaHeight)).setDuration(DURATION_SLIDE_UP_MS), ObjectAnimator.ofFloat(mNewContents, View.ALPHA, 1f) .setDuration(DURATION_FADE_OUT_MS)); return animator; } @Override void onAnimationEnd() { mFrontWrapper.removeViewAt(0); InfoBarContainerLayout.this.setTranslationY(0f); mFrontWrapper.getItem().setControlsEnabled(true); announceForAccessibility(mFrontWrapper.getItem().getAccessibilityText()); } @Override int getAnimationType() { return InfoBarAnimationListener.ANIMATION_TYPE_SWAP; } } /** * Controls whether infobars fill the full available width, or whether they "float" in the * middle of the available space. The latter case happens if the available space is wider than * the max width allowed for infobars. * * Also handles the shadows on the sides of the infobars in floating mode. The side shadows are * separate views -- rather than being part of each InfoBarWrapper -- to avoid a double-shadow * effect, which would happen during animations when two InfoBarWrappers overlap each other. */ private static class FloatingBehavior { /** The InfoBarContainerLayout. */ private FrameLayout mLayout; /** * The max width of the infobars. If the available space is wider than this, the infobars * will switch to floating mode. */ private final int mMaxWidth; /** The width of the left and right shadows. */ private final int mShadowWidth; /** Whether the layout is currently floating. */ private boolean mIsFloating; /** The shadows that appear on the sides of the infobars in floating mode. */ private View mLeftShadowView; private View mRightShadowView; FloatingBehavior(FrameLayout layout) { mLayout = layout; Resources res = mLayout.getContext().getResources(); mMaxWidth = res.getDimensionPixelSize(R.dimen.infobar_max_width); mShadowWidth = res.getDimensionPixelSize(R.dimen.infobar_shadow_width); } /** * This should be called in onMeasure() before super.onMeasure(). The return value is a new * widthMeasureSpec that should be passed to super.onMeasure(). */ int beforeOnMeasure(int widthMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); boolean isFloating = width > mMaxWidth; if (isFloating != mIsFloating) { mIsFloating = isFloating; onIsFloatingChanged(); } if (isFloating) { int mode = MeasureSpec.getMode(widthMeasureSpec); width = Math.min(width, mMaxWidth + 2 * mShadowWidth); widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, mode); } return widthMeasureSpec; } /** * This should be called in onMeasure() after super.onMeasure(). */ void afterOnMeasure(int measuredHeight) { if (!mIsFloating) return; // Measure side shadows to match the parent view's height. int widthSpec = MeasureSpec.makeMeasureSpec(mShadowWidth, MeasureSpec.EXACTLY); int heightSpec = MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY); mLeftShadowView.measure(widthSpec, heightSpec); mRightShadowView.measure(widthSpec, heightSpec); } /** * This should be called whenever the Y-position of an infobar changes. */ void updateShadowPosition() { if (!mIsFloating) return; float minY = mLayout.getHeight(); int childCount = mLayout.getChildCount(); for (int i = 0; i < childCount; i++) { View child = mLayout.getChildAt(i); if (child != mLeftShadowView && child != mRightShadowView) { minY = Math.min(minY, child.getY()); } } mLeftShadowView.setY(minY); mRightShadowView.setY(minY); } private void onIsFloatingChanged() { if (mIsFloating) { initShadowViews(); mLayout.setPadding(mShadowWidth, 0, mShadowWidth, 0); mLayout.setClipToPadding(false); mLayout.addView(mLeftShadowView); mLayout.addView(mRightShadowView); } else { mLayout.setPadding(0, 0, 0, 0); mLayout.removeView(mLeftShadowView); mLayout.removeView(mRightShadowView); } } @SuppressLint("RtlHardcoded") private void initShadowViews() { if (mLeftShadowView != null) return; mLeftShadowView = new View(mLayout.getContext()); mLeftShadowView.setBackgroundResource(R.drawable.infobar_shadow_left); LayoutParams leftLp = new FrameLayout.LayoutParams(0, 0, Gravity.LEFT); leftLp.leftMargin = -mShadowWidth; mLeftShadowView.setLayoutParams(leftLp); mRightShadowView = new View(mLayout.getContext()); mRightShadowView.setBackgroundResource(R.drawable.infobar_shadow_left); LayoutParams rightLp = new FrameLayout.LayoutParams(0, 0, Gravity.RIGHT); rightLp.rightMargin = -mShadowWidth; mRightShadowView.setScaleX(-1f); mRightShadowView.setLayoutParams(rightLp); } } /** * The height of back infobars, i.e. the distance between the top of the front infobar and the * top of the next infobar back. */ private final int mBackInfobarHeight; /** * All the Items, in front to back order. * This list is updated immediately when addInfoBar(), removeInfoBar(), and swapInfoBar() are * called; so during animations, it does *not* match the currently visible views. */ private final ArrayList<Item> mItems = new ArrayList<>(); /** * The currently visible InfoBarWrappers, in front to back order. */ private final ArrayList<InfoBarWrapper> mInfoBarWrappers = new ArrayList<>(); /** The current animation, or null if no animation is happening currently. */ private InfoBarAnimation mAnimation; private InfoBarAnimationListener mAnimationListener; private FloatingBehavior mFloatingBehavior; /** * Determines whether any animations need to run in order to make the visible views match the * current list of Items in mItems. If so, kicks off the next animation that's needed. */ private void processPendingAnimations() { // If an animation is running, wait until it finishes before beginning the next animation. if (mAnimation != null) return; // The steps below are ordered to minimize movement during animations. In particular, // removals happen before additions or swaps, and changes are made to back infobars before // front infobars. // First, remove any infobars that are no longer in mItems, if any. Check the back infobars // before the front. for (int i = mInfoBarWrappers.size() - 1; i >= 0; i--) { Item visibleItem = mInfoBarWrappers.get(i).getItem(); if (!mItems.contains(visibleItem)) { if (i == 0 && mInfoBarWrappers.size() >= 2) { // Remove the front infobar and reveal the second-to-front infobar. runAnimation(new FrontInfoBarDisappearingAndRevealingAnimation()); return; } else { // Move the infobar to the very back if it's not already there. InfoBarWrapper wrapper = mInfoBarWrappers.get(i); if (i != mInfoBarWrappers.size() - 1) { removeWrapper(wrapper); addWrapper(wrapper); } // Remove the backmost infobar (which may be the front infobar). runAnimation(new InfoBarDisappearingAnimation()); return; } } } // Second, run swap animation on front infobar if needed. if (!mInfoBarWrappers.isEmpty()) { Item frontItem = mInfoBarWrappers.get(0).getItem(); View frontContents = mInfoBarWrappers.get(0).getChildAt(0); if (frontContents != frontItem.getView()) { runAnimation(new FrontInfoBarSwapContentsAnimation()); return; } } // Third, check if we should add any infobars. int desiredChildCount = Math.min(mItems.size(), MAX_STACK_DEPTH); if (mInfoBarWrappers.size() < desiredChildCount) { Item itemToShow = mItems.get(mInfoBarWrappers.size()); runAnimation(mInfoBarWrappers.isEmpty() ? new FrontInfoBarAppearingAnimation(itemToShow) : new BackInfoBarAppearingAnimation(itemToShow)); } } private void runAnimation(InfoBarAnimation animation) { mAnimation = animation; mAnimation.prepareAnimation(); if (isLayoutRequested()) { // onLayout() will call mAnimation.start(). } else { mAnimation.start(); } } private void addWrapper(InfoBarWrapper wrapper) { addView(wrapper, 0, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); mInfoBarWrappers.add(wrapper); updateLayoutParams(); } private void removeWrapper(InfoBarWrapper wrapper) { removeView(wrapper); mInfoBarWrappers.remove(wrapper); updateLayoutParams(); } private void updateLayoutParams() { // Stagger the top margins so the back infobars peek out a bit. int childCount = mInfoBarWrappers.size(); for (int i = 0; i < childCount; i++) { View child = mInfoBarWrappers.get(i); LayoutParams lp = (LayoutParams) child.getLayoutParams(); lp.topMargin = (childCount - 1 - i) * mBackInfobarHeight; child.setLayoutParams(lp); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { widthMeasureSpec = mFloatingBehavior.beforeOnMeasure(widthMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); mFloatingBehavior.afterOnMeasure(getMeasuredHeight()); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); mFloatingBehavior.updateShadowPosition(); // Animations start after a layout has completed, at which point all views are guaranteed // to have valid sizes and positions. if (mAnimation != null && !mAnimation.isStarted()) { mAnimation.start(); } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { // Trap any attempts to fiddle with the infobars while we're animating. return super.onInterceptTouchEvent(ev) || mAnimation != null || (!mInfoBarWrappers.isEmpty() && !mInfoBarWrappers.get(0).getItem().areControlsEnabled()); } @Override @SuppressLint("ClickableViewAccessibility") public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); // Consume all touch events so they do not reach the ContentView. return true; } @Override public boolean onHoverEvent(MotionEvent event) { super.onHoverEvent(event); // Consume all hover events so they do not reach the ContentView. In touch exploration mode, // this prevents the user from interacting with the part of the ContentView behind the // infobars. http://crbug.com/430701 return true; } }
/** * Copyright (C) 2012 KRM Associates, Inc. healtheme@krminc.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. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.krminc.phr.api.vitals.converter; import com.krminc.phr.api.converter.DateAdapter; import com.krminc.phr.api.converter.UserConverter; import com.krminc.phr.api.converter.util.ConverterUtils; import com.krminc.phr.domain.HealthRecord; import com.krminc.phr.domain.User; import com.krminc.phr.domain.vitals.BloodSugar; import java.math.BigInteger; import java.net.URI; import java.util.Date; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlAttribute; import javax.ws.rs.core.UriBuilder; import javax.persistence.EntityManager; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * * @author cmccall */ @XmlRootElement(name = "bloodSugar") public class BloodSugarConverter { private BloodSugar entity; private URI uri; private int expandLevel; public boolean hasError = false; /** Creates a new instance of BloodSugarConverter */ public BloodSugarConverter() { entity = new BloodSugar(); } /** * Creates a new instance of BloodSugarConverter. * * @param entity associated entity * @param uri associated uri * @param expandLevel indicates the number of levels the entity graph should be expanded@param isUriExtendable indicates whether the uri can be extended */ public BloodSugarConverter(BloodSugar entity, URI uri, int expandLevel, boolean isUriExtendable) { this.entity = entity; this.uri = (isUriExtendable) ? UriBuilder.fromUri(uri).path(entity.getBloodSugarId() + "/").build() : uri; this.expandLevel = expandLevel; } /** * Creates a new instance of BloodSugarConverter. * * @param entity associated entity * @param uri associated uri * @param expandLevel indicates the number of levels the entity graph should be expanded */ public BloodSugarConverter(BloodSugar entity, URI uri, int expandLevel) { this(entity, uri, expandLevel, false); } /** * Getter for bloodsugarId. * * @return value for bloodsugarId */ @XmlElement public Long getId() { return (expandLevel > 0) ? entity.getBloodSugarId() : null; } /** * Setter for bloodsugarId. * * @param value the value to set */ public void setId(Long value) { try { entity.setBloodSugarId(value); } catch(Exception ex) { hasError = true; } } /** * Getter for bloodSugarLevel. * * @return value for bloodSugarLevel */ @XmlElement public String getBloodSugarLevel() { return (expandLevel > 0) ? entity.getBloodSugarLevel() : null; } /** * Setter for bloodsugarLevel. * * @param value the value to set */ public void setBloodSugarLevel(String value) { try { value = ConverterUtils.prepareInput(value); entity.setBloodSugarLevel(value); } catch(Exception ex) { hasError = true; } } /** * Getter for method. * * @return value for method */ @XmlElement public String getMethod() { return (expandLevel > 0) ? entity.getMethod() : null; } /** * Setter for method. * * @param value the value to set */ public void setMethod(String value) { try { value = ConverterUtils.prepareInput(value); entity.setMethod(value); } catch(Exception ex) { hasError = true; } } /** * Getter for unit. * * @return value for unit */ @XmlElement public String getUnit() { return (expandLevel > 0) ? entity.getUnit() : null; } /** * Setter for unit. * * @param value the value to set */ public void setUnit(String value) { try { value = ConverterUtils.prepareInput(value); entity.setUnit(value); } catch(Exception ex) { hasError = true; } } /** * Getter for observedDate. * * @return value for observedDate */ @XmlElement @XmlJavaTypeAdapter(DateAdapter.class) public Date getObservedDate() { return (expandLevel > 0) ? entity.getObservedDate() : null; } /** * Setter for observedDate. * * @param value the value to set */ public void setObservedDate(Date value) { try { entity.setObservedDate(value); } catch(Exception ex) { hasError = true; } } /** * Getter for addedDate. * * @return value for addedDate */ @XmlElement @XmlJavaTypeAdapter(DateAdapter.class) public Date getDateAdded() { return (expandLevel > 0) ? entity.getDateAdded() : null; } /** * Getter for HealthRecordId. * * @return value for HealthRecordId */ @XmlElement public Long getHealthRecordId() { return (expandLevel > 0) ? entity.getHealthRecordId() : null; } /** * Setter for HealthRecordId. * * @param value the value to set */ public void setHealthRecordId(Long value) { try { entity.setHealthRecordId(value); } catch(Exception ex) { hasError = true; } } /** * Getter for sourceId. * * @return value for sourceId */ @XmlElement public Long getSourceId() { return (expandLevel > 0) ? entity.getSourceId() : null; } /** * Setter for sourceId. * * @param value the value to set */ public void setSourceId(Long value) { try { if (value != 1) { throw new Exception(); } entity.setSourceId(value); } catch(Exception ex) { hasError = true; } } /** * Getter for careDocumentId. * * @return value for careDocumentId */ @XmlElement public BigInteger getCareDocumentId() { return (expandLevel > 0) ? entity.getCareDocumentId() : null; } /** * Setter for careDocumentId. * * @param value the value to set */ public void setCareDocumentId(BigInteger value) { try { entity.setCareDocumentId(value); } catch(Exception ex) { hasError = true; } } /** * Getter for mask. * * @return value for mask */ @XmlElement public String getMask() { return (expandLevel > 0) ? entity.getMask() : null; } /** * Setter for mask. * * @param value the value to set */ public void setMask(String value) { try { if (ConverterUtils.isValidMask(value)) { entity.setMask(value.trim()); } else { throw new Exception(); } } catch(Exception ex) { hasError = true; } } /** * Getter for dataSourceId. * * @return value for dataSourceId */ @XmlElement public Long getDataSourceId() { return (expandLevel > 0) ? entity.getDataSourceId() : null; } /** * Setter for dataSourceId. * * @param value the value to set */ public void setDataSourceId(Long value) { try { if (value != 1) { throw new Exception(); } entity.setDataSourceId(value); } catch(Exception ex) { hasError = true; } } /** * Returns the URI associated with this converter. * * @return the uri */ @XmlAttribute public URI getUri() { return uri; } /** * Sets the URI for this reference converter. * */ public void setUri(URI uri) { try { this.uri = uri; } catch(Exception ex) { hasError = true; } } /** * Returns the BloodSugar entity. * * @return an entity */ @XmlTransient public BloodSugar getEntity() { if (entity.getBloodSugarId() == null) { BloodSugarConverter converter = UriResolver.getInstance().resolve(BloodSugarConverter.class, uri); if (converter != null) { entity = converter.getEntity(); } } return entity; } /** * Returns the resolved BloodSugar entity. * * @return an resolved entity */ public BloodSugar resolveEntity(EntityManager em) { HealthRecord healthRecord = entity.getHealthRecord(); if (healthRecord != null) { entity.setHealthRecord(em.getReference(HealthRecord.class, healthRecord.getHealthRecordId())); } return entity; } }
/* * Open Payments Cloud Application API * Open Payments Cloud API * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.ixaris.ope.applications.client.model; import java.util.Objects; import com.google.gson.annotations.SerializedName; import com.ixaris.ope.applications.client.model.CurrencyAmountMessage; import com.ixaris.ope.applications.client.model.Fee; import com.ixaris.ope.applications.client.model.TypedId; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; /** * CreateExternalAccountDepositParams */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-30T15:46:40.836+02:00") public class CreateExternalAccountDepositParams { @SerializedName("profileId") private String profileId = null; @SerializedName("amount") private CurrencyAmountMessage amount = null; @SerializedName("sourceInstrumentId") private TypedId sourceInstrumentId = null; @SerializedName("sourcePayinId") private String sourcePayinId = null; @SerializedName("destinationInstrumentId") private TypedId destinationInstrumentId = null; @SerializedName("fees") private List<Fee> fees = new ArrayList<Fee>(); public CreateExternalAccountDepositParams profileId(String profileId) { this.profileId = profileId; return this; } /** * Get profileId * @return profileId **/ @ApiModelProperty(example = "null", required = true, value = "") public String getProfileId() { return profileId; } public void setProfileId(String profileId) { this.profileId = profileId; } public CreateExternalAccountDepositParams amount(CurrencyAmountMessage amount) { this.amount = amount; return this; } /** * The amount to deposit into the external account. Amount currency must be the same as the payin currency. The polarity should be positive. * @return amount **/ @ApiModelProperty(example = "null", required = true, value = "The amount to deposit into the external account. Amount currency must be the same as the payin currency. The polarity should be positive.") public CurrencyAmountMessage getAmount() { return amount; } public void setAmount(CurrencyAmountMessage amount) { this.amount = amount; } public CreateExternalAccountDepositParams sourceInstrumentId(TypedId sourceInstrumentId) { this.sourceInstrumentId = sourceInstrumentId; return this; } /** * The ID of the instrument from which funds will be taken. This must be an external instrument where the type is `external_accounts`. * @return sourceInstrumentId **/ @ApiModelProperty(example = "null", required = true, value = "The ID of the instrument from which funds will be taken. This must be an external instrument where the type is `external_accounts`.") public TypedId getSourceInstrumentId() { return sourceInstrumentId; } public void setSourceInstrumentId(TypedId sourceInstrumentId) { this.sourceInstrumentId = sourceInstrumentId; } public CreateExternalAccountDepositParams sourcePayinId(String sourcePayinId) { this.sourcePayinId = sourcePayinId; return this; } /** * The ID of the payin instruction that was used to load funds into the system. * @return sourcePayinId **/ @ApiModelProperty(example = "null", required = true, value = "The ID of the payin instruction that was used to load funds into the system.") public String getSourcePayinId() { return sourcePayinId; } public void setSourcePayinId(String sourcePayinId) { this.sourcePayinId = sourcePayinId; } public CreateExternalAccountDepositParams destinationInstrumentId(TypedId destinationInstrumentId) { this.destinationInstrumentId = destinationInstrumentId; return this; } /** * The ID of the instrument onto which funds will be deposited. This must be a managed instrument where the type is one of `managed_cards` and `managed_accounts`. * @return destinationInstrumentId **/ @ApiModelProperty(example = "null", required = true, value = "The ID of the instrument onto which funds will be deposited. This must be a managed instrument where the type is one of `managed_cards` and `managed_accounts`.") public TypedId getDestinationInstrumentId() { return destinationInstrumentId; } public void setDestinationInstrumentId(TypedId destinationInstrumentId) { this.destinationInstrumentId = destinationInstrumentId; } public CreateExternalAccountDepositParams fees(List<Fee> fees) { this.fees = fees; return this; } public CreateExternalAccountDepositParams addFeesItem(Fee feesItem) { this.fees.add(feesItem); return this; } /** * A set of fees to be applied to this transaction. * @return fees **/ @ApiModelProperty(example = "null", value = "A set of fees to be applied to this transaction.") public List<Fee> getFees() { return fees; } public void setFees(List<Fee> fees) { this.fees = fees; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateExternalAccountDepositParams createExternalAccountDepositParams = (CreateExternalAccountDepositParams) o; return Objects.equals(this.profileId, createExternalAccountDepositParams.profileId) && Objects.equals(this.amount, createExternalAccountDepositParams.amount) && Objects.equals(this.sourceInstrumentId, createExternalAccountDepositParams.sourceInstrumentId) && Objects.equals(this.sourcePayinId, createExternalAccountDepositParams.sourcePayinId) && Objects.equals(this.destinationInstrumentId, createExternalAccountDepositParams.destinationInstrumentId) && Objects.equals(this.fees, createExternalAccountDepositParams.fees); } @Override public int hashCode() { return Objects.hash(profileId, amount, sourceInstrumentId, sourcePayinId, destinationInstrumentId, fees); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CreateExternalAccountDepositParams {\n"); sb.append(" profileId: ").append(toIndentedString(profileId)).append("\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" sourceInstrumentId: ").append(toIndentedString(sourceInstrumentId)).append("\n"); sb.append(" sourcePayinId: ").append(toIndentedString(sourcePayinId)).append("\n"); sb.append(" destinationInstrumentId: ").append(toIndentedString(destinationInstrumentId)).append("\n"); sb.append(" fees: ").append(toIndentedString(fees)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.file; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Date; import java.util.List; import org.apache.camel.Exchange; import org.apache.camel.InvalidPayloadException; import org.apache.camel.util.ExchangeHelper; import org.apache.camel.util.FileUtil; import org.apache.camel.util.IOHelper; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * File operations for {@link java.io.File}. */ public class FileOperations implements GenericFileOperations<File> { private static final transient Logger LOG = LoggerFactory.getLogger(FileOperations.class); private FileEndpoint endpoint; public FileOperations() { } public FileOperations(FileEndpoint endpoint) { this.endpoint = endpoint; } public void setEndpoint(GenericFileEndpoint<File> endpoint) { this.endpoint = (FileEndpoint) endpoint; } public boolean deleteFile(String name) throws GenericFileOperationFailedException { File file = new File(name); return FileUtil.deleteFile(file); } public boolean renameFile(String from, String to) throws GenericFileOperationFailedException { File file = new File(from); File target = new File(to); return FileUtil.renameFile(file, target); } public boolean existsFile(String name) throws GenericFileOperationFailedException { File file = new File(name); return file.exists(); } public boolean buildDirectory(String directory, boolean absolute) throws GenericFileOperationFailedException { ObjectHelper.notNull(endpoint, "endpoint"); // always create endpoint defined directory if (endpoint.isAutoCreate() && !endpoint.getFile().exists()) { LOG.trace("Building starting directory: {}", endpoint.getFile()); endpoint.getFile().mkdirs(); } if (ObjectHelper.isEmpty(directory)) { // no directory to build so return true to indicate ok return true; } File endpointPath = endpoint.getFile(); File target = new File(directory); File path; if (absolute) { // absolute path path = target; } else if (endpointPath.equals(target)) { // its just the root of the endpoint path path = endpointPath; } else { // relative after the endpoint path String afterRoot = ObjectHelper.after(directory, endpointPath.getPath() + File.separator); if (ObjectHelper.isNotEmpty(afterRoot)) { // dir is under the root path path = new File(endpoint.getFile(), afterRoot); } else { // dir is relative to the root path path = new File(endpoint.getFile(), directory); } } // We need to make sure that this is thread-safe and only one thread tries to create the path directory at the same time. synchronized (this) { if (path.isDirectory() && path.exists()) { // the directory already exists return true; } else { if (LOG.isTraceEnabled()) { LOG.trace("Building directory: {}", path); } return path.mkdirs(); } } } public List<File> listFiles() throws GenericFileOperationFailedException { // noop return null; } public List<File> listFiles(String path) throws GenericFileOperationFailedException { // noop return null; } public void changeCurrentDirectory(String path) throws GenericFileOperationFailedException { // noop } public void changeToParentDirectory() throws GenericFileOperationFailedException { // noop } public String getCurrentDirectory() throws GenericFileOperationFailedException { // noop return null; } public boolean retrieveFile(String name, Exchange exchange) throws GenericFileOperationFailedException { // noop as we use type converters to read the body content for java.io.File return true; } public boolean storeFile(String fileName, Exchange exchange) throws GenericFileOperationFailedException { ObjectHelper.notNull(endpoint, "endpoint"); File file = new File(fileName); // if an existing file already exists what should we do? if (file.exists()) { if (endpoint.getFileExist() == GenericFileExist.Ignore) { // ignore but indicate that the file was written LOG.trace("An existing file already exists: {}. Ignore and do not override it.", file); return true; } else if (endpoint.getFileExist() == GenericFileExist.Fail) { throw new GenericFileOperationFailedException("File already exist: " + file + ". Cannot write new file."); } } // we can write the file by 3 different techniques // 1. write file to file // 2. rename a file from a local work path // 3. write stream to file try { // is the body file based File source = null; // get the File Object from in message source = exchange.getIn().getBody(File.class); if (source != null) { // okay we know the body is a file type // so try to see if we can optimize by renaming the local work path file instead of doing // a full file to file copy, as the local work copy is to be deleted afterwards anyway // local work path File local = exchange.getIn().getHeader(Exchange.FILE_LOCAL_WORK_PATH, File.class); if (local != null && local.exists()) { boolean renamed = writeFileByLocalWorkPath(local, file); if (renamed) { // try to keep last modified timestamp if configured to do so keepLastModified(exchange, file); // clear header as we have renamed the file exchange.getIn().setHeader(Exchange.FILE_LOCAL_WORK_PATH, null); // return as the operation is complete, we just renamed the local work file // to the target. return true; } } else if (source.exists()) { // no there is no local work file so use file to file copy if the source exists writeFileByFile(source, file); // try to keep last modified timestamp if configured to do so keepLastModified(exchange, file); return true; } } // fallback and use stream based InputStream in = ExchangeHelper.getMandatoryInBody(exchange, InputStream.class); writeFileByStream(in, file); // try to keep last modified timestamp if configured to do so keepLastModified(exchange, file); return true; } catch (IOException e) { throw new GenericFileOperationFailedException("Cannot store file: " + file, e); } catch (InvalidPayloadException e) { throw new GenericFileOperationFailedException("Cannot store file: " + file, e); } } private void keepLastModified(Exchange exchange, File file) { if (endpoint.isKeepLastModified()) { Long last; Date date = exchange.getIn().getHeader(Exchange.FILE_LAST_MODIFIED, Date.class); if (date != null) { last = date.getTime(); } else { // fallback and try a long last = exchange.getIn().getHeader(Exchange.FILE_LAST_MODIFIED, Long.class); } if (last != null) { boolean result = file.setLastModified(last); if (LOG.isTraceEnabled()) { LOG.trace("Keeping last modified timestamp: {} on file: {} with result: {}", new Object[]{last, file, result}); } } } } private boolean writeFileByLocalWorkPath(File source, File file) { LOG.trace("Using local work file being renamed from: {} to: {}", source, file); return FileUtil.renameFile(source, file); } private void writeFileByFile(File source, File target) throws IOException { FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = null; try { out = prepareOutputFileChannel(target, out); LOG.trace("Using FileChannel to transfer from: {} to: {}", in, out); long size = in.size(); long position = 0; while (position < size) { position += in.transferTo(position, endpoint.getBufferSize(), out); } } finally { IOHelper.close(in, source.getName(), LOG); IOHelper.close(out, target.getName(), LOG); } } private void writeFileByStream(InputStream in, File target) throws IOException { FileChannel out = null; try { out = prepareOutputFileChannel(target, out); LOG.trace("Using InputStream to transfer from: {} to: {}", in, out); int size = endpoint.getBufferSize(); byte[] buffer = new byte[size]; ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { if (bytesRead < size) { byteBuffer.limit(bytesRead); } out.write(byteBuffer); byteBuffer.clear(); } } finally { IOHelper.close(in, target.getName(), LOG); IOHelper.close(out, target.getName(), LOG); } } /** * Creates and prepares the output file channel. Will position itself in correct position if the file is writable * eg. it should append or override any existing content. */ private FileChannel prepareOutputFileChannel(File target, FileChannel out) throws IOException { if (endpoint.getFileExist() == GenericFileExist.Append) { out = new RandomAccessFile(target, "rw").getChannel(); out = out.position(out.size()); } else { // will override out = new FileOutputStream(target).getChannel(); } return out; } }
package water; import org.testng.annotations.*; import water.util.Log; import java.io.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.sql.Connection; import java.sql.DriverManager; import java.util.*; public class AccuracyTestingSuite { private String logDir; private String resultsDBTableConfig; private int numH2ONodes; private String dataSetsCSVPath; private String testCasesCSVPath; private String testCasesFilterString; public static PrintStream summaryLog; private Connection resultsDBTableConn; private boolean recordResults; public static List<String> dataSetsCSVRows; private ArrayList<TestCase> testCasesList; @BeforeClass @Parameters( {"logDir", "resultsDBTableConfig", "numH2ONodes", "dataSetsCSVPath", "testCasesCSVPath", "testCasesFilterString" } ) private void accuracySuiteSetup(@org.testng.annotations.Optional("h2o-test-accuracy") String logDir, @org.testng.annotations.Optional("") String resultsDBTableConfig, @org.testng.annotations.Optional("1") String numH2ONodes, @org.testng.annotations.Optional("h2o-test-accuracy/src/test/resources/accuracyDataSets.csv") String dataSetsCSVPath, @org.testng.annotations.Optional("h2o-test-accuracy/src/test/resources/accuracyTestCases.csv") String testCasesCSVPath, @org.testng.annotations.Optional("") String testCasesFilterString) { // Logging this.logDir = logDir; File resultsDir = null, h2oLogsDir = null; try { resultsDir = new File(AccuracyTestingUtil.find_test_file_static(logDir).getCanonicalFile().toString() + "/results"); h2oLogsDir = new File(AccuracyTestingUtil.find_test_file_static(logDir).getCanonicalFile().toString() + "/results/h2ologs"); } catch (IOException e) { System.out.println("Couldn't create directory."); e.printStackTrace(); System.exit(-1); } resultsDir.mkdir(); for(File f: resultsDir.listFiles()) f.delete(); h2oLogsDir.mkdir(); for(File f: h2oLogsDir.listFiles()) f.delete(); File suiteSummary; try { suiteSummary = new File(AccuracyTestingUtil.find_test_file_static(logDir).getCanonicalFile().toString() + "/results/accuracySuiteSummary.log"); suiteSummary.createNewFile(); summaryLog = new PrintStream(new FileOutputStream(suiteSummary, false)); } catch (IOException e) { System.out.println("Couldn't create the accuracySuiteSummary.log"); e.printStackTrace(); System.exit(-1); } System.out.println("Commenced logging to h2o-test-accuracy/results directory."); // Results database table this.resultsDBTableConfig = resultsDBTableConfig; if (this.resultsDBTableConfig.isEmpty()) { summaryLog.println("No results database configuration specified, so test case results will not be saved."); recordResults = false; } else { summaryLog.println("Results database configuration specified specified by: " + this.resultsDBTableConfig); resultsDBTableConn = makeResultsDBTableConn(); recordResults = true; } // H2O Cloud this.numH2ONodes = Integer.parseInt(numH2ONodes); summaryLog.println("Setting up the H2O Cloud with " + this.numH2ONodes + " nodes.");; AccuracyTestingUtil.setupH2OCloud(this.numH2ONodes, this.logDir); // Data sets this.dataSetsCSVPath = dataSetsCSVPath; File dataSetsFile = AccuracyTestingUtil.find_test_file_static(this.dataSetsCSVPath); try { dataSetsCSVRows = Files.readAllLines(dataSetsFile.toPath(), Charset.defaultCharset()); } catch (IOException e) { summaryLog.println("Cannot read the lines of the the data sets file: " + dataSetsFile.toPath()); writeStackTrace(e,summaryLog); System.exit(-1); } dataSetsCSVRows.remove(0); // remove the header // Test Cases this.testCasesCSVPath = testCasesCSVPath; this.testCasesFilterString = testCasesFilterString; testCasesList = makeTestCasesList(); } @Test public void accuracyTest() { TestCase tc = null; TestCaseResult tcResult; int id; boolean suiteFailure = false; Iterator i = testCasesList.iterator(); while(i.hasNext()) { tc = (TestCase) i.next(); id = tc.getTestCaseId(); try { //removeAll(); summaryLog.println("\n-----------------------------"); summaryLog.println("Accuracy Suite Test Case: " + id); summaryLog.println("-----------------------------\n"); Log.info("-----------------------------"); Log.info("Accuracy Suite Test Case: " + id); Log.info("-----------------------------"); tcResult = tc.execute(); tcResult.printValidationMetrics(tc.isCrossVal()); if (recordResults) { summaryLog.println("Recording test case " + id + " result."); tcResult.saveToAccuracyTable(resultsDBTableConn); } } catch (Exception e) { StringWriter stringWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stringWriter)); String stackTraceString = stringWriter.toString(); Log.err("Test case " + id + " failed on: "); Log.err(stackTraceString); summaryLog.println("Test case " + id + " failed on: "); summaryLog.println(stackTraceString); suiteFailure = true; } catch (AssertionError ae) { Log.err("Test case " + id + " failed on: "); Log.err(ae.getMessage()); summaryLog.println("Test case " + id + " failed on: "); summaryLog.println(ae.getMessage()); suiteFailure = true; } } if (suiteFailure) { System.out.println("The suite failed due to one or more test case failures."); System.exit(-1); } } private ArrayList<TestCase> makeTestCasesList() { String[] algorithms = filterForAlgos(testCasesFilterString); String[] testCases = filterForTestCases(testCasesFilterString); List<String> testCaseEntries = null; try { summaryLog.println("Reading test cases from: " + testCasesCSVPath); File testCasesFile = AccuracyTestingUtil.find_test_file_static(this.testCasesCSVPath); testCaseEntries = Files.readAllLines(testCasesFile.toPath(), Charset.defaultCharset()); } catch (Exception e) { summaryLog.println("Cannot read the test cases from: " + testCasesCSVPath); writeStackTrace(e,summaryLog); System.exit(-1); } testCaseEntries.remove(0); // remove header line ArrayList<TestCase> testCaseArray = new ArrayList<>(); String[] testCaseEntry; for (String t : testCaseEntries) { testCaseEntry = t.trim().split(",", -1); // If algorithms are specified in the testCaseFilterString, load all test cases for these algorithms. Otherwise, // if specific test cases are specified, then only load those. Else, load all the test cases. if (null != algorithms) { if (!Arrays.asList(algorithms).contains(testCaseEntry[1])) { continue; } } else if (null != testCases) { if (!Arrays.asList(testCases).contains(testCaseEntry[0])) { continue; } } summaryLog.println("Creating test case: " + t); try { testCaseArray.add( new TestCase(Integer.parseInt(testCaseEntry[0]), testCaseEntry[1], testCaseEntry[2], testCaseEntry[3].equals("1"), testCaseEntry[4], testCaseEntry[5], testCaseEntry[6], testCaseEntry[7].equals("1"), Integer.parseInt(testCaseEntry[8]), Integer.parseInt(testCaseEntry[9]), testCaseEntry[10]) ); } catch (Exception e) { summaryLog.println("Couldn't create test case: " + t); writeStackTrace(e, summaryLog); System.exit(-1); } } return testCaseArray; } private String[] filterForAlgos(String selectionString) { if (selectionString.isEmpty()) return null; String algoSelectionString = selectionString.trim().split(";", -1)[0]; if (algoSelectionString.isEmpty()) return null; return algoSelectionString.trim().split(",", -1); } private String[] filterForTestCases(String selectionString) { if (selectionString.isEmpty()) return null; String testCaseSelectionString = selectionString.trim().split(";", -1)[1]; if (null == testCaseSelectionString || testCaseSelectionString.isEmpty()) return null; return testCaseSelectionString.trim().split(",", -1); } private Connection makeResultsDBTableConn() { Connection connection = null; try { summaryLog.println("Reading the database configuration settings from: " + resultsDBTableConfig); File configFile = new File(resultsDBTableConfig); Properties properties = new Properties(); properties.load(new BufferedReader(new FileReader(configFile))); summaryLog.println("Establishing connection to the database."); Class.forName("com.mysql.jdbc.Driver"); String url = String.format("jdbc:mysql://%s:%s/%s", properties.getProperty("db.host"), properties.getProperty("db.port"), properties.getProperty("db.databaseName")); connection = DriverManager.getConnection(url, properties.getProperty("db.user"), properties.getProperty("db.password")); } catch (Exception e) { summaryLog.println("Couldn't connect to the database."); writeStackTrace(e, summaryLog); System.exit(-1); } return connection; } private static void writeStackTrace(Exception e, PrintStream ps) { StringWriter stringWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stringWriter)); ps.println(stringWriter.toString()); } private void removeAll() { //FIXME: This was just copied over from RemoveAllHandler. summaryLog.println("Removing all."); Futures fs = new Futures(); for( Job j : Job.jobs() ) { j.stop(); j.remove(fs); } fs.blockForPending(); new MRTask(){ @Override public void setupLocal() { H2O.raw_clear(); water.fvec.Vec.ESPC.clear(); } }.doAllNodes(); H2O.getPM().getIce().cleanUp(); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.snapshots.mockstore; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.metadata.RepositoryMetaData; import org.elasticsearch.common.blobstore.BlobContainer; import org.elasticsearch.common.blobstore.BlobMetaData; import org.elasticsearch.common.blobstore.BlobPath; import org.elasticsearch.common.blobstore.BlobStore; import org.elasticsearch.common.io.PathUtils; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.plugins.RepositoryPlugin; import org.elasticsearch.repositories.Repository; import org.elasticsearch.repositories.IndexId; import org.elasticsearch.repositories.fs.FsRepository; import org.elasticsearch.snapshots.SnapshotId; public class MockRepository extends FsRepository { public static class Plugin extends org.elasticsearch.plugins.Plugin implements RepositoryPlugin { public static final Setting<String> USERNAME_SETTING = Setting.simpleString("secret.mock.username", Property.NodeScope); public static final Setting<String> PASSWORD_SETTING = Setting.simpleString("secret.mock.password", Property.NodeScope, Property.Filtered); @Override public Map<String, Repository.Factory> getRepositories(Environment env) { return Collections.singletonMap("mock", (metadata) -> new MockRepository(metadata, env)); } @Override public List<Setting<?>> getSettings() { return Arrays.asList(USERNAME_SETTING, PASSWORD_SETTING); } } private final AtomicLong failureCounter = new AtomicLong(); public long getFailureCount() { return failureCounter.get(); } private final double randomControlIOExceptionRate; private final double randomDataFileIOExceptionRate; private final long maximumNumberOfFailures; private final long waitAfterUnblock; private final MockBlobStore mockBlobStore; private final String randomPrefix; private volatile boolean blockOnInitialization; private volatile boolean blockOnControlFiles; private volatile boolean blockOnDataFiles; private volatile boolean blocked = false; public MockRepository(RepositoryMetaData metadata, Environment environment) throws IOException { super(overrideSettings(metadata, environment), environment); randomControlIOExceptionRate = metadata.settings().getAsDouble("random_control_io_exception_rate", 0.0); randomDataFileIOExceptionRate = metadata.settings().getAsDouble("random_data_file_io_exception_rate", 0.0); maximumNumberOfFailures = metadata.settings().getAsLong("max_failure_number", 100L); blockOnControlFiles = metadata.settings().getAsBoolean("block_on_control", false); blockOnDataFiles = metadata.settings().getAsBoolean("block_on_data", false); blockOnInitialization = metadata.settings().getAsBoolean("block_on_init", false); randomPrefix = metadata.settings().get("random", "default"); waitAfterUnblock = metadata.settings().getAsLong("wait_after_unblock", 0L); logger.info("starting mock repository with random prefix {}", randomPrefix); mockBlobStore = new MockBlobStore(super.blobStore()); } @Override public void initializeSnapshot(SnapshotId snapshotId, List<IndexId> indices, MetaData clusterMetadata) { if (blockOnInitialization) { blockExecution(); } super.initializeSnapshot(snapshotId, indices, clusterMetadata); } private static RepositoryMetaData overrideSettings(RepositoryMetaData metadata, Environment environment) { // TODO: use another method of testing not being able to read the test file written by the master... // this is super duper hacky if (metadata.settings().getAsBoolean("localize_location", false)) { Path location = PathUtils.get(metadata.settings().get("location")); location = location.resolve(Integer.toString(environment.hashCode())); return new RepositoryMetaData(metadata.name(), metadata.type(), Settings.builder().put(metadata.settings()).put("location", location.toAbsolutePath()).build()); } else { return metadata; } } private long incrementAndGetFailureCount() { return failureCounter.incrementAndGet(); } @Override protected void doStop() { unblock(); super.doStop(); } @Override protected BlobStore blobStore() { return mockBlobStore; } public void unblock() { unblockExecution(); } public void blockOnDataFiles(boolean blocked) { blockOnDataFiles = blocked; } public void blockOnControlFiles(boolean blocked) { blockOnControlFiles = blocked; } public boolean blockOnDataFiles() { return blockOnDataFiles; } public synchronized void unblockExecution() { blocked = false; // Clean blocking flags, so we wouldn't try to block again blockOnDataFiles = false; blockOnControlFiles = false; blockOnInitialization = false; this.notifyAll(); } public boolean blocked() { return blocked; } private synchronized boolean blockExecution() { logger.debug("Blocking execution"); boolean wasBlocked = false; try { while (blockOnDataFiles || blockOnControlFiles || blockOnInitialization) { blocked = true; this.wait(); wasBlocked = true; } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } logger.debug("Unblocking execution"); return wasBlocked; } public class MockBlobStore extends BlobStoreWrapper { ConcurrentMap<String, AtomicLong> accessCounts = new ConcurrentHashMap<>(); private long incrementAndGet(String path) { AtomicLong value = accessCounts.get(path); if (value == null) { value = accessCounts.putIfAbsent(path, new AtomicLong(1)); } if (value != null) { return value.incrementAndGet(); } return 1; } public MockBlobStore(BlobStore delegate) { super(delegate); } @Override public BlobContainer blobContainer(BlobPath path) { return new MockBlobContainer(super.blobContainer(path)); } private class MockBlobContainer extends BlobContainerWrapper { private MessageDigest digest; private boolean shouldFail(String blobName, double probability) { if (probability > 0.0) { String path = path().add(blobName).buildAsString() + randomPrefix; path += "/" + incrementAndGet(path); logger.info("checking [{}] [{}]", path, Math.abs(hashCode(path)) < Integer.MAX_VALUE * probability); return Math.abs(hashCode(path)) < Integer.MAX_VALUE * probability; } else { return false; } } private int hashCode(String path) { try { digest = MessageDigest.getInstance("MD5"); byte[] bytes = digest.digest(path.getBytes("UTF-8")); int i = 0; return ((bytes[i++] & 0xFF) << 24) | ((bytes[i++] & 0xFF) << 16) | ((bytes[i++] & 0xFF) << 8) | (bytes[i++] & 0xFF); } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { throw new ElasticsearchException("cannot calculate hashcode", ex); } } private void maybeIOExceptionOrBlock(String blobName) throws IOException { if (blobName.startsWith("__")) { if (shouldFail(blobName, randomDataFileIOExceptionRate) && (incrementAndGetFailureCount() < maximumNumberOfFailures)) { logger.info("throwing random IOException for file [{}] at path [{}]", blobName, path()); throw new IOException("Random IOException"); } else if (blockOnDataFiles) { logger.info("blocking I/O operation for file [{}] at path [{}]", blobName, path()); if (blockExecution() && waitAfterUnblock > 0) { try { // Delay operation after unblocking // So, we can start node shutdown while this operation is still running. Thread.sleep(waitAfterUnblock); } catch (InterruptedException ex) { // } } } } else { if (shouldFail(blobName, randomControlIOExceptionRate) && (incrementAndGetFailureCount() < maximumNumberOfFailures)) { logger.info("throwing random IOException for file [{}] at path [{}]", blobName, path()); throw new IOException("Random IOException"); } else if (blockOnControlFiles) { logger.info("blocking I/O operation for file [{}] at path [{}]", blobName, path()); if (blockExecution() && waitAfterUnblock > 0) { try { // Delay operation after unblocking // So, we can start node shutdown while this operation is still running. Thread.sleep(waitAfterUnblock); } catch (InterruptedException ex) { // } } } } } public MockBlobContainer(BlobContainer delegate) { super(delegate); } @Override public boolean blobExists(String blobName) { return super.blobExists(blobName); } @Override public InputStream readBlob(String name) throws IOException { maybeIOExceptionOrBlock(name); return super.readBlob(name); } @Override public void deleteBlob(String blobName) throws IOException { maybeIOExceptionOrBlock(blobName); super.deleteBlob(blobName); } @Override public Map<String, BlobMetaData> listBlobs() throws IOException { maybeIOExceptionOrBlock(""); return super.listBlobs(); } @Override public Map<String, BlobMetaData> listBlobsByPrefix(String blobNamePrefix) throws IOException { maybeIOExceptionOrBlock(blobNamePrefix); return super.listBlobsByPrefix(blobNamePrefix); } @Override public void move(String sourceBlob, String targetBlob) throws IOException { maybeIOExceptionOrBlock(targetBlob); super.move(sourceBlob, targetBlob); } @Override public void writeBlob(String blobName, InputStream inputStream, long blobSize) throws IOException { maybeIOExceptionOrBlock(blobName); super.writeBlob(blobName, inputStream, blobSize); } } } }
/* * 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.protocol.http.parser; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import org.apache.commons.lang3.StringUtils; import org.apache.jmeter.protocol.http.util.ConversionUtils; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import org.htmlparser.Node; import org.htmlparser.Parser; import org.htmlparser.Tag; import org.htmlparser.tags.AppletTag; import org.htmlparser.tags.BaseHrefTag; import org.htmlparser.tags.BodyTag; import org.htmlparser.tags.CompositeTag; import org.htmlparser.tags.FrameTag; import org.htmlparser.tags.ImageTag; import org.htmlparser.tags.InputTag; import org.htmlparser.tags.ObjectTag; import org.htmlparser.tags.ScriptTag; import org.htmlparser.util.NodeIterator; import org.htmlparser.util.ParserException; /** * HtmlParser implementation using SourceForge's HtmlParser. * */ class HtmlParserHTMLParser extends HTMLParser { private static final Logger log = LoggingManager.getLoggerForClass(); static{ org.htmlparser.scanners.ScriptScanner.STRICT = false; // Try to ensure that more javascript code is processed OK ... } protected HtmlParserHTMLParser() { super(); log.info("Using htmlparser version: "+Parser.getVersion()); } @Override protected boolean isReusable() { return true; } /** * {@inheritDoc} */ @Override public Iterator<URL> getEmbeddedResourceURLs(String userAgent, byte[] html, URL baseUrl, URLCollection urls, String encoding) throws HTMLParseException { if (log.isDebugEnabled()) { log.debug("Parsing html of: " + baseUrl); } Parser htmlParser = null; try { String contents = new String(html,encoding); htmlParser = new Parser(); htmlParser.setInputHTML(contents); } catch (Exception e) { throw new HTMLParseException(e); } // Now parse the DOM tree try { // we start to iterate through the elements parseNodes(htmlParser.elements(), new URLPointer(baseUrl), urls); log.debug("End : parseNodes"); } catch (ParserException e) { throw new HTMLParseException(e); } return urls.iterator(); } /* * A dummy class to pass the pointer of URL. */ private static class URLPointer { private URLPointer(URL newUrl) { url = newUrl; } private URL url; } /** * Recursively parse all nodes to pick up all URL s. * @see e the nodes to be parsed * @see baseUrl Base URL from which the HTML code was obtained * @see urls URLCollection */ private void parseNodes(final NodeIterator e, final URLPointer baseUrl, final URLCollection urls) throws HTMLParseException, ParserException { while(e.hasMoreNodes()) { Node node = e.nextNode(); // a url is always in a Tag. if (!(node instanceof Tag)) { continue; } Tag tag = (Tag) node; String tagname=tag.getTagName(); String binUrlStr = null; // first we check to see if body tag has a // background set if (tag instanceof BodyTag) { binUrlStr = tag.getAttribute(ATT_BACKGROUND); } else if (tag instanceof BaseHrefTag) { BaseHrefTag baseHref = (BaseHrefTag) tag; String baseref = baseHref.getBaseUrl(); try { if (!baseref.equals(""))// Bugzilla 30713 { baseUrl.url = ConversionUtils.makeRelativeURL(baseUrl.url, baseref); } } catch (MalformedURLException e1) { throw new HTMLParseException(e1); } } else if (tag instanceof ImageTag) { ImageTag image = (ImageTag) tag; binUrlStr = image.getImageURL(); } else if (tag instanceof AppletTag) { // look for applets // This will only work with an Applet .class file. // Ideally, this should be upgraded to work with Objects (IE) // and archives (.jar and .zip) files as well. AppletTag applet = (AppletTag) tag; binUrlStr = applet.getAppletClass(); } else if (tag instanceof ObjectTag) { // look for Objects ObjectTag applet = (ObjectTag) tag; String data = applet.getAttribute(ATT_CODEBASE); if(!StringUtils.isEmpty(data)) { binUrlStr = data; } data = applet.getAttribute(ATT_DATA); if(!StringUtils.isEmpty(data)) { binUrlStr = data; } } else if (tag instanceof InputTag) { // we check the input tag type for image if (ATT_IS_IMAGE.equalsIgnoreCase(tag.getAttribute(ATT_TYPE))) { // then we need to download the binary binUrlStr = tag.getAttribute(ATT_SRC); } } else if (tag instanceof ScriptTag) { binUrlStr = tag.getAttribute(ATT_SRC); // Bug 51750 } else if (tag instanceof FrameTag || tagname.equalsIgnoreCase(TAG_IFRAME)) { binUrlStr = tag.getAttribute(ATT_SRC); } else if (tagname.equalsIgnoreCase(TAG_EMBED) || tagname.equalsIgnoreCase(TAG_BGSOUND)){ binUrlStr = tag.getAttribute(ATT_SRC); } else if (tagname.equalsIgnoreCase(TAG_LINK)) { // Putting the string first means it works even if the attribute is null if (STYLESHEET.equalsIgnoreCase(tag.getAttribute(ATT_REL))) { binUrlStr = tag.getAttribute(ATT_HREF); } } else { binUrlStr = tag.getAttribute(ATT_BACKGROUND); } if (binUrlStr != null) { urls.addURL(binUrlStr, baseUrl.url); } // Now look for URLs in the STYLE attribute String styleTagStr = tag.getAttribute(ATT_STYLE); if(styleTagStr != null) { HtmlParsingUtils.extractStyleURLs(baseUrl.url, urls, styleTagStr); } // second, if the tag was a composite tag, // recursively parse its children. if (tag instanceof CompositeTag) { CompositeTag composite = (CompositeTag) tag; parseNodes(composite.elements(), baseUrl, urls); } } } }
/* * 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.catalina.core; import javax.servlet.SessionCookieConfig; import javax.servlet.http.Cookie; import org.apache.catalina.Context; import org.apache.catalina.LifecycleState; import org.apache.catalina.util.SessionConfig; import org.apache.tomcat.util.res.StringManager; public class ApplicationSessionCookieConfig implements SessionCookieConfig { /** * The string manager for this package. */ private static final StringManager sm = StringManager .getManager(Constants.Package); private boolean httpOnly; private boolean secure; private int maxAge = -1; private String comment; private String domain; private String name; private String path; private StandardContext context; public ApplicationSessionCookieConfig(StandardContext context) { this.context = context; } @Override public String getComment() { return comment; } @Override public String getDomain() { return domain; } @Override public int getMaxAge() { return maxAge; } @Override public String getName() { return name; } @Override public String getPath() { return path; } @Override public boolean isHttpOnly() { return httpOnly; } @Override public boolean isSecure() { return secure; } @Override public void setComment(String comment) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationSessionCookieConfig.ise", "comment", context.getPath())); } this.comment = comment; } @Override public void setDomain(String domain) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationSessionCookieConfig.ise", "domain name", context.getPath())); } this.domain = domain; } @Override public void setHttpOnly(boolean httpOnly) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationSessionCookieConfig.ise", "HttpOnly", context.getPath())); } this.httpOnly = httpOnly; } @Override public void setMaxAge(int maxAge) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationSessionCookieConfig.ise", "max age", context.getPath())); } this.maxAge = maxAge; } @Override public void setName(String name) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationSessionCookieConfig.ise", "name", context.getPath())); } this.name = name; } @Override public void setPath(String path) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationSessionCookieConfig.ise", "path", context.getPath())); } this.path = path; } @Override public void setSecure(boolean secure) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationSessionCookieConfig.ise", "secure", context.getPath())); } this.secure = secure; } /** * Creates a new session cookie for the given session ID * * @param context The Context for the web application * @param sessionId The ID of the session for which the cookie will be * created * @param secure Should session cookie be configured as secure */ public static Cookie createSessionCookie(Context context, String sessionId, boolean secure) { SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig(); // NOTE: The priority order for session cookie configuration is: // 1. Context level configuration // 2. Values from SessionCookieConfig // 3. Defaults Cookie cookie = new Cookie( SessionConfig.getSessionCookieName(context), sessionId); // Just apply the defaults. cookie.setMaxAge(scc.getMaxAge()); cookie.setComment(scc.getComment()); if (context.getSessionCookieDomain() == null) { // Avoid possible NPE if (scc.getDomain() != null) { cookie.setDomain(scc.getDomain()); } } else { cookie.setDomain(context.getSessionCookieDomain()); } // Always set secure if the request is secure if (scc.isSecure() || secure) { cookie.setSecure(true); } // Always set httpOnly if the context is configured for that if (scc.isHttpOnly() || context.getUseHttpOnly()) { cookie.setHttpOnly(true); } String contextPath = context.getSessionCookiePath(); if (contextPath == null || contextPath.length() == 0) { contextPath = scc.getPath(); } if (contextPath == null || contextPath.length() == 0) { contextPath = context.getEncodedPath(); } if (context.getSessionCookiePathUsesTrailingSlash()) { // Handle special case of ROOT context where cookies require a path of // '/' but the servlet spec uses an empty string // Also ensure the cookies for a context with a path of /foo don't get // sent for requests with a path of /foobar if (!contextPath.endsWith("/")) { contextPath = contextPath + "/"; } } else { // Only handle special case of ROOT context where cookies require a // path of '/' but the servlet spec uses an empty string if (contextPath.length() == 0) { contextPath = "/"; } } cookie.setPath(contextPath); return cookie; } /** * Determine the name to use for the session cookie for the provided * context. * @param context * * @deprecated Replaced by * {@link SessionConfig#getSessionCookieName(Context)}. This * will be removed in Tomcat 8.0.x. */ @Deprecated public static String getSessionCookieName(Context context) { return SessionConfig.getSessionCookieName(context); } /** * Determine the name to use for the session cookie for the provided * context. * @param context * * @deprecated Replaced by * {@link SessionConfig#getSessionUriParamName(Context)}. This * will be removed in Tomcat 8.0.x. */ @Deprecated public static String getSessionUriParamName(Context context) { return SessionConfig.getSessionUriParamName(context); } }
/* * Copyright (C) 2011 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.dx.io.instructions; import com.android.dex.DexException; import com.android.dx.io.IndexType; import com.android.dx.io.OpcodeInfo; import com.android.dx.io.Opcodes; import com.android.dx.util.Hex; import java.io.EOFException; /** * A decoded Dalvik instruction. This consists of a format codec, a * numeric opcode, an optional index type, and any additional * arguments of the instruction. The additional arguments (if any) are * represented as uninterpreted data. * * <p><b>Note:</b> The names of the arguments are <i>not</i> meant to * match the names given in the Dalvik instruction format * specification, specification which just names fields (somewhat) * arbitrarily alphabetically from A. In this class, non-register * fields are given descriptive names and register fields are * consistently named alphabetically.</p> */ public abstract class DecodedInstruction { /** non-null; instruction format / codec */ private final InstructionCodec format; /** opcode number */ private final int opcode; /** constant index argument */ private final int index; /** null-ok; index type */ private final IndexType indexType; /** * target address argument. This is an absolute address, not just * a signed offset. <b>Note:</b> The address is unsigned, even * though it is stored in an {@code int}. */ private final int target; /** * literal value argument; also used for special verification error * constants (format 20bc) as well as should-be-zero values * (formats 10x, 20t, 30t, and 32x) */ private final long literal; /** * Decodes an instruction from the given input source. */ public static DecodedInstruction decode(CodeInput in) throws EOFException { int opcodeUnit = in.read(); int opcode = Opcodes.extractOpcodeFromUnit(opcodeUnit); InstructionCodec format = OpcodeInfo.getFormat(opcode); return format.decode(opcodeUnit, in); } /** * Decodes an array of instructions. The result has non-null * elements at each offset that represents the start of an * instruction. */ public static DecodedInstruction[] decodeAll(short[] encodedInstructions) { int size = encodedInstructions.length; DecodedInstruction[] decoded = new DecodedInstruction[size]; ShortArrayCodeInput in = new ShortArrayCodeInput(encodedInstructions); try { while (in.hasMore()) { decoded[in.cursor()] = DecodedInstruction.decode(in); } } catch (EOFException ex) { throw new DexException(ex); } return decoded; } /** * Constructs an instance. */ public DecodedInstruction(InstructionCodec format, int opcode, int index, IndexType indexType, int target, long literal) { if (format == null) { throw new NullPointerException("format == null"); } if (!Opcodes.isValidShape(opcode)) { throw new IllegalArgumentException("invalid opcode"); } this.format = format; this.opcode = opcode; this.index = index; this.indexType = indexType; this.target = target; this.literal = literal; } public final InstructionCodec getFormat() { return format; } public final int getOpcode() { return opcode; } /** * Gets the opcode, as a code unit. */ public final short getOpcodeUnit() { return (short) opcode; } public final int getIndex() { return index; } /** * Gets the index, as a code unit. */ public final short getIndexUnit() { return (short) index; } public final IndexType getIndexType() { return indexType; } /** * Gets the raw target. */ public final int getTarget() { return target; } /** * Gets the target as a relative offset from the given address. */ public final int getTarget(int baseAddress) { return target - baseAddress; } /** * Gets the target as a relative offset from the given base * address, as a code unit. This will throw if the value is out of * the range of a signed code unit. */ public final short getTargetUnit(int baseAddress) { int relativeTarget = getTarget(baseAddress); if (relativeTarget != (short) relativeTarget) { throw new DexException("Target out of range: " + Hex.s4(relativeTarget)); } return (short) relativeTarget; } /** * Gets the target as a relative offset from the given base * address, masked to be a byte in size. This will throw if the * value is out of the range of a signed byte. */ public final int getTargetByte(int baseAddress) { int relativeTarget = getTarget(baseAddress); if (relativeTarget != (byte) relativeTarget) { throw new DexException("Target out of range: " + Hex.s4(relativeTarget)); } return relativeTarget & 0xff; } public final long getLiteral() { return literal; } /** * Gets the literal value, masked to be an int in size. This will * throw if the value is out of the range of a signed int. */ public final int getLiteralInt() { if (literal != (int) literal) { throw new DexException("Literal out of range: " + Hex.u8(literal)); } return (int) literal; } /** * Gets the literal value, as a code unit. This will throw if the * value is out of the range of a signed code unit. */ public final short getLiteralUnit() { if (literal != (short) literal) { throw new DexException("Literal out of range: " + Hex.u8(literal)); } return (short) literal; } /** * Gets the literal value, masked to be a byte in size. This will * throw if the value is out of the range of a signed byte. */ public final int getLiteralByte() { if (literal != (byte) literal) { throw new DexException("Literal out of range: " + Hex.u8(literal)); } return (int) literal & 0xff; } /** * Gets the literal value, masked to be a nibble in size. This * will throw if the value is out of the range of a signed nibble. */ public final int getLiteralNibble() { if ((literal < -8) || (literal > 7)) { throw new DexException("Literal out of range: " + Hex.u8(literal)); } return (int) literal & 0xf; } public abstract int getRegisterCount(); public int getA() { return 0; } public int getB() { return 0; } public int getC() { return 0; } public int getD() { return 0; } public int getE() { return 0; } /** * Gets the register count, as a code unit. This will throw if the * value is out of the range of an unsigned code unit. */ public final short getRegisterCountUnit() { int registerCount = getRegisterCount(); if ((registerCount & ~0xffff) != 0) { throw new DexException("Register count out of range: " + Hex.u8(registerCount)); } return (short) registerCount; } /** * Gets the A register number, as a code unit. This will throw if the * value is out of the range of an unsigned code unit. */ public final short getAUnit() { int a = getA(); if ((a & ~0xffff) != 0) { throw new DexException("Register A out of range: " + Hex.u8(a)); } return (short) a; } /** * Gets the A register number, as a byte. This will throw if the * value is out of the range of an unsigned byte. */ public final short getAByte() { int a = getA(); if ((a & ~0xff) != 0) { throw new DexException("Register A out of range: " + Hex.u8(a)); } return (short) a; } /** * Gets the A register number, as a nibble. This will throw if the * value is out of the range of an unsigned nibble. */ public final short getANibble() { int a = getA(); if ((a & ~0xf) != 0) { throw new DexException("Register A out of range: " + Hex.u8(a)); } return (short) a; } /** * Gets the B register number, as a code unit. This will throw if the * value is out of the range of an unsigned code unit. */ public final short getBUnit() { int b = getB(); if ((b & ~0xffff) != 0) { throw new DexException("Register B out of range: " + Hex.u8(b)); } return (short) b; } /** * Gets the B register number, as a byte. This will throw if the * value is out of the range of an unsigned byte. */ public final short getBByte() { int b = getB(); if ((b & ~0xff) != 0) { throw new DexException("Register B out of range: " + Hex.u8(b)); } return (short) b; } /** * Gets the B register number, as a nibble. This will throw if the * value is out of the range of an unsigned nibble. */ public final short getBNibble() { int b = getB(); if ((b & ~0xf) != 0) { throw new DexException("Register B out of range: " + Hex.u8(b)); } return (short) b; } /** * Gets the C register number, as a code unit. This will throw if the * value is out of the range of an unsigned code unit. */ public final short getCUnit() { int c = getC(); if ((c & ~0xffff) != 0) { throw new DexException("Register C out of range: " + Hex.u8(c)); } return (short) c; } /** * Gets the C register number, as a byte. This will throw if the * value is out of the range of an unsigned byte. */ public final short getCByte() { int c = getC(); if ((c & ~0xff) != 0) { throw new DexException("Register C out of range: " + Hex.u8(c)); } return (short) c; } /** * Gets the C register number, as a nibble. This will throw if the * value is out of the range of an unsigned nibble. */ public final short getCNibble() { int c = getC(); if ((c & ~0xf) != 0) { throw new DexException("Register C out of range: " + Hex.u8(c)); } return (short) c; } /** * Gets the D register number, as a code unit. This will throw if the * value is out of the range of an unsigned code unit. */ public final short getDUnit() { int d = getD(); if ((d & ~0xffff) != 0) { throw new DexException("Register D out of range: " + Hex.u8(d)); } return (short) d; } /** * Gets the D register number, as a byte. This will throw if the * value is out of the range of an unsigned byte. */ public final short getDByte() { int d = getD(); if ((d & ~0xff) != 0) { throw new DexException("Register D out of range: " + Hex.u8(d)); } return (short) d; } /** * Gets the D register number, as a nibble. This will throw if the * value is out of the range of an unsigned nibble. */ public final short getDNibble() { int d = getD(); if ((d & ~0xf) != 0) { throw new DexException("Register D out of range: " + Hex.u8(d)); } return (short) d; } /** * Gets the E register number, as a nibble. This will throw if the * value is out of the range of an unsigned nibble. */ public final short getENibble() { int e = getE(); if ((e & ~0xf) != 0) { throw new DexException("Register E out of range: " + Hex.u8(e)); } return (short) e; } /** * Encodes this instance to the given output. */ public final void encode(CodeOutput out) { format.encode(this, out); } /** * Returns an instance just like this one, except with the index replaced * with the given one. */ public abstract DecodedInstruction withIndex(int newIndex); }
/* * Copyright 2017 David Haegele * * 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 hageldave.imagingkit.core; import static hageldave.imagingkit.core.util.ImagingKitUtils.*; /** * Pixel class for retrieving a value from an {@link Img}. * A Pixel object stores a position and can be used to get and set values of * an Img. It is NOT the value and changing its position will not change the * image, instead it will reference a different value of the image as the * pixel object is a pointer to a value in the Img's data array. * <p> * The Pixel class also provides a set of static methods for color decomposition * and recombination from color channels like {@link #argb(int, int, int, int)} * or {@link #a(int)}, {@link #r(int)}, {@link #g(int)}, {@link #b(int)}. * * @author hageldave * @since 1.0 */ public class Pixel implements PixelBase { /** Img this pixel belongs to * @since 1.0 */ private final Img img; /** index of the value this pixel references * @since 1.0 */ private int index; /** * Creates a new Pixel object referencing the value * of specified Img at specified index. * <p> * No bounds checks are performed for index. * @param img the Img this pixel corresponds to * @param index of the value in the images data array * @see #Pixel(Img, int, int) * @see Img#getPixel() * @see Img#getPixel(int, int) * @since 1.0 */ public Pixel(Img img, int index) { this.img = img; this.index = index; } /** * Creates a new Pixel object referencing the value * of specified Img at specified position. * <p> * No bounds checks are performed for x and y * @param img the Img this pixel corresponds to * @param x coordinate * @param y coordinate * @see #Pixel(Img, int) * @see Img#getPixel() * @see Img#getPixel(int, int) * @since 1.0 */ public Pixel(Img img, int x, int y) { this(img, y*img.getWidth()+x); } /** * @return the Img this Pixel belongs to. * @since 1.0 */ public Img getSource() { return img; } /** * Sets the index of the Img value this Pixel references. * No bounds checks are performed. * @param index corresponding to the position of the image's data array. * @see #setPosition(int, int) * @see #getIndex() * @since 1.0 */ public Pixel setIndex(int index) { this.index = index; return this; } /** * Sets the position of the Img value this Pixel references. * No bounds checks are performed. * @param x coordinate * @param y coordinate * @see #setIndex(int) * @see #getX() * @see #getY() * @since 1.0 */ public Pixel setPosition(int x, int y) { this.index = y*img.getWidth()+x; return this; } /** * @return the index of the Img value this Pixel references. * @since 1.0 */ public int getIndex() { return index; } /** * @return the x coordinate of the position in the Img this Pixel references. * @see #getY() * @see #getIndex() * @see #setPosition(int, int) * @since 1.0 */ public int getX() { return index % img.getWidth(); } /** * @return the y coordinate of the position in the Img this Pixel references. * @see #getX() * @see #getIndex() * @see #setPosition(int, int) * @since 1.0 */ public int getY() { return index / img.getWidth(); } /** * Sets the value of the Img at the position currently referenced by * this Pixel. * <p> * If the position of this pixel is not in bounds of the Img the value for * a different position may be set or an ArrayIndexOutOfBoundsException * may be thrown. * @param pixelValue to be set e.g. 0xff0000ff for blue. * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #setARGB(int, int, int, int) * @see #setRGB(int, int, int) * @see #getValue() * @see Img#setValue(int, int, int) * @since 1.0 */ public Pixel setValue(int pixelValue){ this.img.getData()[index] = pixelValue; return this; } /** * Gets the value of the Img at the position currently referenced by * this Pixel. * <p> * If the position of this pixel is not in bounds of the Img the value for * a different position may be returned or an ArrayIndexOutOfBoundsException * may be thrown. * @return the value of the Img currently referenced by this Pixel. * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #a() * @see #r() * @see #g() * @see #b() * @see #setValue(int) * @see Img#getValue(int, int) * @since 1.0 */ public int getValue(){ return this.img.getData()[index]; } /** * @return the alpha component of the value currently referenced by this * Pixel. It is assumed that the value is an ARGB value with 8bits per * color channel, so this will return a value in [0..255]. * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #r() * @see #g() * @see #b() * @see #setRGB(int, int, int) * @see #setARGB(int, int, int, int) * @see #getValue() * @since 1.0 */ public int a(){ return Pixel.a(getValue()); } /** * @return the red component of the value currently referenced by this * Pixel. It is assumed that the value is an ARGB value with 8bits per * color channel, so this will return a value in [0..255]. * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #a() * @see #g() * @see #b() * @see #setRGB(int, int, int) * @see #setARGB(int, int, int, int) * @see #getValue() * @since 1.0 */ public int r(){ return Pixel.r(getValue()); } /** * @return the green component of the value currently referenced by this * Pixel. It is assumed that the value is an ARGB value with 8bits per * color channel, so this will return a value in [0..255]. * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #a() * @see #r() * @see #b() * @see #setRGB(int, int, int) * @see #setARGB(int, int, int, int) * @see #getValue() * @since 1.0 */ public int g(){ return Pixel.g(getValue()); } /** * @return the blue component of the value currently referenced by this * Pixel. It is assumed that the value is an ARGB value with 8bits per * color channel, so this will return a value in [0..255]. * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #a() * @see #r() * @see #g() * @see #setRGB(int, int, int) * @see #setARGB(int, int, int, int) * @see #getValue() * @since 1.0 */ public int b(){ return Pixel.b(getValue()); } /** * @return the normalized alpha component of the value currently referenced by this * Pixel. This will return a value in [0.0 .. 1.0]. * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * * @see #a() * @see #r_asDouble() * @see #g_asDouble() * @see #b_asDouble() * @since 1.2 */ public double a_asDouble(){ return Pixel.a_normalized(getValue()); } /** * @return the normalized red component of the value currently referenced by this * Pixel. This will return a value in [0.0 .. 1.0]. * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * * @see #r() * @see #a_asDouble() * @see #g_asDouble() * @see #b_asDouble() * @since 1.2 */ public double r_asDouble(){ return Pixel.r_normalized(getValue()); } /** * @return the normalized green component of the value currently referenced by this * Pixel. This will return a value in [0.0 .. 1.0]. * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * * @see #g() * @see #a_asDouble() * @see #r_asDouble() * @see #b_asDouble() * @since 1.2 */ public double g_asDouble(){ return Pixel.g_normalized(getValue()); } /** * @return the normalized blue component of the value currently referenced by this * Pixel. This will return a value in [0.0 .. 1.0]. * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * * @see #b() * @see #a_asDouble() * @see #r_asDouble() * @see #g_asDouble() * @since 1.2 */ public double b_asDouble(){ return Pixel.b_normalized(getValue()); } /** * Sets an ARGB value at the position currently referenced by this Pixel. * Each channel value is assumed to be 8bit and otherwise truncated. * @param a alpha * @param r red * @param g green * @param b blue * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #setRGB(int, int, int) * @see #setRGB_preserveAlpha(int, int, int) * @see #argb(int, int, int, int) * @see #argb_bounded(int, int, int, int) * @see #argb_fast(int, int, int, int) * @see #setValue(int) * @since 1.0 */ public void setARGB(int a, int r, int g, int b){ setValue(Pixel.argb(a, r, g, b)); } /** * Sets an opaque RGB value at the position currently referenced by this Pixel. * Each channel value is assumed to be 8bit and otherwise truncated. * @param r red * @param g green * @param b blue * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #setARGB(int, int, int, int) * @see #setRGB_preserveAlpha(int, int, int) * @see #argb(int, int, int, int) * @see #argb_bounded(int, int, int, int) * @see #argb_fast(int, int, int, int) * @see #setValue(int) * @since 1.0 */ public void setRGB(int r, int g, int b){ setValue(Pixel.rgb(r, g, b)); } /** * Sets an RGB value at the position currently referenced by this Pixel. * The present alpha value will not be altered by this operation. * Each channel value is assumed to be 8bit and otherwise truncated. * @param r red * @param g green * @param b blue * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #setRGB_fromDouble_preserveAlpha(double, double, double) * @since 1.2 */ public void setRGB_preserveAlpha(int r, int g, int b){ setValue((getValue() & 0xff000000 ) | Pixel.argb(0, r, g, b)); } /** * Sets an ARGB value at the position currently referenced by this Pixel. <br> * Each channel value is assumed to be within [0.0 .. 1.0]. Channel values * outside these bounds will be clamped to them. * @param a normalized alpha * @param r normalized red * @param g normalized green * @param b normalized blue * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * * @see #setRGB_fromDouble(double, double, double) * @see #setRGB_fromDouble_preserveAlpha(double, double, double) * @see #setARGB(int, int, int, int) * @see #a_asDouble() * @see #r_asDouble() * @see #g_asDouble() * @see #b_asDouble() * @since 1.2 */ public Pixel setARGB_fromDouble(double a, double r, double g, double b){ return setValue(Pixel.argb_fromNormalized(a, r, g, b)); } /** * Sets an opaque RGB value at the position currently referenced by this Pixel. <br> * Each channel value is assumed to be within [0.0 .. 1.0]. Channel values * outside these bounds will be clamped to them. * @param r normalized red * @param g normalized green * @param b normalized blue * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * * @see #setARGB_fromDouble(double, double, double, double) * @see #setRGB_fromDouble_preserveAlpha(double, double, double) * @see #setRGB(int, int, int) * @see #a_asDouble() * @see #r_asDouble() * @see #g_asDouble() * @see #b_asDouble() * @since 1.2 */ public Pixel setRGB_fromDouble(double r, double g, double b){ return setValue(Pixel.rgb_fromNormalized(r, g, b)); } /** * Sets an RGB value at the position currently referenced by this Pixel. * The present alpha value will not be altered by this operation. <br> * Each channel value is assumed to be within [0.0 .. 1.0]. Channel values * outside these bounds will be clamped to them. * @param r normalized red * @param g normalized green * @param b normalized blue * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * * @see #setRGB_preserveAlpha(int, int, int) * @since 1.2 */ public Pixel setRGB_fromDouble_preserveAlpha(double r, double g, double b){ return setValue((getValue() & 0xff000000) | (0x00ffffff & Pixel.rgb_fromNormalized(r, g, b))); } /** * Sets alpha channel value of this Pixel. Value will be truncated to * 8bits (e.g. 0x12ff will truncate to 0xff). * @param a alpha value in range [0..255] * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #setARGB(int a, int r, int g, int b) * @since 1.2 */ public Pixel setA(int a){ return setValue((getValue() & 0x00ffffff) | ((a<<24) & 0xff000000)); } /** * Sets red channel value of this Pixel. Value will be truncated to * 8bits (e.g. 0x12ff will truncate to 0xff). * @param r red value in range [0..255] * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #setARGB(int a, int r, int g, int b) * @see #setRGB(int r, int g, int b) * @since 1.2 */ public Pixel setR(int r){ return setValue((getValue() & 0xff00ffff) | ((r<<16) & 0x00ff0000)); } /** * Sets green channel value of this Pixel. Value will be truncated to * 8bits (e.g. 0x12ff will truncate to 0xff). * @param g green value in range [0..255] * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #setARGB(int a, int r, int g, int b) * @see #setRGB(int r, int g, int b) * @since 1.2 */ public Pixel setG(int g){ return setValue((getValue() & 0xffff00ff) | ((g<<8) & 0x0000ff00)); } /** * Sets blue channel value of this Pixel. Value will be truncated to * 8bits (e.g. 0x12ff will truncate to 0xff). * @param b blue value in range [0..255] * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #setARGB(int a, int r, int g, int b) * @see #setRGB(int r, int g, int b) * @since 1.2 */ public Pixel setB(int b){ return setValue((getValue() & 0xffffff00) | ((b) & 0x000000ff)); } @Override public PixelBase setA_fromDouble(double a) { return setA(clamp_0_255((int)Math.round(a*0xff))); } @Override public PixelBase setR_fromDouble(double r) { return setR(clamp_0_255((int)Math.round(r*0xff))); } @Override public PixelBase setG_fromDouble(double g) { return setG(clamp_0_255((int)Math.round(g*0xff))); } @Override public PixelBase setB_fromDouble(double b) { return setB(clamp_0_255((int)Math.round(b*0xff))); } /** * @return 8bit luminance value of this pixel. <br> * Using weights r=0.2126 g=0.7152 b=0.0722 * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #getGrey(int, int, int) * @see #getLuminance(int) * @since 1.2 */ public int getLuminance(){ return Pixel.getLuminance(getValue()); } /** * Calculates the grey value of this pixel using specified weights. * @param redWeight weight for red channel * @param greenWeight weight for green channel * @param blueWeight weight for blue channel * @return grey value of pixel for specified weights * @throws ArithmeticException divide by zero if the weights sum up to 0. * @throws ArrayIndexOutOfBoundsException if this Pixel's index is not in * range of the Img's data array. * @see #getLuminance() * @see #getGrey(int, int, int, int) * @since 1.2 */ public int getGrey(final int redWeight, final int greenWeight, final int blueWeight){ return Pixel.getGrey(getValue(), redWeight, greenWeight, blueWeight); } @Override public String toString() { return asString(); } /* * * * * * * * * */ // STATIC METHODS // /* * * * * * * * * */ /** * @param color RGB(24bit) or ARGB(32bit) value * @return 8bit luminance value of given RGB value. <br> * Using weights r=0.2126 g=0.7152 b=0.0722 * @see #getGrey(int, int, int, int) * @since 1.0 */ public static final int getLuminance(final int color){ return getGrey(color, 2126, 7152, 722); } /** * Calculates a grey value from an RGB or ARGB value using specified * weights for each R,G and B channel. * <p> * Weights are integer values so normalized weights need to be converted * beforehand. E.g. normalized weights (0.33, 0.62, 0.05) would be have to * be converted to integer weights (33, 62, 5). * <p> * When using weights with same signs, the value is within [0..255]. When * weights have mixed signs the resulting value is unbounded. * @param color RGB(24bit) or ARGB(32bit) value * @param redWeight weight for red channel * @param greenWeight weight for green channel * @param blueWeight weight for blue channel * @return weighted grey value (8bit) of RGB color value for non-negative weights. * @throws ArithmeticException divide by zero if the weights sum up to 0. * @see #getLuminance(int) * @since 1.0 */ public static final int getGrey(final int color, final int redWeight, final int greenWeight, final int blueWeight){ return (r(color)*redWeight + g(color)*greenWeight + b(color)*blueWeight)/(redWeight+blueWeight+greenWeight); } /** * Packs 8bit RGB color components into a single 32bit ARGB integer value * with alpha=255 (opaque). * Components are clamped to [0,255]. * @param r red * @param g green * @param b blue * @return packed ARGB value * * @see #argb(int, int, int, int) * @see #argb_bounded(int, int, int, int) * @see #argb_fast(int, int, int, int) * @see #rgb(int, int, int) * @see #rgb_fast(int, int, int) * @see #a(int) * @see #r(int) * @see #g(int) * @see #b(int) * @since 1.0 */ public static final int rgb_bounded(final int r, final int g, final int b){ return rgb_fast( r > 255 ? 255: r < 0 ? 0:r, g > 255 ? 255: g < 0 ? 0:g, b > 255 ? 255: b < 0 ? 0:b); } /** * Packs 8bit RGB color components into a single 32bit ARGB integer value * with alpha=255 (opaque). * Components larger than 8bit get truncated to 8bit. * @param r red * @param g green * @param b blue * @return packed ARGB value * * @see #argb(int, int, int, int) * @see #argb_bounded(int, int, int, int) * @see #argb_fast(int, int, int, int) * @see #rgb_bounded(int, int, int) * @see #rgb_fast(int, int, int) * @see #a(int) * @see #r(int) * @see #g(int) * @see #b(int) * @since 1.0 */ public static final int rgb(final int r, final int g, final int b){ return rgb_fast(r & 0xff, g & 0xff, b & 0xff); } /** * Packs 8bit RGB color components into a single 32bit ARGB integer value * with alpha=255 (opaque). * Components larger than 8bit are NOT truncated and will result in a * broken, malformed value. * @param r red * @param g green * @param b blue * @return packed ARGB value * * @see #argb(int, int, int, int) * @see #argb_bounded(int, int, int, int) * @see #argb_fast(int, int, int, int) * @see #rgb_bounded(int, int, int) * @see #rgb(int, int, int) * @see #a(int) * @see #r(int) * @see #g(int) * @see #b(int) * @since 1.0 */ public static final int rgb_fast(final int r, final int g, final int b){ return 0xff000000|(r<<16)|(g<<8)|b; } /** * Packs normalized ARGB color components (values in [0.0 .. 1.0]) into a * single 32bit integer value with alpha=255 (opaque). * Component values less than 0 or greater than 1 clamped to fit the range. * @param r red * @param g green * @param b blue * @return packed ARGB value * * @see #argb_fromNormalized(double, double, double, double) * @see #rgb(int, int, int) * @see #a_normalized(int) * @see #r_normalized(int) * @see #g_normalized(int) * @see #b_normalized(int) * @since 1.2 */ public static final int rgb_fromNormalized(final double r, final double g, final double b){ return rgb_bounded((int)Math.round(r*0xff), (int)Math.round(g*0xff), (int)Math.round(b*0xff)); } /** * Packs 8bit ARGB color components into a single 32bit integer value. * Components are clamped to [0,255]. * @param a alpha * @param r red * @param g green * @param b blue * @return packed ARGB value * * @see #argb(int, int, int, int) * @see #argb_fast(int, int, int, int) * @see #rgb_bounded(int, int, int) * @see #rgb(int, int, int) * @see #rgb_fast(int, int, int) * @see #a(int) * @see #r(int) * @see #g(int) * @see #b(int) * @since 1.0 */ public static final int argb_bounded(final int a, final int r, final int g, final int b){ return argb_fast( a > 255 ? 255: a < 0 ? 0:a, r > 255 ? 255: r < 0 ? 0:r, g > 255 ? 255: g < 0 ? 0:g, b > 255 ? 255: b < 0 ? 0:b); } /** * Packs 8bit ARGB color components into a single 32bit integer value. * Components larger than 8bit get truncated to 8bit. * @param a alpha * @param r red * @param g green * @param b blue * @return packed ARGB value * * @see #argb_bounded(int, int, int, int) * @see #argb_fast(int, int, int, int) * @see #rgb_bounded(int, int, int) * @see #rgb(int, int, int) * @see #rgb_fast(int, int, int) * @see #a(int) * @see #r(int) * @see #g(int) * @see #b(int) * @since 1.0 */ public static final int argb(final int a, final int r, final int g, final int b){ return argb_fast(a & 0xff, r & 0xff, g & 0xff, b & 0xff); } /** * Packs 8bit ARGB color components into a single 32bit integer value. * Components larger than 8bit are NOT truncated and will result in a * broken, malformed value. * @param a alpha * @param r red * @param g green * @param b blue * @return packed ARGB value * * @see #argb(int, int, int, int) * @see #argb_bounded(int, int, int, int) * @see #rgb_bounded(int, int, int) * @see #rgb(int, int, int) * @see #rgb_fast(int, int, int) * @see #a(int) * @see #r(int) * @see #g(int) * @see #b(int) * @since 1.0 */ public static final int argb_fast(final int a, final int r, final int g, final int b){ return (a<<24)|(r<<16)|(g<<8)|b; } /** * Packs normalized ARGB color components (values in [0.0 .. 1.0]) into a * single 32bit integer value. * Component values less than 0 or greater than 1 are clamped to fit the range. * @param a alpha * @param r red * @param g green * @param b blue * @return packed ARGB value * * @see #rgb_fromNormalized(double, double, double) * @see #argb(int, int, int, int) * @see #a_normalized(int) * @see #r_normalized(int) * @see #g_normalized(int) * @see #b_normalized(int) * @since 1.2 */ public static final int argb_fromNormalized(final double a, final double r, final double g, final double b){ return argb_bounded((int)Math.round(a*0xff), (int)Math.round(r*0xff), (int)Math.round(g*0xff), (int)Math.round(b*0xff)); } /** * @param color ARGB(32bit) or RGB(24bit) value * @return blue component(8bit) of specified color. * @see #a(int) * @see #r(int) * @see #g(int) * @see #argb(int, int, int, int) * @see #rgb(int, int, int) * @since 1.0 */ public static final int b(final int color){ return (color) & 0xff; } /** * @param color ARGB(32bit) or RGB(24bit) value * @return green component(8bit) of specified color. * @see #a(int) * @see #r(int) * @see #b(int) * @see #argb(int, int, int, int) * @see #rgb(int, int, int) * @since 1.0 */ public static final int g(final int color){ return (color >> 8) & 0xff; } /** * @param color ARGB(32bit) or RGB(24bit) value * @return red component(8bit) of specified color. * @see #a(int) * @see #g(int) * @see #b(int) * @see #argb(int, int, int, int) * @see #rgb(int, int, int) * @since 1.0 */ public static final int r(final int color){ return (color >> 16) & 0xff; } /** * @param color ARGB(32bit) value * @return alpha component(8bit) of specified color. * @see #r(int) * @see #g(int) * @see #b(int) * @see #argb(int, int, int, int) * @see #rgb(int, int, int) * @since 1.0 */ public static final int a(final int color){ return (color >> 24) & 0xff; } /** * @param color ARGB(32bit) or RGB(24bit) value * @return normalized blue component of specified color <br> * (value in [0.0 .. 1.0]). * @see #b() * @see #r_normalized(int) * @see #g_normalized(int) * @see #a_normalized(int) * @since 1.2 */ public static final double b_normalized(final int color){ return b(color)/255.0; } /** * @param color ARGB(32bit) or RGB(24bit) value * @return normalized green component of specified color <br> * (value in [0.0 .. 1.0]). * @see #g() * @see #r_normalized(int) * @see #b_normalized(int) * @see #a_normalized(int) * @since 1.2 */ public static final double g_normalized(final int color){ return g(color)/255.0; } /** * @param color ARGB(32bit) or RGB(24bit) value * @return normalized red component of specified color <br> * (value in [0.0 .. 1.0]). * @see #r() * @see #b_normalized(int) * @see #g_normalized(int) * @see #a_normalized(int) * @since 1.2 */ public static final double r_normalized(final int color){ return r(color)/255.0; } /** * @param color ARGB(32bit) value * @return normalized alpha component of specified color <br> * (value in [0.0 .. 1.0]). * @see #a() * @see #r_normalized(int) * @see #g_normalized(int) * @see #a_normalized(int) * @since 1.2 */ public static final double a_normalized(final int color){ return a(color)/255.0; } }
// 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. /** * DisassociateAddressResponse.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.5.1 Built on : Oct 19, 2009 (10:59:34 EDT) */ package com.amazon.ec2; /** * DisassociateAddressResponse bean class */ public class DisassociateAddressResponse implements org.apache.axis2.databinding.ADBBean{ public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName( "http://ec2.amazonaws.com/doc/2009-10-31/", "DisassociateAddressResponse", "ns1"); private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://ec2.amazonaws.com/doc/2009-10-31/")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * field for DisassociateAddressResponse */ protected com.amazon.ec2.DisassociateAddressResponseType localDisassociateAddressResponse ; /** * Auto generated getter method * @return com.amazon.ec2.DisassociateAddressResponseType */ public com.amazon.ec2.DisassociateAddressResponseType getDisassociateAddressResponse(){ return localDisassociateAddressResponse; } /** * Auto generated setter method * @param param DisassociateAddressResponse */ public void setDisassociateAddressResponse(com.amazon.ec2.DisassociateAddressResponseType param){ this.localDisassociateAddressResponse=param; } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,MY_QNAME){ public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { DisassociateAddressResponse.this.serialize(MY_QNAME,factory,xmlWriter); } }; return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl( MY_QNAME,factory,dataSource); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,factory,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ //We can safely assume an element has only one type associated with it if (localDisassociateAddressResponse==null){ throw new org.apache.axis2.databinding.ADBException("Property cannot be null!"); } localDisassociateAddressResponse.serialize(MY_QNAME,factory,xmlWriter); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ //We can safely assume an element has only one type associated with it return localDisassociateAddressResponse.getPullParser(MY_QNAME); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static DisassociateAddressResponse parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ DisassociateAddressResponse object = new DisassociateAddressResponse(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); while(!reader.isEndElement()) { if (reader.isStartElement() ){ if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2009-10-31/","DisassociateAddressResponse").equals(reader.getName())){ object.setDisassociateAddressResponse(com.amazon.ec2.DisassociateAddressResponseType.Factory.parse(reader)); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } } else { reader.next(); } } // end of while loop } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.patch; import com.intellij.diff.DiffDialogHints; import com.intellij.diff.DiffManager; import com.intellij.diff.chains.DiffRequestChain; import com.intellij.diff.chains.DiffRequestProducer; import com.intellij.diff.chains.DiffRequestProducerException; import com.intellij.diff.requests.DiffRequest; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diff.impl.patch.FilePatch; import com.intellij.openapi.diff.impl.patch.PatchFileHeaderInfo; import com.intellij.openapi.diff.impl.patch.PatchReader; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.fileTypes.FileTypeRegistry; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopupStep; import com.intellij.openapi.ui.popup.PopupStep; import com.intellij.openapi.ui.popup.util.BaseListPopupStep; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.StreamUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vcs.changes.*; import com.intellij.openapi.vcs.changes.shelf.ShelvedBinaryFilePatch; import com.intellij.openapi.vcs.changes.ui.*; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.ui.*; import com.intellij.ui.components.JBLoadingPanel; import com.intellij.util.Alarm; import com.intellij.util.concurrency.annotations.RequiresEdt; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.vcs.log.VcsUser; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.tree.DefaultTreeModel; import java.awt.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.InputStreamReader; import java.util.List; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Supplier; import static com.intellij.openapi.util.text.StringUtil.isEmptyOrSpaces; import static com.intellij.util.ObjectUtils.chooseNotNull; import static com.intellij.util.containers.ContainerUtil.map; public class ApplyPatchDifferentiatedDialog extends DialogWrapper { @ApiStatus.Internal public static final String DIMENSION_SERVICE_KEY = "vcs.ApplyPatchDifferentiatedDialog"; private static final Logger LOG = Logger.getInstance(ApplyPatchDifferentiatedDialog.class); private final ZipperUpdater myLoadQueue; private final TextFieldWithBrowseButton myPatchFile; private final List<AbstractFilePatchInProgress<?>> myPatches; private final List<ShelvedBinaryFilePatch> myBinaryShelvedPatches; @NotNull private final EditorNotificationPanel myErrorNotificationPanel; @NotNull private final MyChangeTreeList myChangesTreeList; @NotNull private final JBLoadingPanel myChangesTreeLoadingPanel; @Nullable private final Collection<? extends Change> myPreselectedChanges; private final boolean myUseProjectRootAsPredefinedBase; private JComponent myCenterPanel; protected final Project myProject; private final AtomicReference<FilePresentationModel> myRecentPathFileChange; private final ApplyPatchDifferentiatedDialog.MyUpdater myUpdater; private final Runnable myReset; @Nullable private final ChangeListChooserPanel myChangeListChooser; private final ChangesLegendCalculator myInfoCalculator; private final CommitLegendPanel myCommitLegendPanel; private final ApplyPatchExecutor myCallback; private final List<? extends ApplyPatchExecutor> myExecutors; private boolean myContainBasedChanges; private JLabel myPatchFileLabel; private PatchReader myReader; private final boolean myCanChangePatchFile; private String myHelpId = "reference.dialogs.vcs.patch.apply"; //NON-NLS private final boolean myShouldUpdateChangeListName; public ApplyPatchDifferentiatedDialog(Project project, ApplyPatchExecutor<?> callback, List<? extends ApplyPatchExecutor<?>> executors, @NotNull ApplyPatchMode applyPatchMode, @NotNull VirtualFile patchFile) { this(project, callback, executors, applyPatchMode, patchFile, null, null, null, null, null, false); } public ApplyPatchDifferentiatedDialog(Project project, ApplyPatchExecutor<?> callback, List<? extends ApplyPatchExecutor<?>> executors, @NotNull ApplyPatchMode applyPatchMode, @NotNull List<FilePatch> patches, @Nullable ChangeList defaultList) { this(project, callback, executors, applyPatchMode, null, patches, defaultList, null, null, null, false); } public ApplyPatchDifferentiatedDialog(Project project, ApplyPatchExecutor<?> callback, List<? extends ApplyPatchExecutor<?>> executors, @NotNull ApplyPatchMode applyPatchMode, @Nullable VirtualFile patchFile, @Nullable List<FilePatch> patches, @Nullable ChangeList defaultList, @Nullable List<ShelvedBinaryFilePatch> binaryShelvedPatches, @Nullable Collection<Change> preselectedChanges, @Nullable @NlsSafe String externalCommitMessage, boolean useProjectRootAsPredefinedBase) { super(project, true); myCallback = callback; myExecutors = executors; myUseProjectRootAsPredefinedBase = useProjectRootAsPredefinedBase; setModal(false); setHorizontalStretch(2); setVerticalStretch(2); setTitle(applyPatchMode.getTitle()); final FileChooserDescriptor descriptor = createSelectPatchDescriptor(); descriptor.setTitle(VcsBundle.message("patch.apply.select.title")); myProject = project; myPatches = new ArrayList<>(); myRecentPathFileChange = new AtomicReference<>(); myBinaryShelvedPatches = binaryShelvedPatches; myPreselectedChanges = preselectedChanges; myErrorNotificationPanel = new EditorNotificationPanel(LightColors.RED); cleanNotifications(); myChangesTreeList = new MyChangeTreeList(project, new Runnable() { @Override public void run() { final NamedLegendStatuses includedNameStatuses = new NamedLegendStatuses(); final Collection<AbstractFilePatchInProgress.PatchChange> includedChanges = myChangesTreeList.getIncludedChanges(); final Set<Couple<String>> set = new HashSet<>(); for (AbstractFilePatchInProgress.PatchChange change : includedChanges) { final FilePatch patch = change.getPatchInProgress().getPatch(); final Couple<String> pair = Couple.of(patch.getBeforeName(), patch.getAfterName()); if (set.contains(pair)) continue; set.add(pair); acceptChange(includedNameStatuses, change); } myInfoCalculator.setIncluded(includedNameStatuses); myCommitLegendPanel.update(); updateOkActions(); } }, new MyChangeNodeDecorator()); myChangesTreeList.setDoubleClickAndEnterKeyHandler(() -> { List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges(); if (selectedChanges.size() == 1 && !selectedChanges.get(0).isValid()) { myChangesTreeList.handleInvalidChangesAndToggle(); } new MyShowDiff().showDiff(); }); myChangesTreeLoadingPanel = new JBLoadingPanel(new BorderLayout(), getDisposable()); myChangesTreeLoadingPanel.add(myChangesTreeList, BorderLayout.CENTER); myShouldUpdateChangeListName = defaultList == null && externalCommitMessage == null; myUpdater = new MyUpdater(); myPatchFile = new TextFieldWithBrowseButton(); myPatchFile.addBrowseFolderListener(VcsBundle.message("patch.apply.select.title"), "", project, descriptor); myPatchFile.getTextField().getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(@NotNull DocumentEvent e) { setPathFileChangeDefault(); queueRequest(); } }); myLoadQueue = new ZipperUpdater(500, Alarm.ThreadToUse.POOLED_THREAD, getDisposable()); myCanChangePatchFile = applyPatchMode.isCanChangePatchFile(); myReset = myCanChangePatchFile ? this::reset : EmptyRunnable.getInstance(); ChangeListManager changeListManager = ChangeListManager.getInstance(project); if (changeListManager.areChangeListsEnabled()) { myChangeListChooser = new ChangeListChooserPanel(project, new Consumer<>() { @Override public void accept(final @Nullable @NlsContexts.DialogMessage String errorMessage) { setOKActionEnabled(errorMessage == null && isChangeTreeEnabled()); setErrorText(errorMessage, myChangeListChooser); } }); if (defaultList != null) { myChangeListChooser.setDefaultSelection(defaultList); } else if (externalCommitMessage != null) { myChangeListChooser.setSuggestedName(externalCommitMessage); } myChangeListChooser.init(); } else { myChangeListChooser = null; } myInfoCalculator = new ChangesLegendCalculator(); myCommitLegendPanel = new CommitLegendPanel(myInfoCalculator) { @Override public void update() { super.update(); final int inapplicable = myInfoCalculator.getInapplicable(); if (inapplicable > 0) { appendSpace(); append(inapplicable, FileStatus.MERGED_WITH_CONFLICTS, VcsBundle.message("patch.apply.missing.base.file.label")); } } }; init(); if (patchFile != null && patchFile.isValid()) { patchFile.refresh(false, false); init(patchFile); } else if (patches != null) { init(patches); } myPatchFileLabel.setVisible(myCanChangePatchFile); myPatchFile.setVisible(myCanChangePatchFile); if (myCanChangePatchFile) { BulkFileListener listener = new BulkFileListener() { @Override public void after(@NotNull List<? extends @NotNull VFileEvent> events) { for (VFileEvent event : events) { if (event instanceof VFileContentChangeEvent) { syncUpdatePatchFileAndScheduleReloadIfNeeded(event.getFile()); } } } }; ApplicationManager.getApplication().getMessageBus().connect(getDisposable()) .subscribe(VirtualFileManager.VFS_CHANGES, listener); } updateOkActions(); } private void updateOkActions() { boolean changeTreeEnabled = isChangeTreeEnabled(); setOKActionEnabled(changeTreeEnabled); if (changeTreeEnabled) { if (myChangeListChooser != null) myChangeListChooser.updateEnabled(); } } private boolean isChangeTreeEnabled() { return !myChangesTreeList.getIncludedChanges().isEmpty(); } private void queueRequest() { paintBusy(true); myLoadQueue.queue(myUpdater); } private void init(@NotNull List<FilePatch> patches) { List<AbstractFilePatchInProgress<?>> matchedPatches = new MatchPatchPaths(myProject).execute(patches, myUseProjectRootAsPredefinedBase); //todo add shelved binary patches ApplicationManager.getApplication().invokeLater(() -> { myPatches.clear(); myPatches.addAll(matchedPatches); updateTree(true); }); } public static FileChooserDescriptor createSelectPatchDescriptor() { return new FileChooserDescriptor(true, false, false, false, false, false) { @Override public boolean isFileSelectable(VirtualFile file) { return FileTypeRegistry.getInstance().isFileOfType(file, PatchFileType.INSTANCE) || FileTypeRegistry.getInstance().isFileOfType(file, FileTypes.PLAIN_TEXT); } }; } @Override protected Action @NotNull [] createActions() { if (myExecutors.isEmpty()) { return super.createActions(); } final List<Action> actions = new ArrayList<>(4); actions.add(getOKAction()); for (int i = 0; i < myExecutors.size(); i++) { final ApplyPatchExecutor executor = myExecutors.get(i); final int finalI = i; actions.add(new AbstractAction(executor.getName()) { @Override public void actionPerformed(ActionEvent e) { runExecutor(executor); close(NEXT_USER_EXIT_CODE + finalI); } }); } actions.add(getCancelAction()); actions.add(getHelpAction()); return actions.toArray(new Action[0]); } @RequiresEdt private void runExecutor(ApplyPatchExecutor<AbstractFilePatchInProgress<?>> executor) { Collection<AbstractFilePatchInProgress<?>> included = getIncluded(); if (included.isEmpty()) { return; } MultiMap<VirtualFile, AbstractFilePatchInProgress<?>> patchGroups = new MultiMap<>(); for (AbstractFilePatchInProgress<?> patchInProgress : included) { patchGroups.putValue(patchInProgress.getBase(), patchInProgress); } LocalChangeList targetChangelist = getSelectedChangeList(); FilePresentationModel presentation = myRecentPathFileChange.get(); VirtualFile vf = presentation != null ? presentation.getVf() : null; executor.apply(getOriginalRemaining(), patchGroups, targetChangelist, vf == null ? null : vf.getName(), myReader == null ? null : myReader.getAdditionalInfo(ApplyPatchDefaultExecutor.pathsFromGroups(patchGroups))); } @NotNull private List<FilePatch> getOriginalRemaining() { Collection<AbstractFilePatchInProgress> notIncluded = ContainerUtil.subtract(myPatches, getIncluded()); List<FilePatch> remainingOriginal = new ArrayList<>(); for (AbstractFilePatchInProgress progress : notIncluded) { progress.reset(); remainingOriginal.add(progress.getPatch()); } return remainingOriginal; } @Override @NonNls protected String getDimensionServiceKey() { return DIMENSION_SERVICE_KEY; } @Override protected String getHelpId() { return myHelpId; } @Nullable @Override public JComponent getPreferredFocusedComponent() { if (myChangeListChooser != null) return myChangeListChooser.getPreferredFocusedComponent(); return myChangesTreeList; } private void setPathFileChangeDefault() { myRecentPathFileChange.set(new FilePresentationModel(myPatchFile.getText())); } private void init(@NotNull final VirtualFile patchFile) { myPatchFile.setText(patchFile.getPresentableUrl()); myRecentPathFileChange.set(new FilePresentationModel(patchFile)); } public void setHelpId(String s) { myHelpId = s; } private class MyUpdater implements Runnable { @Override public void run() { cleanNotifications(); final FilePresentationModel filePresentationModel = myRecentPathFileChange.get(); final VirtualFile file = filePresentationModel != null ? filePresentationModel.getVf() : null; if (file == null) { ApplicationManager.getApplication().invokeLater(myReset, ModalityState.stateForComponent(myCenterPanel)); return; } myReader = loadPatches(file); final PatchFileHeaderInfo patchFileInfo = myReader != null ? myReader.getPatchFileInfo() : null; final String messageFromPatch = patchFileInfo != null ? patchFileInfo.getMessage() : null; VcsUser author = patchFileInfo != null ? patchFileInfo.getAuthor() : null; if (author != null && myChangeListChooser != null) { myChangeListChooser.setData(new ChangeListData(author)); } List<FilePatch> filePatches = new ArrayList<>(); if (myReader != null) { filePatches.addAll(myReader.getAllPatches()); } if (!ContainerUtil.isEmpty(myBinaryShelvedPatches)) { filePatches.addAll(myBinaryShelvedPatches); } List<AbstractFilePatchInProgress<?>> matchedPatches = new MatchPatchPaths(myProject).execute(filePatches, myUseProjectRootAsPredefinedBase); ApplicationManager.getApplication().invokeLater(() -> { if (myShouldUpdateChangeListName && myChangeListChooser != null) { String subject = chooseNotNull(getSubjectFromMessage(messageFromPatch), file.getNameWithoutExtension().replace('_', ' ').trim()); myChangeListChooser.setSuggestedName(subject, messageFromPatch, false); } myPatches.clear(); myPatches.addAll(matchedPatches); updateTree(true); paintBusy(false); updateOkActions(); }, ModalityState.stateForComponent(myCenterPanel)); } } @Nullable private String getSubjectFromMessage(@Nullable String message) { return isEmptyOrSpaces(message) ? null : ChangeListUtil.createNameForChangeList(myProject, message); } @Nullable private PatchReader loadPatches(@NotNull VirtualFile patchFile) { try { String text = ReadAction.compute(() -> { try (InputStreamReader inputStreamReader = new InputStreamReader(patchFile.getInputStream(), patchFile.getCharset())) { return StreamUtil.readText(inputStreamReader); } }); PatchReader reader = new PatchReader(text); reader.parseAllPatches(); return reader; } catch (Exception e) { addNotificationAndWarn(VcsBundle.message("patch.apply.cannot.read.patch", patchFile.getPresentableName(), e.getMessage())); return null; } } private void addNotificationAndWarn(@NotNull @NlsContexts.Label String errorMessage) { LOG.warn(errorMessage); myErrorNotificationPanel.setText(errorMessage); myErrorNotificationPanel.setVisible(true); } private void cleanNotifications() { myErrorNotificationPanel.setText(""); myErrorNotificationPanel.setVisible(false); } @RequiresEdt private void syncUpdatePatchFileAndScheduleReloadIfNeeded(@Nullable VirtualFile eventFile) { // if dialog is modal and refresh called not from dispatch thread then // fireEvents in RefreshQueueImpl will not be triggered because of wrong modality state inside those thread -> defaultMS == NON_MODAL final FilePresentationModel filePresentationModel = myRecentPathFileChange.get(); VirtualFile filePresentationVf = filePresentationModel != null ? filePresentationModel.getVf() : null; if (filePresentationVf != null && (eventFile == null || filePresentationVf.equals(eventFile))) { filePresentationVf.refresh(false, false); queueRequest(); } } private static class FilePresentationModel { @NotNull private final String myPath; @Nullable private VirtualFile myVf; private FilePresentationModel(@NotNull String path) { myPath = path; myVf = null; // don't try to find vf for each typing; only when requested } FilePresentationModel(@NotNull VirtualFile file) { myPath = file.getPath(); myVf = file; } @Nullable public VirtualFile getVf() { if (myVf == null) { final VirtualFile file = VfsUtil.findFileByIoFile(new File(myPath), true); myVf = file != null && !file.isDirectory() ? file : null; } return myVf; } } private void reset() { myPatches.clear(); myChangesTreeList.setChangesToDisplay(Collections.emptyList()); myChangesTreeList.repaint(); myContainBasedChanges = false; paintBusy(false); } @Override protected JComponent createCenterPanel() { if (myCenterPanel == null) { myCenterPanel = new JPanel(new GridBagLayout()); final GridBagConstraints centralGb = createConstraints(); myPatchFileLabel = new JLabel(VcsBundle.message("patch.apply.file.name.field")); myPatchFileLabel.setLabelFor(myPatchFile); myCenterPanel.add(myPatchFileLabel, centralGb); centralGb.fill = GridBagConstraints.HORIZONTAL; ++centralGb.gridy; myCenterPanel.add(myPatchFile, centralGb); JPanel treePanel = new JPanel(new GridBagLayout()); final GridBagConstraints gb = createConstraints(); final DefaultActionGroup group = new DefaultActionGroup(); final MyShowDiff diffAction = new MyShowDiff(); diffAction.registerCustomShortcutSet(CommonShortcuts.getDiff(), getRootPane()); group.add(diffAction); ActionGroup mapDirectoryActionGroup = new ActionGroup(VcsBundle.message("patch.apply.change.directory.paths.group"), null, AllIcons.Vcs.Folders) { @Override public AnAction @NotNull [] getChildren(@Nullable AnActionEvent e) { return new AnAction[]{ new MapDirectory(), new StripUp(IdeBundle.messagePointer("action.Anonymous.text.remove.leading.directory")), new ZeroStrip(), new StripDown(IdeBundle.messagePointer("action.Anonymous.text.restore.leading.directory")), new ResetStrip()}; } }; mapDirectoryActionGroup.setPopup(true); group.add(mapDirectoryActionGroup); if (myCanChangePatchFile) { group.add(new DumbAwareAction(VcsBundle.messagePointer("action.DumbAware.ApplyPatchDifferentiatedDialog.text.refresh"), VcsBundle.messagePointer("action.DumbAware.ApplyPatchDifferentiatedDialog.description.refresh"), AllIcons.Actions.Refresh) { @Override public void actionPerformed(@NotNull AnActionEvent e) { syncUpdatePatchFileAndScheduleReloadIfNeeded(null); } }); } group.add(Separator.getInstance()); group.add(ActionManager.getInstance().getAction(ChangesTree.GROUP_BY_ACTION_GROUP)); final ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("APPLY_PATCH", group, true); TreeActionsToolbarPanel toolbarPanel = new TreeActionsToolbarPanel(toolbar, myChangesTreeList); gb.fill = GridBagConstraints.HORIZONTAL; treePanel.add(toolbarPanel, gb); ++gb.gridy; gb.weighty = 1; gb.fill = GridBagConstraints.BOTH; JPanel changeTreePanel = JBUI.Panels.simplePanel(myChangesTreeLoadingPanel).addToTop(myErrorNotificationPanel); treePanel.add(ScrollPaneFactory.createScrollPane(changeTreePanel), gb); ++gb.gridy; gb.weighty = 0; gb.fill = GridBagConstraints.NONE; gb.insets.bottom = UIUtil.DEFAULT_VGAP; treePanel.add(myCommitLegendPanel.getComponent(), gb); ++gb.gridy; ++centralGb.gridy; centralGb.weighty = 1; centralGb.fill = GridBagConstraints.BOTH; if (myChangeListChooser != null) { Splitter splitter = new Splitter(true, 0.7f); splitter.setFirstComponent(treePanel); splitter.setSecondComponent(myChangeListChooser); myCenterPanel.add(splitter, centralGb); } else { myCenterPanel.add(treePanel, centralGb); } } return myCenterPanel; } @NotNull private static GridBagConstraints createConstraints() { return new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, JBUI.insets(1), 0, 0); } private void paintBusy(final boolean isBusy) { if (isBusy) { myChangesTreeList.setEmptyText(""); myChangesTreeLoadingPanel.startLoading(); } else { myChangesTreeList.setEmptyText(VcsBundle.message("commit.dialog.no.changes.detected.text")); myChangesTreeLoadingPanel.stopLoading(); } } private final class MyChangeTreeList extends ChangesTreeImpl<AbstractFilePatchInProgress.PatchChange> { @Nullable private final ChangeNodeDecorator myChangeNodeDecorator; private MyChangeTreeList(Project project, @Nullable Runnable inclusionListener, @Nullable ChangeNodeDecorator decorator) { super(project, true, false, AbstractFilePatchInProgress.PatchChange.class); setInclusionListener(inclusionListener); myChangeNodeDecorator = decorator; } @NotNull @Override protected DefaultTreeModel buildTreeModel(@NotNull List<? extends AbstractFilePatchInProgress.PatchChange> changes) { return TreeModelBuilder.buildFromChanges(myProject, getGrouping(), changes, myChangeNodeDecorator); } @Override protected boolean isInclusionEnabled(@NotNull ChangesBrowserNode<?> node) { boolean enabled = super.isInclusionEnabled(node); Object value = node.getUserObject(); if (value instanceof AbstractFilePatchInProgress.PatchChange) { enabled &= ((AbstractFilePatchInProgress.PatchChange)value).isValid(); } return enabled; } @NotNull private List<AbstractFilePatchInProgress.PatchChange> getOnlyValidChanges(@NotNull Collection<? extends AbstractFilePatchInProgress.PatchChange> changes) { return ContainerUtil.filter(changes, AbstractFilePatchInProgress.PatchChange::isValid); } @Override protected void toggleChanges(@NotNull Collection<?> changes) { List<AbstractFilePatchInProgress.PatchChange> patchChanges = ContainerUtil.findAll(changes, AbstractFilePatchInProgress.PatchChange.class); if (patchChanges.size() == 1 && !patchChanges.get(0).isValid()) { handleInvalidChangesAndToggle(); } else { super.toggleChanges(getOnlyValidChanges(patchChanges)); } } private void handleInvalidChangesAndToggle() { new NewBaseSelector(false).run(); super.toggleChanges(getOnlyValidChanges(getSelectedChanges())); } } private final class MapDirectory extends DumbAwareAction { private final NewBaseSelector myNewBaseSelector; private MapDirectory() { super(VcsBundle.message("patch.apply.map.base.directory.action")); myNewBaseSelector = new NewBaseSelector(); } @Override public void actionPerformed(@NotNull AnActionEvent e) { final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges(); if ((selectedChanges.size() >= 1) && (sameBase(selectedChanges))) { final AbstractFilePatchInProgress.PatchChange patchChange = selectedChanges.get(0); final AbstractFilePatchInProgress patch = patchChange.getPatchInProgress(); final List<VirtualFile> autoBases = patch.getAutoBasesCopy(); if (autoBases.isEmpty() || (autoBases.size() == 1 && autoBases.get(0).equals(patch.getBase()))) { myNewBaseSelector.run(); } else { autoBases.add(null); ListPopupStep<VirtualFile> step = new MapPopup(autoBases, myNewBaseSelector); JBPopupFactory.getInstance().createListPopup(step).showCenteredInCurrentWindow(myProject); } } } @Override public void update(@NotNull AnActionEvent e) { final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges(); e.getPresentation().setEnabled((selectedChanges.size() >= 1) && (sameBase(selectedChanges))); } } private static boolean sameBase(final List<? extends AbstractFilePatchInProgress.PatchChange> selectedChanges) { VirtualFile base = null; for (AbstractFilePatchInProgress.PatchChange change : selectedChanges) { final VirtualFile changeBase = change.getPatchInProgress().getBase(); if (base == null) { base = changeBase; } else if (!base.equals(changeBase)) { return false; } } return true; } private void updateTree(boolean doInitCheck) { final List<AbstractFilePatchInProgress> patchesToSelect = changes2patches(myChangesTreeList.getSelectedChanges()); final List<AbstractFilePatchInProgress.PatchChange> changes = getAllChanges(); final Collection<AbstractFilePatchInProgress.PatchChange> included = getIncluded(doInitCheck, changes); myChangesTreeList.setIncludedChanges(included); myChangesTreeList.setChangesToDisplay(changes); if (doInitCheck) { myChangesTreeList.expandAll(); } myChangesTreeList.repaint(); if (!doInitCheck) { final List<AbstractFilePatchInProgress.PatchChange> toSelect = new ArrayList<>(patchesToSelect.size()); for (AbstractFilePatchInProgress.PatchChange change : changes) { if (patchesToSelect.contains(change.getPatchInProgress())) { toSelect.add(change); } } myChangesTreeList.setSelectedChanges(toSelect); } myContainBasedChanges = false; for (AbstractFilePatchInProgress patch : myPatches) { if (patch.baseExistsOrAdded()) { myContainBasedChanges = true; break; } } } private List<AbstractFilePatchInProgress.PatchChange> getAllChanges() { return map(myPatches, AbstractFilePatchInProgress::getChange); } private static void acceptChange(final NamedLegendStatuses nameStatuses, final AbstractFilePatchInProgress.PatchChange change) { final AbstractFilePatchInProgress patchInProgress = change.getPatchInProgress(); if (FilePatchStatus.ADDED.equals(patchInProgress.getStatus())) { nameStatuses.plusAdded(); } else if (FilePatchStatus.DELETED.equals(patchInProgress.getStatus())) { nameStatuses.plusDeleted(); } else { nameStatuses.plusModified(); } if (!patchInProgress.baseExistsOrAdded()) { nameStatuses.plusInapplicable(); // may be deleted or modified, but still not applicable } } private Collection<AbstractFilePatchInProgress.PatchChange> getIncluded(boolean doInitCheck, List<? extends AbstractFilePatchInProgress.PatchChange> changes) { final NamedLegendStatuses totalNameStatuses = new NamedLegendStatuses(); final NamedLegendStatuses includedNameStatuses = new NamedLegendStatuses(); final Collection<AbstractFilePatchInProgress.PatchChange> included = new ArrayList<>(); if (doInitCheck) { for (AbstractFilePatchInProgress.PatchChange change : changes) { acceptChange(totalNameStatuses, change); final AbstractFilePatchInProgress abstractFilePatchInProgress = change.getPatchInProgress(); if (abstractFilePatchInProgress.baseExistsOrAdded() && (myPreselectedChanges == null || myPreselectedChanges.contains(change))) { acceptChange(includedNameStatuses, change); included.add(change); } } } else { // todo maybe written pretty final Collection<AbstractFilePatchInProgress.PatchChange> includedNow = myChangesTreeList.getIncludedChanges(); final Set<AbstractFilePatchInProgress> toBeIncluded = new HashSet<>(); for (AbstractFilePatchInProgress.PatchChange change : includedNow) { final AbstractFilePatchInProgress patch = change.getPatchInProgress(); toBeIncluded.add(patch); } for (AbstractFilePatchInProgress.PatchChange change : changes) { final AbstractFilePatchInProgress patch = change.getPatchInProgress(); acceptChange(totalNameStatuses, change); if (toBeIncluded.contains(patch) && patch.baseExistsOrAdded()) { acceptChange(includedNameStatuses, change); included.add(change); } } } myInfoCalculator.setTotal(totalNameStatuses); myInfoCalculator.setIncluded(includedNameStatuses); myCommitLegendPanel.update(); return included; } private class NewBaseSelector implements Runnable { final boolean myDirectorySelector; NewBaseSelector() { this(true); } NewBaseSelector(boolean directorySelector) { myDirectorySelector = directorySelector; } @Override public void run() { final FileChooserDescriptor descriptor = myDirectorySelector ? FileChooserDescriptorFactory.createSingleFolderDescriptor() : FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(); descriptor.setTitle(VcsBundle.message("patch.apply.select.base.title", myDirectorySelector ? 0 : 1)); VirtualFile selectedFile = FileChooser.chooseFile(descriptor, myProject, null); if (selectedFile == null) { return; } final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges(); if (selectedChanges.size() >= 1) { for (AbstractFilePatchInProgress.PatchChange patchChange : selectedChanges) { final AbstractFilePatchInProgress patch = patchChange.getPatchInProgress(); if (myDirectorySelector) { patch.setNewBase(selectedFile); } else { final FilePatch filePatch = patch.getPatch(); //if file was renamed in the patch but applied on another or already renamed local one then we shouldn't apply this rename/move filePatch.setAfterName(selectedFile.getName()); filePatch.setBeforeName(selectedFile.getName()); patch.setNewBase(selectedFile.getParent()); } } updateTree(false); } } } private static List<AbstractFilePatchInProgress> changes2patches(final List<? extends AbstractFilePatchInProgress.PatchChange> selectedChanges) { return map(selectedChanges, AbstractFilePatchInProgress.PatchChange::getPatchInProgress); } private final class MapPopup extends BaseListPopupStep<VirtualFile> { private final Runnable myNewBaseSelector; private MapPopup(final @NotNull List<? extends VirtualFile> aValues, Runnable newBaseSelector) { super(VcsBundle.message("path.apply.select.base.directory.for.a.path.popup"), aValues); myNewBaseSelector = newBaseSelector; } @Override public boolean isSpeedSearchEnabled() { return true; } @Override public PopupStep onChosen(final VirtualFile selectedValue, boolean finalChoice) { if (selectedValue == null) { myNewBaseSelector.run(); return null; } final List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges(); if (selectedChanges.size() >= 1) { for (AbstractFilePatchInProgress.PatchChange patchChange : selectedChanges) { final AbstractFilePatchInProgress patch = patchChange.getPatchInProgress(); patch.setNewBase(selectedValue); } updateTree(false); } return null; } @NotNull @Override public String getTextFor(VirtualFile value) { return value == null ? VcsBundle.message("patch.apply.select.base.for.a.path.message") : value.getPath(); //NON-NLS } } private static class NamedLegendStatuses { private int myAdded; private int myModified; private int myDeleted; private int myInapplicable; NamedLegendStatuses() { myAdded = 0; myModified = 0; myDeleted = 0; myInapplicable = 0; } public void plusAdded() { ++myAdded; } public void plusModified() { ++myModified; } public void plusDeleted() { ++myDeleted; } public void plusInapplicable() { ++myInapplicable; } public int getAdded() { return myAdded; } public int getModified() { return myModified; } public int getDeleted() { return myDeleted; } public int getInapplicable() { return myInapplicable; } } private static final class ChangesLegendCalculator implements CommitLegendPanel.InfoCalculator { private NamedLegendStatuses myTotal; private NamedLegendStatuses myIncluded; private ChangesLegendCalculator() { myTotal = new NamedLegendStatuses(); myIncluded = new NamedLegendStatuses(); } public void setTotal(final NamedLegendStatuses nameStatuses) { myTotal = nameStatuses; } public void setIncluded(final NamedLegendStatuses nameStatuses) { myIncluded = nameStatuses; } @Override public int getNew() { return myTotal.getAdded(); } @Override public int getModified() { return myTotal.getModified(); } @Override public int getDeleted() { return myTotal.getDeleted(); } @Override public int getUnversioned() { return 0; } public int getInapplicable() { return myTotal.getInapplicable(); } @Override public int getIncludedNew() { return myIncluded.getAdded(); } @Override public int getIncludedModified() { return myIncluded.getModified(); } @Override public int getIncludedDeleted() { return myIncluded.getDeleted(); } @Override public int getIncludedUnversioned() { return 0; } } private final class MyChangeNodeDecorator implements ChangeNodeDecorator { @Override public void decorate(@NotNull Change change, @NotNull SimpleColoredComponent component, boolean isShowFlatten) { if (change instanceof AbstractFilePatchInProgress.PatchChange) { final AbstractFilePatchInProgress.PatchChange patchChange = (AbstractFilePatchInProgress.PatchChange)change; final AbstractFilePatchInProgress patchInProgress = patchChange.getPatchInProgress(); if (patchInProgress.getCurrentStrip() > 0) { component.append(VcsBundle.message("patch.apply.stripped.description", patchInProgress.getCurrentStrip()), SimpleTextAttributes.GRAY_ITALIC_ATTRIBUTES); } final String text; if (FilePatchStatus.ADDED.equals(patchInProgress.getStatus())) { text = VcsBundle.message("patch.apply.added.status"); } else if (FilePatchStatus.DELETED.equals(patchInProgress.getStatus())) { text = VcsBundle.message("patch.apply.deleted.status"); } else { text = VcsBundle.message("patch.apply.modified.status"); } component.append(" "); component.append(text, SimpleTextAttributes.GRAY_ATTRIBUTES); if (!patchInProgress.baseExistsOrAdded()) { component.append(" "); component.append(VcsBundle.message("patch.apply.select.missing.base.link"), SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES, (Runnable)myChangesTreeList::handleInvalidChangesAndToggle); } else { if (!patchInProgress.getStatus().equals(FilePatchStatus.ADDED) && basePathWasChanged(patchInProgress)) { component.append(" "); component .append(VcsBundle.message("patch.apply.new.base.detected.node.description"), SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES); component.setToolTipText(VcsBundle.message("patch.apply.old.new.base.info", patchInProgress.getOriginalBeforePath(), myProject.getBasePath(), patchInProgress.getPatch().getBeforeName(), patchInProgress.getBase().getPath())); } } } } @Override public void preDecorate(@NotNull Change change, @NotNull ChangesBrowserNodeRenderer renderer, boolean showFlatten) { } } private boolean basePathWasChanged(@NotNull AbstractFilePatchInProgress patchInProgress) { return !FileUtil .filesEqual(patchInProgress.myIoCurrentBase, new File(myProject.getBasePath(), patchInProgress.getOriginalBeforePath())); } private Collection<AbstractFilePatchInProgress<?>> getIncluded() { return map(myChangesTreeList.getIncludedChanges(), AbstractFilePatchInProgress.PatchChange::getPatchInProgress); } @Nullable private LocalChangeList getSelectedChangeList() { return myChangeListChooser != null ? myChangeListChooser.getSelectedList(myProject) : null; } @Override protected void doOKAction() { super.doOKAction(); runExecutor(myCallback); } private class ZeroStrip extends StripUp { ZeroStrip() { super(VcsBundle.messagePointer("action.Anonymous.text.remove.all.leading.directories")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myChangesTreeList.getSelectedChanges().forEach(change -> change.getPatchInProgress().setZero()); updateTree(false); } } private class StripDown extends DumbAwareAction { StripDown(@NotNull Supplier<String> text) { super(text); } @Override public void update(@NotNull AnActionEvent e) { boolean isEnabled = ContainerUtil.exists(myChangesTreeList.getSelectedChanges(), change -> change.getPatchInProgress().canDown()); e.getPresentation().setEnabled(isEnabled); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myChangesTreeList.getSelectedChanges().forEach(change -> change.getPatchInProgress().down()); updateTree(false); } } private class StripUp extends DumbAwareAction { StripUp(Supplier<String> text) { super(text); } @Override public void update(@NotNull AnActionEvent e) { boolean isEnabled = ContainerUtil.exists(myChangesTreeList.getSelectedChanges(), change -> change.getPatchInProgress().canUp()); e.getPresentation().setEnabled(isEnabled); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myChangesTreeList.getSelectedChanges().forEach(change -> change.getPatchInProgress().up()); updateTree(false); } } private class ResetStrip extends StripDown { ResetStrip() { super(VcsBundle.messagePointer("action.Anonymous.text.restore.all.leading.directories")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myChangesTreeList.getSelectedChanges().forEach(change -> change.getPatchInProgress().reset()); updateTree(false); } } private final class MyShowDiff extends DumbAwareAction { private final MyChangeComparator myMyChangeComparator; private MyShowDiff() { super(VcsBundle.message("action.name.show.difference"),null, AllIcons.Actions.Diff); myMyChangeComparator = new MyChangeComparator(); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabled((!myPatches.isEmpty()) && myContainBasedChanges); } @Override public void actionPerformed(@NotNull AnActionEvent e) { showDiff(); } private void showDiff() { if (ChangeListManager.getInstance(myProject).isFreezedWithNotification(null)) return; if (myPatches.isEmpty() || (!myContainBasedChanges)) return; final List<AbstractFilePatchInProgress.PatchChange> changes = getAllChanges(); changes.sort(myMyChangeComparator); List<AbstractFilePatchInProgress.PatchChange> selectedChanges = myChangesTreeList.getSelectedChanges(); if (changes.isEmpty()) return; final AbstractFilePatchInProgress.PatchChange selectedChange = !selectedChanges.isEmpty() ? selectedChanges.get(0) : changes.get(0); int selectedIdx = 0; List<ChangeDiffRequestChain.Producer> diffRequestPresentableList = new ArrayList<>(); for (AbstractFilePatchInProgress.PatchChange change : changes) { diffRequestPresentableList.add(createDiffRequestProducer(change)); if (change.equals(selectedChange)) { selectedIdx = diffRequestPresentableList.size() - 1; } } DiffRequestChain chain = new ChangeDiffRequestChain(diffRequestPresentableList, selectedIdx); DiffManager.getInstance().showDiff(myProject, chain, DiffDialogHints.DEFAULT); } @NotNull private ChangeDiffRequestChain.Producer createDiffRequestProducer(@NotNull AbstractFilePatchInProgress.PatchChange change) { AbstractFilePatchInProgress patchInProgress = change.getPatchInProgress(); DiffRequestProducer delegate; if (!patchInProgress.baseExistsOrAdded()) { delegate = createBaseNotFoundErrorRequest(patchInProgress); } else { delegate = patchInProgress.getDiffRequestProducers(myProject, myReader); } return new MyProducerWrapper(delegate, change); } } @NotNull private static DiffRequestProducer createBaseNotFoundErrorRequest(@NotNull final AbstractFilePatchInProgress patchInProgress) { final String beforePath = patchInProgress.getPatch().getBeforeName(); final String afterPath = patchInProgress.getPatch().getAfterName(); return new DiffRequestProducer() { @NotNull @Override public String getName() { final File ioCurrentBase = patchInProgress.getIoCurrentBase(); return ioCurrentBase == null ? patchInProgress.getCurrentPath() : ioCurrentBase.getPath(); } @NotNull @Override public DiffRequest process(@NotNull UserDataHolder context, @NotNull ProgressIndicator indicator) throws DiffRequestProducerException, ProcessCanceledException { throw new DiffRequestProducerException( VcsBundle.message("changes.error.cannot.find.base.for.path", beforePath != null ? beforePath : afterPath)); } }; } private static final class MyProducerWrapper implements ChangeDiffRequestChain.Producer { private final DiffRequestProducer myProducer; private final Change myChange; private MyProducerWrapper(@NotNull DiffRequestProducer producer, @NotNull Change change) { myChange = change; myProducer = producer; } @NotNull @Override public String getName() { return myProducer.getName(); } @NotNull @Override public DiffRequest process(@NotNull UserDataHolder context, @NotNull ProgressIndicator indicator) throws DiffRequestProducerException { return myProducer.process(context, indicator); } @NotNull @Override public FilePath getFilePath() { return ChangesUtil.getFilePath(myChange); } @NotNull @Override public FileStatus getFileStatus() { return myChange.getFileStatus(); } } private class MyChangeComparator implements Comparator<AbstractFilePatchInProgress.PatchChange> { @Override public int compare(AbstractFilePatchInProgress.PatchChange o1, AbstractFilePatchInProgress.PatchChange o2) { if (PropertiesComponent.getInstance(myProject).isTrueValue("ChangesBrowser.SHOW_FLATTEN")) { return o1.getPatchInProgress().getIoCurrentBase().getName().compareTo(o2.getPatchInProgress().getIoCurrentBase().getName()); } return FileUtil.compareFiles(o1.getPatchInProgress().getIoCurrentBase(), o2.getPatchInProgress().getIoCurrentBase()); } } }
package io.github.deltajulio.pantrybank.ui.adapter; import android.content.Context; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.Query; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import io.github.deltajulio.pantrybank.FoodKey; import io.github.deltajulio.pantrybank.R; import io.github.deltajulio.pantrybank.data.Category; import io.github.deltajulio.pantrybank.data.FoodItem; /** * Base class for our adapters. */ public abstract class BaseRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final String TAG = BaseRecyclerAdapter.class.getSimpleName(); // Firebase objects private Query categoriesRef; private Query itemsRef; private ChildEventListener categoryListener; private ChildEventListener itemListener; // Stored copy of our categories, used to sort data by category name private HashMap<String, Category> allCategories; // Categories that are VISIBLE. (has corresponding FoodItems that are also visible) protected HashMap<String, Category> visibleCategories; // List of food items, to be used by the adapter protected TreeMap<FoodKey, FoodItem> sortedFood; // Category vars private static final int categoryResourceId = R.layout.category; protected static final int CATEGORY_TYPE = 2; protected static final int FOOD_TYPE = 1; private final Context context; protected BaseRecyclerAdapter(Query categoriesRef, Query itemsRef, Context context) { this.categoriesRef = categoriesRef; this.itemsRef = itemsRef; this.context = context; allCategories = new HashMap<>(); visibleCategories = new HashMap<>(); sortedFood = new TreeMap<>(); AddListeners(); } protected void AddListeners() { RemoveListeners(); // Monitor changes to allCategories categoryListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { // create Category from data snapshot Category category = dataSnapshot.getValue(Category.class); // add new category to containers allCategories.put(category.getCategoryId(), category); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { // create Category from data snapshot Category category = dataSnapshot.getValue(Category.class); // update stored version of category allCategories.put(category.getCategoryId(), category); } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { // create Category from data snapshot Category category = dataSnapshot.getValue(Category.class); // remove category from container allCategories.remove(category.getCategoryId()); visibleCategories.remove(category.getCategoryId()); } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { // Intentionally left blank } @Override public void onCancelled(DatabaseError databaseError) { Log.e(TAG, databaseError.toString()); } }; categoriesRef.addChildEventListener(categoryListener); // Monitor changes to food items itemListener = new ChildEventListener() { /** * Searches for the category name, given the provided ID. * * @param categoryId The ID of the category being searched for. * @return First returns TRUE if a match was found, with second being the name of the match. * First returns FALSE if no match was found, with second being null. */ private Pair<Boolean, String> GetCategoryName(String categoryId) { Category category = allCategories.get(categoryId); if (category != null) { return Pair.create(true, category.getName()); } return Pair.create(false, null); } @Override public void onChildAdded(final DataSnapshot dataSnapshot, final String s) { // create FoodItem from data snapshot FoodItem item = dataSnapshot.getValue(FoodItem.class); // find category name Pair<Boolean, String> result = GetCategoryName(item.getCategoryId()); if (!result.first) { // category was not found, delay (wait for database to finish syncing) Log.v(TAG, "itemListener:onChildAdded: category was not found. Retrying!"); new Handler().postDelayed(new Runnable() { @Override public void run() { onChildAdded(dataSnapshot, s); } }, 100); return; } // create FoodKey FoodKey foodkey = new FoodKey(result.second, item.getName()); if (!ShouldBeDisplayed(item)) { // Remove old copy sortedFood.remove(foodkey); } else { // add to container sortedFood.put(foodkey, item); } UpdateCategoryVisibility(item.getCategoryId()); notifyDataSetChanged(); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { // Create FoodItem from snapshot FoodItem item = dataSnapshot.getValue(FoodItem.class); // check if old key needs to be replaced for (FoodItem itemItr : sortedFood.values()) { if (itemItr.getFoodId().equals(item.getFoodId())) { // if category/name has been changed, replace key if (!itemItr.getCategoryId().equals(item.getCategoryId()) || !itemItr.getName().equals(item.getName())) { // Remove item from container Pair<Boolean, String> result = GetCategoryName(itemItr.getCategoryId()); if (!result.first) { throw null; } sortedFood.remove(new FoodKey(result.second, itemItr.getName())); } break; } } if (!ShouldBeDisplayed(item)) { // Remove updated item Pair<Boolean, String> result = GetCategoryName(item.getCategoryId()); if (!result.first) { throw null; } sortedFood.remove(new FoodKey(result.second, item.getName())); UpdateCategoryVisibility(item.getCategoryId()); notifyDataSetChanged(); return; } // Find Category name Pair<Boolean, String> result = GetCategoryName(item.getCategoryId()); if (result.first) { // Update value in container sortedFood.put(new FoodKey(result.second, item.getName()), item); } else { // Category was not found. Critical error. Log.e(TAG, "itemListener:onChildChanged: category was not found. Data will NOT be updated!"); } UpdateCategoryVisibility(item.getCategoryId()); notifyDataSetChanged(); } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { // Create FoodItem from snapshot FoodItem item = dataSnapshot.getValue(FoodItem.class); // Remove from container sortedFood.remove(new FoodKey(null, item.getName())); UpdateCategoryVisibility(item.getCategoryId()); notifyDataSetChanged(); } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { // Intentionally left blank } @Override public void onCancelled(DatabaseError databaseError) { Log.e(TAG, databaseError.toString()); } }; itemsRef.addChildEventListener(itemListener); } /** * Called when the containing fragment is ending its lifecycle. At this point we clean up our * data event listeners. */ public void RemoveListeners() { if (categoryListener != null) { categoriesRef.removeEventListener(categoryListener); categoryListener = null; } if (itemListener != null) { itemsRef.removeEventListener(itemListener); itemListener = null; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == CATEGORY_TYPE) { final View view = LayoutInflater.from(context).inflate(categoryResourceId, parent, false); return new CategoryHolder(view); } else { // This should never be reachable code, inherited classes should only call this function // if a category header should be made. throw null; } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) throws NullPointerException { PositionResult result = GetObjectAtPosition(position); ((CategoryHolder)holder).title.setText(result.category.getName()); } @Override public int getItemViewType(int position) { if (IsCategoryPosition(visibleCategories, sortedFood, position)) { return CATEGORY_TYPE; } else { return FOOD_TYPE; } } @Override public int getItemCount() { return sortedFood.size() + visibleCategories.size(); } /** * Called from ChildEventListener itemListener, this function determines whether the provided * FoodItem should be displayed in the RecyclerView. * * @param item FoodItem to be evaluated. * @return Return TRUE if FoodItem should be displayed in Recycler view, FALSE if not. */ protected abstract boolean ShouldBeDisplayed(FoodItem item); /** * Called from ChildEventListeners. This function determines whether the Category attached to the * provided ID should be displayed in the RecyclereView. * * @param categoryId CategoryId to be evaluated. * @throws NullPointerException In the event that no such category exists, throw a NPE. This would * be a fatal error. */ protected final void UpdateCategoryVisibility(String categoryId) throws NullPointerException { Category category = allCategories.get(categoryId); for (FoodItem foodItem : sortedFood.values()) { if (foodItem.getCategoryId().equals(categoryId)) { visibleCategories.put(categoryId, category); return; } } visibleCategories.remove(categoryId); } public static final boolean IsCategoryPosition(Map<String, Category> categories, TreeMap<FoodKey, FoodItem> food, int position) { int i = 0; // iterate through categories for (String categoryKey : categories.keySet()) { String categoryId = categories.get(categoryKey).getCategoryId(); // check if position is a Category if (i == position) { return true; } // iterate through FoodItems for (FoodItem foodItem : food.values()) { // only count items under the current category if (foodItem.getCategoryId().equals(categoryId)) { i++; // check if position is a FoodItem if (i == position) { return false; } } } i++; } return false; } protected final PositionResult GetObjectAtPosition(int position) { int i = 0; // iterate through categories for (String categoryKey : visibleCategories.keySet()) { String categoryId = visibleCategories.get(categoryKey).getCategoryId(); // check if position is a Category if (i == position) { return new PositionResult(visibleCategories.get(categoryKey)); } // iterate through FoodItems for (FoodItem foodItem : sortedFood.values()) { // only count items under the current category if (foodItem.getCategoryId().equals(categoryId)) { i++; // check if position is a FoodItem if (i == position) { return new PositionResult(foodItem); } } } i++; } Log.d(TAG, String.valueOf(visibleCategories.size())); throw null; } private class CategoryHolder extends RecyclerView.ViewHolder { private static final int textResourceId = R.id.category_text; public final TextView title; private CategoryHolder(View view) { super(view); title = (TextView) view.findViewById(textResourceId); } } protected final class PositionResult { public final boolean isCategory; public final Category category; public final FoodItem foodItem; public PositionResult(Category category) { this.isCategory = true; this.category = category; this.foodItem = null; } public PositionResult(FoodItem foodItem) { this.isCategory = false; this.category = null; this.foodItem = foodItem; } } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.generation; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.CodeInsightActionHandler; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.MethodImplementor; import com.intellij.codeInsight.intention.AddAnnotationFix; import com.intellij.codeInsight.intention.AddAnnotationPsiFix; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.featureStatistics.ProductivityFeatureNames; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.FileTemplateUtil; import com.intellij.ide.fileTemplates.JavaTemplateUtil; import com.intellij.ide.util.MemberChooser; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.actionSystem.KeyboardShortcut; import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.*; import com.intellij.util.Consumer; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.*; public class OverrideImplementUtil extends OverrideImplementExploreUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.OverrideImplementUtil"); private OverrideImplementUtil() { } protected static MethodImplementor[] getImplementors() { return Extensions.getExtensions(MethodImplementor.EXTENSION_POINT_NAME); } /** * generate methods (with bodies) corresponding to given method declaration * there are maybe two method implementations for one declaration * (e.g. EJB' create() -> ejbCreate(), ejbPostCreate() ) * @param aClass context for method implementations * @param method method to override or implement * @param toCopyJavaDoc true if copy JavaDoc from method declaration * @return list of method prototypes */ @NotNull public static List<PsiMethod> overrideOrImplementMethod(PsiClass aClass, PsiMethod method, boolean toCopyJavaDoc) throws IncorrectOperationException { final PsiClass containingClass = method.getContainingClass(); LOG.assertTrue(containingClass != null); PsiSubstitutor substitutor = aClass.isInheritor(containingClass, true) ? TypeConversionUtil.getSuperClassSubstitutor(containingClass, aClass, PsiSubstitutor.EMPTY) : PsiSubstitutor.EMPTY; return overrideOrImplementMethod(aClass, method, substitutor, toCopyJavaDoc, CodeStyleSettingsManager.getSettings(aClass.getProject()).INSERT_OVERRIDE_ANNOTATION); } public static boolean isInsertOverride(PsiMethod superMethod, PsiClass targetClass) { if (!CodeStyleSettingsManager.getSettings(targetClass.getProject()).INSERT_OVERRIDE_ANNOTATION) { return false; } return canInsertOverride(superMethod, targetClass); } public static boolean canInsertOverride(PsiMethod superMethod, PsiClass targetClass) { if (superMethod.isConstructor() || superMethod.hasModifierProperty(PsiModifier.STATIC)) { return false; } if (!PsiUtil.isLanguageLevel5OrHigher(targetClass)) { return false; } if (PsiUtil.isLanguageLevel6OrHigher(targetClass)) return true; PsiClass superClass = superMethod.getContainingClass(); return superClass != null && !superClass.isInterface(); } public static List<PsiMethod> overrideOrImplementMethod(PsiClass aClass, PsiMethod method, PsiSubstitutor substitutor, boolean toCopyJavaDoc, boolean insertOverrideIfPossible) throws IncorrectOperationException { if (!method.isValid() || !substitutor.isValid()) return Collections.emptyList(); List<PsiMethod> results = new ArrayList<>(); for (final MethodImplementor implementor : getImplementors()) { final PsiMethod[] prototypes = implementor.createImplementationPrototypes(aClass, method); for (PsiMethod prototype : prototypes) { implementor.createDecorator(aClass, method, toCopyJavaDoc, insertOverrideIfPossible).consume(prototype); results.add(prototype); } } if (results.isEmpty()) { PsiMethod method1 = GenerateMembersUtil.substituteGenericMethod(method, substitutor, aClass); PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory(); PsiMethod result = (PsiMethod)factory.createClass("Dummy").add(method1); if (PsiUtil.isAnnotationMethod(result)) { PsiAnnotationMemberValue defaultValue = ((PsiAnnotationMethod)result).getDefaultValue(); if (defaultValue != null) { PsiElement defaultKeyword = defaultValue; while (!(defaultKeyword instanceof PsiKeyword) && defaultKeyword != null) { defaultKeyword = defaultKeyword.getPrevSibling(); } if (defaultKeyword == null) defaultKeyword = defaultValue; defaultValue.getParent().deleteChildRange(defaultKeyword, defaultValue); } } Consumer<PsiMethod> decorator = createDefaultDecorator(aClass, method, toCopyJavaDoc, insertOverrideIfPossible); decorator.consume(result); results.add(result); } for (Iterator<PsiMethod> iterator = results.iterator(); iterator.hasNext();) { if (aClass.findMethodBySignature(iterator.next(), false) != null) { iterator.remove(); } } return results; } public static Consumer<PsiMethod> createDefaultDecorator(final PsiClass aClass, final PsiMethod method, final boolean toCopyJavaDoc, final boolean insertOverrideIfPossible) { return result -> decorateMethod(aClass, method, toCopyJavaDoc, insertOverrideIfPossible, result); } private static PsiMethod decorateMethod(PsiClass aClass, PsiMethod method, boolean toCopyJavaDoc, boolean insertOverrideIfPossible, PsiMethod result) { PsiUtil.setModifierProperty(result, PsiModifier.ABSTRACT, aClass.isInterface() && method.hasModifierProperty(PsiModifier.ABSTRACT)); PsiUtil.setModifierProperty(result, PsiModifier.NATIVE, false); if (!toCopyJavaDoc){ deleteDocComment(result); } //method type params are not allowed when overriding from raw type final PsiTypeParameterList list = result.getTypeParameterList(); if (list != null) { final PsiClass containingClass = method.getContainingClass(); if (containingClass != null) { for (PsiClassType classType : aClass.getSuperTypes()) { if (InheritanceUtil.isInheritorOrSelf(PsiUtil.resolveClassInType(classType), containingClass, true) && classType.isRaw()) { list.replace(JavaPsiFacade.getElementFactory(aClass.getProject()).createTypeParameterList()); break; } } } } annotateOnOverrideImplement(result, aClass, method, insertOverrideIfPossible); if (CodeStyleSettingsManager.getSettings(aClass.getProject()).REPEAT_SYNCHRONIZED && method.hasModifierProperty(PsiModifier.SYNCHRONIZED)) { result.getModifierList().setModifierProperty(PsiModifier.SYNCHRONIZED, true); } final PsiCodeBlock body = JavaPsiFacade.getInstance(method.getProject()).getElementFactory().createCodeBlockFromText("{}", null); PsiCodeBlock oldBody = result.getBody(); if (oldBody != null) { oldBody.replace(body); } else { result.add(body); } setupMethodBody(result, method, aClass); // probably, it's better to reformat the whole method - it can go from other style sources final Project project = method.getProject(); CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); CommonCodeStyleSettings javaSettings = CodeStyleSettingsManager.getSettings(project).getCommonSettings(JavaLanguage.INSTANCE); boolean keepBreaks = javaSettings.KEEP_LINE_BREAKS; javaSettings.KEEP_LINE_BREAKS = false; result = (PsiMethod)JavaCodeStyleManager.getInstance(project).shortenClassReferences(result); result = (PsiMethod)codeStyleManager.reformat(result); javaSettings.KEEP_LINE_BREAKS = keepBreaks; return result; } public static void deleteDocComment(PsiMethod result) { PsiDocComment comment = result.getDocComment(); if (comment != null){ comment.delete(); } } public static void annotateOnOverrideImplement(PsiMethod method, PsiClass targetClass, PsiMethod overridden) { annotateOnOverrideImplement(method, targetClass, overridden, CodeStyleSettingsManager.getSettings(method.getProject()).INSERT_OVERRIDE_ANNOTATION); } public static void annotateOnOverrideImplement(PsiMethod method, PsiClass targetClass, PsiMethod overridden, boolean insertOverride) { if (insertOverride && canInsertOverride(overridden, targetClass)) { final String overrideAnnotationName = Override.class.getName(); if (!AnnotationUtil.isAnnotated(method, overrideAnnotationName, false, true)) { AddAnnotationPsiFix.addPhysicalAnnotation(overrideAnnotationName, PsiNameValuePair.EMPTY_ARRAY, method.getModifierList()); } } final Module module = ModuleUtilCore.findModuleForPsiElement(targetClass); final GlobalSearchScope moduleScope = module != null ? GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) : null; final Project project = targetClass.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); for (OverrideImplementsAnnotationsHandler each : Extensions.getExtensions(OverrideImplementsAnnotationsHandler.EP_NAME)) { for (String annotation : each.getAnnotations(project)) { if (moduleScope != null && facade.findClass(annotation, moduleScope) == null) continue; if (AnnotationUtil.isAnnotated(overridden, annotation, false, false) && !AnnotationUtil.isAnnotated(method, annotation, false, false)) { PsiAnnotation psiAnnotation = AnnotationUtil.findAnnotation(overridden, annotation); if (psiAnnotation != null && AnnotationUtil.isInferredAnnotation(psiAnnotation)) { continue; } AddAnnotationPsiFix.removePhysicalAnnotations(method, each.annotationsToRemove(project, annotation)); AddAnnotationPsiFix.addPhysicalAnnotation(annotation, PsiNameValuePair.EMPTY_ARRAY, method.getModifierList()); } } } } public static void annotate(@NotNull PsiMethod result, String fqn, String... annosToRemove) throws IncorrectOperationException { Project project = result.getProject(); AddAnnotationFix fix = new AddAnnotationFix(fqn, result, annosToRemove); if (fix.isAvailable(project, null, result.getContainingFile())) { fix.invoke(project, null, result.getContainingFile()); } } @NotNull public static List<PsiGenerationInfo<PsiMethod>> overrideOrImplementMethods(PsiClass aClass, Collection<PsiMethodMember> candidates, boolean toCopyJavaDoc, boolean toInsertAtOverride) throws IncorrectOperationException { List<CandidateInfo> candidateInfos = ContainerUtil.map2List(candidates, s -> new CandidateInfo(s.getElement(), s.getSubstitutor())); final List<PsiMethod> methods = overrideOrImplementMethodCandidates(aClass, candidateInfos, toCopyJavaDoc, toInsertAtOverride); return convert2GenerationInfos(methods); } @NotNull public static List<PsiMethod> overrideOrImplementMethodCandidates(PsiClass aClass, Collection<CandidateInfo> candidates, boolean toCopyJavaDoc, boolean insertOverrideWherePossible) throws IncorrectOperationException { List<PsiMethod> result = new ArrayList<>(); for (CandidateInfo candidateInfo : candidates) { result.addAll(overrideOrImplementMethod(aClass, (PsiMethod)candidateInfo.getElement(), candidateInfo.getSubstitutor(), toCopyJavaDoc, insertOverrideWherePossible)); } return result; } public static List<PsiGenerationInfo<PsiMethod>> convert2GenerationInfos(final Collection<PsiMethod> methods) { return ContainerUtil.map2List(methods, s -> createGenerationInfo(s)); } public static PsiGenerationInfo<PsiMethod> createGenerationInfo(PsiMethod s) { return createGenerationInfo(s, true); } public static PsiGenerationInfo<PsiMethod> createGenerationInfo(PsiMethod s, boolean mergeIfExists) { for (MethodImplementor implementor : getImplementors()) { final GenerationInfo info = implementor.createGenerationInfo(s, mergeIfExists); if (info instanceof PsiGenerationInfo) { @SuppressWarnings({"unchecked"}) final PsiGenerationInfo<PsiMethod> psiGenerationInfo = (PsiGenerationInfo<PsiMethod>)info; return psiGenerationInfo; } } return new PsiGenerationInfo<>(s); } @NotNull public static String callSuper(PsiMethod superMethod, PsiMethod overriding) { @NonNls StringBuilder buffer = new StringBuilder(); if (!superMethod.isConstructor() && !PsiType.VOID.equals(superMethod.getReturnType())) { buffer.append("return "); } buffer.append("super"); PsiParameter[] parameters = overriding.getParameterList().getParameters(); if (!superMethod.isConstructor()) { buffer.append("."); buffer.append(superMethod.getName()); } buffer.append("("); for (int i = 0; i < parameters.length; i++) { String name = parameters[i].getName(); if (i > 0) buffer.append(","); buffer.append(name); } buffer.append(")"); return buffer.toString(); } public static void setupMethodBody(PsiMethod result, PsiMethod originalMethod, PsiClass targetClass) throws IncorrectOperationException { boolean isAbstract = originalMethod.hasModifierProperty(PsiModifier.ABSTRACT) || originalMethod.hasModifierProperty(PsiModifier.DEFAULT); String templateName = isAbstract ? JavaTemplateUtil.TEMPLATE_IMPLEMENTED_METHOD_BODY : JavaTemplateUtil.TEMPLATE_OVERRIDDEN_METHOD_BODY; FileTemplate template = FileTemplateManager.getInstance(originalMethod.getProject()).getCodeTemplate(templateName); setupMethodBody(result, originalMethod, targetClass, template); } public static void setupMethodBody(final PsiMethod result, final PsiMethod originalMethod, final PsiClass targetClass, final FileTemplate template) throws IncorrectOperationException { if (targetClass.isInterface()) { if (isImplementInterfaceInJava8Interface(targetClass) || originalMethod.hasModifierProperty(PsiModifier.DEFAULT)) { PsiUtil.setModifierProperty(result, PsiModifier.DEFAULT, true); } else { final PsiCodeBlock body = result.getBody(); if (body != null) body.delete(); } } FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(template.getExtension()); PsiType returnType = result.getReturnType(); if (returnType == null) { returnType = PsiType.VOID; } Properties properties = FileTemplateManager.getInstance(targetClass.getProject()).getDefaultProperties(); properties.setProperty(FileTemplate.ATTRIBUTE_RETURN_TYPE, returnType.getPresentableText()); properties.setProperty(FileTemplate.ATTRIBUTE_DEFAULT_RETURN_VALUE, PsiTypesUtil.getDefaultValueOfType(returnType)); properties.setProperty(FileTemplate.ATTRIBUTE_CALL_SUPER, callSuper(originalMethod, result)); JavaTemplateUtil.setClassAndMethodNameProperties(properties, targetClass, result); JVMElementFactory factory = JVMElementFactories.getFactory(targetClass.getLanguage(), originalMethod.getProject()); if (factory == null) factory = JavaPsiFacade.getInstance(originalMethod.getProject()).getElementFactory(); @NonNls String methodText; try { methodText = "void foo () {\n" + template.getText(properties) + "\n}"; methodText = FileTemplateUtil.indent(methodText, result.getProject(), fileType); } catch (Exception e) { throw new IncorrectOperationException("Failed to parse file template", (Throwable)e); } if (methodText != null) { PsiMethod m; try { m = factory.createMethodFromText(methodText, originalMethod); } catch (IncorrectOperationException e) { ApplicationManager.getApplication().invokeLater( () -> Messages.showErrorDialog(CodeInsightBundle.message("override.implement.broken.file.template.message"), CodeInsightBundle.message("override.implement.broken.file.template.title"))); return; } PsiCodeBlock oldBody = result.getBody(); if (oldBody != null) { oldBody.replace(m.getBody()); } } } private static boolean isImplementInterfaceInJava8Interface(PsiClass targetClass) { if (!PsiUtil.isLanguageLevel8OrHigher(targetClass)){ return false; } String commandName = CommandProcessor.getInstance().getCurrentCommandName(); return commandName != null && StringUtil.containsIgnoreCase(commandName, "implement"); } public static void chooseAndOverrideMethods(Project project, Editor editor, PsiClass aClass){ FeatureUsageTracker.getInstance().triggerFeatureUsed(ProductivityFeatureNames.CODEASSISTS_OVERRIDE_IMPLEMENT); chooseAndOverrideOrImplementMethods(project, editor, aClass, false); } public static void chooseAndImplementMethods(Project project, Editor editor, PsiClass aClass){ FeatureUsageTracker.getInstance().triggerFeatureUsed(ProductivityFeatureNames.CODEASSISTS_OVERRIDE_IMPLEMENT); chooseAndOverrideOrImplementMethods(project, editor, aClass, true); } public static void chooseAndOverrideOrImplementMethods(final Project project, final Editor editor, final PsiClass aClass, final boolean toImplement) { LOG.assertTrue(aClass.isValid()); ApplicationManager.getApplication().assertReadAccessAllowed(); Collection<CandidateInfo> candidates = getMethodsToOverrideImplement(aClass, toImplement); Collection<CandidateInfo> secondary = toImplement || aClass.isInterface() ? ContainerUtil.<CandidateInfo>newArrayList() : getMethodsToOverrideImplement(aClass, true); final MemberChooser<PsiMethodMember> chooser = showOverrideImplementChooser(editor, aClass, toImplement, candidates, secondary); if (chooser == null) return; final List<PsiMethodMember> selectedElements = chooser.getSelectedElements(); if (selectedElements == null || selectedElements.isEmpty()) return; LOG.assertTrue(aClass.isValid()); new WriteCommandAction(project, aClass.getContainingFile()) { @Override protected void run(@NotNull final Result result) throws Throwable { overrideOrImplementMethodsInRightPlace(editor, aClass, selectedElements, chooser.isCopyJavadoc(), chooser.isInsertOverrideAnnotation()); } }.execute(); } /** * @param candidates, secondary should allow modifications */ @Nullable public static MemberChooser<PsiMethodMember> showOverrideImplementChooser(Editor editor, final PsiElement aClass, final boolean toImplement, final Collection<CandidateInfo> candidates, Collection<CandidateInfo> secondary) { if (toImplement) { for (Iterator<CandidateInfo> iterator = candidates.iterator(); iterator.hasNext(); ) { CandidateInfo candidate = iterator.next(); PsiElement element = candidate.getElement(); if (element instanceof PsiMethod && ((PsiMethod)element).hasModifierProperty(PsiModifier.DEFAULT)) { iterator.remove(); secondary.add(candidate); } } } final JavaOverrideImplementMemberChooser chooser = JavaOverrideImplementMemberChooser.create(aClass, toImplement, candidates, secondary); if (chooser == null) { return null; } Project project = aClass.getProject(); registerHandlerForComplementaryAction(project, editor, aClass, toImplement, chooser); if (ApplicationManager.getApplication().isUnitTestMode()) { return chooser; } chooser.show(); if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE) return null; return chooser; } private static void registerHandlerForComplementaryAction(final Project project, final Editor editor, final PsiElement aClass, final boolean toImplement, final MemberChooser<PsiMethodMember> chooser) { final JComponent preferredFocusedComponent = chooser.getPreferredFocusedComponent(); final Keymap keymap = KeymapManager.getInstance().getActiveKeymap(); @NonNls final String s = toImplement ? "OverrideMethods" : "ImplementMethods"; final Shortcut[] shortcuts = keymap.getShortcuts(s); if (shortcuts.length > 0 && shortcuts[0] instanceof KeyboardShortcut) { preferredFocusedComponent.getInputMap().put( ((KeyboardShortcut)shortcuts[0]).getFirstKeyStroke(), s ); preferredFocusedComponent.getActionMap().put( s, new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { chooser.close(DialogWrapper.CANCEL_EXIT_CODE); // invoke later in order to close previous modal dialog ApplicationManager.getApplication().invokeLater(() -> { final CodeInsightActionHandler handler = toImplement ? new OverrideMethodsHandler(): new ImplementMethodsHandler(); handler.invoke(project, editor, aClass.getContainingFile()); }); } } ); } } public static void overrideOrImplementMethodsInRightPlace(Editor editor, PsiClass aClass, Collection<PsiMethodMember> candidates, boolean copyJavadoc, boolean insertOverrideWherePossible) { try { int offset = editor.getCaretModel().getOffset(); PsiElement brace = aClass.getLBrace(); if (brace == null) { PsiClass psiClass = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory().createClass("X"); brace = aClass.addRangeAfter(psiClass.getLBrace(), psiClass.getRBrace(), aClass.getLastChild()); LOG.assertTrue(brace != null, aClass.getLastChild()); } int lbraceOffset = brace.getTextOffset(); List<PsiGenerationInfo<PsiMethod>> resultMembers; if (offset <= lbraceOffset || aClass.isEnum()) { resultMembers = new ArrayList<>(); for (PsiMethodMember candidate : candidates) { Collection<PsiMethod> prototypes = overrideOrImplementMethod(aClass, candidate.getElement(), candidate.getSubstitutor(), copyJavadoc, insertOverrideWherePossible); List<PsiGenerationInfo<PsiMethod>> infos = convert2GenerationInfos(prototypes); for (PsiGenerationInfo<PsiMethod> info : infos) { PsiElement anchor = getDefaultAnchorToOverrideOrImplement(aClass, candidate.getElement(), candidate.getSubstitutor()); info.insert(aClass, anchor, true); resultMembers.add(info); } } } else { List<PsiGenerationInfo<PsiMethod>> prototypes = overrideOrImplementMethods(aClass, candidates, copyJavadoc, insertOverrideWherePossible); resultMembers = GenerateMembersUtil.insertMembersAtOffset(aClass.getContainingFile(), offset, prototypes); } if (!resultMembers.isEmpty()) { resultMembers.get(0).positionCaret(editor, true); } } catch (IncorrectOperationException e) { LOG.error(e); } } @Nullable public static PsiElement getDefaultAnchorToOverrideOrImplement(PsiClass aClass, PsiMethod baseMethod, PsiSubstitutor substitutor){ PsiMethod prevBaseMethod = PsiTreeUtil.getPrevSiblingOfType(baseMethod, PsiMethod.class); while(prevBaseMethod != null) { String name = prevBaseMethod.isConstructor() ? aClass.getName() : prevBaseMethod.getName(); //Happens when aClass instanceof PsiAnonymousClass if (name != null) { MethodSignature signature = MethodSignatureUtil.createMethodSignature(name, prevBaseMethod.getParameterList(), prevBaseMethod.getTypeParameterList(), substitutor, prevBaseMethod.isConstructor()); PsiMethod prevMethod = MethodSignatureUtil.findMethodBySignature(aClass, signature, false); if (prevMethod != null && prevMethod.isPhysical()){ return prevMethod.getNextSibling(); } } prevBaseMethod = PsiTreeUtil.getPrevSiblingOfType(prevBaseMethod, PsiMethod.class); } PsiMethod nextBaseMethod = PsiTreeUtil.getNextSiblingOfType(baseMethod, PsiMethod.class); while(nextBaseMethod != null) { String name = nextBaseMethod.isConstructor() ? aClass.getName() : nextBaseMethod.getName(); if (name != null) { MethodSignature signature = MethodSignatureUtil.createMethodSignature(name, nextBaseMethod.getParameterList(), nextBaseMethod.getTypeParameterList(), substitutor, nextBaseMethod.isConstructor()); PsiMethod nextMethod = MethodSignatureUtil.findMethodBySignature(aClass, signature, false); if (nextMethod != null && nextMethod.isPhysical()){ return nextMethod; } } nextBaseMethod = PsiTreeUtil.getNextSiblingOfType(nextBaseMethod, PsiMethod.class); } return null; } public static List<PsiGenerationInfo<PsiMethod>> overrideOrImplement(PsiClass psiClass, @NotNull PsiMethod baseMethod) throws IncorrectOperationException { FileEditorManager fileEditorManager = FileEditorManager.getInstance(baseMethod.getProject()); List<PsiGenerationInfo<PsiMethod>> results = new ArrayList<>(); try { List<PsiGenerationInfo<PsiMethod>> prototypes = convert2GenerationInfos(overrideOrImplementMethod(psiClass, baseMethod, false)); if (prototypes.isEmpty()) return null; PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(baseMethod.getContainingClass(), psiClass, PsiSubstitutor.EMPTY); PsiElement anchor = getDefaultAnchorToOverrideOrImplement(psiClass, baseMethod, substitutor); results = GenerateMembersUtil.insertMembersBeforeAnchor(psiClass, anchor, prototypes); return results; } finally { PsiFile psiFile = psiClass.getContainingFile(); Editor editor = fileEditorManager.openTextEditor(new OpenFileDescriptor(psiFile.getProject(), psiFile.getVirtualFile()), true); if (editor != null && !results.isEmpty()) { results.get(0).positionCaret(editor, true); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); } } } @Nullable public static PsiClass getContextClass(Project project, Editor editor, PsiFile file, boolean allowInterface) { int offset = editor.getCaretModel().getOffset(); PsiElement element = file.findElementAt(offset); do { element = PsiTreeUtil.getParentOfType(element, PsiClass.class); } while (element instanceof PsiTypeParameter); final PsiClass aClass = (PsiClass)element; if (aClass instanceof PsiSyntheticClass) return null; return aClass == null || !allowInterface && aClass.isInterface() ? null : aClass; } public static void overrideOrImplementMethodsInRightPlace(Editor editor1, PsiClass aClass, Collection<PsiMethodMember> members, boolean copyJavadoc) { boolean insert = CodeStyleSettingsManager.getSettings(aClass.getProject()).INSERT_OVERRIDE_ANNOTATION; overrideOrImplementMethodsInRightPlace(editor1, aClass, members, copyJavadoc, insert); } public static List<PsiMethod> overrideOrImplementMethodCandidates(PsiClass aClass, Collection<CandidateInfo> candidatesToImplement, boolean copyJavadoc) throws IncorrectOperationException { boolean insert = CodeStyleSettingsManager.getSettings(aClass.getProject()).INSERT_OVERRIDE_ANNOTATION; return overrideOrImplementMethodCandidates(aClass, candidatesToImplement, copyJavadoc, insert); } }
/** * 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.hive.ql.exec; import java.util.Arrays; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.serde2.lazy.LazyDouble; import org.apache.hadoop.hive.serde2.objectinspector.ListObjectsEqualComparer; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; public class KeyWrapperFactory { public KeyWrapperFactory(ExprNodeEvaluator[] keyFields, ObjectInspector[] keyObjectInspectors, ObjectInspector[] currentKeyObjectInspectors) { this.keyFields = keyFields; this.keyObjectInspectors = keyObjectInspectors; this.currentKeyObjectInspectors = currentKeyObjectInspectors; } public KeyWrapper getKeyWrapper() { if (keyFields.length == 1 && TypeInfoUtils.getTypeInfoFromObjectInspector(keyObjectInspectors[0]).equals( TypeInfoFactory.stringTypeInfo)) { assert(TypeInfoUtils.getTypeInfoFromObjectInspector(currentKeyObjectInspectors[0]).equals( TypeInfoFactory.stringTypeInfo)); soi_new = (StringObjectInspector) keyObjectInspectors[0]; soi_copy = (StringObjectInspector) currentKeyObjectInspectors[0]; return new TextKeyWrapper(false); } else { currentStructEqualComparer = new ListObjectsEqualComparer(currentKeyObjectInspectors, currentKeyObjectInspectors); newKeyStructEqualComparer = new ListObjectsEqualComparer(currentKeyObjectInspectors, keyObjectInspectors); return new ListKeyWrapper(false); } } transient ExprNodeEvaluator[] keyFields; transient ObjectInspector[] keyObjectInspectors; transient ObjectInspector[] currentKeyObjectInspectors; transient ListObjectsEqualComparer currentStructEqualComparer; transient ListObjectsEqualComparer newKeyStructEqualComparer; class ListKeyWrapper extends KeyWrapper { int hashcode; Object[] keys; // decide whether this is already in hashmap (keys in hashmap are deepcopied // version, and we need to use 'currentKeyObjectInspector'). ListObjectsEqualComparer equalComparer; public ListKeyWrapper(boolean isCopy) { this(-1, new Object[keyFields.length], isCopy); } private ListKeyWrapper(int hashcode, Object[] copiedKeys, boolean isCopy) { super(); this.hashcode = hashcode; keys = copiedKeys; setEqualComparer(isCopy); } private void setEqualComparer(boolean copy) { if (!copy) { equalComparer = newKeyStructEqualComparer; } else { equalComparer = currentStructEqualComparer; } } @Override public int hashCode() { return hashcode; } @Override public boolean equals(Object obj) { Object[] copied_in_hashmap = ((ListKeyWrapper) obj).keys; return equalComparer.areEqual(copied_in_hashmap, keys); } @Override public void setHashKey() { hashcode = ObjectInspectorUtils.writableArrayHashCode(keys); } @Override public void getNewKey(Object row, ObjectInspector rowInspector) throws HiveException { // Compute the keys for (int i = 0; i < keyFields.length; i++) { keys[i] = keyFields[i].evaluate(row); } } @Override public KeyWrapper copyKey() { Object[] newDefaultKeys = deepCopyElements(keys, keyObjectInspectors, ObjectInspectorCopyOption.WRITABLE); return new ListKeyWrapper(hashcode, newDefaultKeys, true); } @Override public void copyKey(KeyWrapper oldWrapper) { ListKeyWrapper listWrapper = (ListKeyWrapper) oldWrapper; hashcode = listWrapper.hashcode; equalComparer = currentStructEqualComparer; deepCopyElements(listWrapper.keys, keyObjectInspectors, keys, ObjectInspectorCopyOption.WRITABLE); } @Override public Object[] getKeyArray() { return keys; } private Object[] deepCopyElements(Object[] keys, ObjectInspector[] keyObjectInspectors, ObjectInspectorCopyOption copyOption) { Object[] result = new Object[keys.length]; deepCopyElements(keys, keyObjectInspectors, result, copyOption); return result; } private void deepCopyElements(Object[] keys, ObjectInspector[] keyObjectInspectors, Object[] result, ObjectInspectorCopyOption copyOption) { for (int i = 0; i < keys.length; i++) { result[i] = ObjectInspectorUtils.copyToStandardObject(keys[i], keyObjectInspectors[i], copyOption); } } } transient Object[] singleEleArray = new Object[1]; transient StringObjectInspector soi_new, soi_copy; class TextKeyWrapper extends KeyWrapper { int hashcode; Object key; boolean isCopy; public TextKeyWrapper(boolean isCopy) { this(-1, null, isCopy); } private TextKeyWrapper(int hashcode, Object key, boolean isCopy) { super(); this.hashcode = hashcode; this.key = key; this.isCopy = isCopy; } @Override public int hashCode() { return hashcode; } @Override public boolean equals(Object other) { Object obj = ((TextKeyWrapper) other).key; Text t1; Text t2; if (isCopy) { t1 = soi_copy.getPrimitiveWritableObject(key); t2 = soi_copy.getPrimitiveWritableObject(obj); } else { t1 = soi_new.getPrimitiveWritableObject(key); t2 = soi_copy.getPrimitiveWritableObject(obj); } if (t1 == null && t2 == null) { return true; } else if (t1 == null || t2 == null) { return false; } else { return t1.equals(t2); } } @Override public void setHashKey() { if (key == null) { hashcode = 0; } else{ hashcode = key.hashCode(); } } @Override public void getNewKey(Object row, ObjectInspector rowInspector) throws HiveException { // Compute the keys key = keyFields[0].evaluate(row); } @Override public KeyWrapper copyKey() { return new TextKeyWrapper(hashcode, ObjectInspectorUtils.copyToStandardObject(key, soi_new, ObjectInspectorCopyOption.WRITABLE), true); } @Override public void copyKey(KeyWrapper oldWrapper) { TextKeyWrapper textWrapper = (TextKeyWrapper) oldWrapper; hashcode = textWrapper.hashcode; isCopy = true; key = ObjectInspectorUtils.copyToStandardObject(textWrapper.key, soi_new, ObjectInspectorCopyOption.WRITABLE); } @Override public Object[] getKeyArray() { singleEleArray[0] = key; return singleEleArray; } } }
// The MIT License (MIT) // // Copyright (c) 2021 Timothy D. Jones // // 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 io.github.jonestimd.swing.component; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JSeparator; import javax.swing.JToolBar; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.TableRowSorter; import com.google.common.collect.Lists; import io.github.jonestimd.swing.table.DecoratedTable; import io.github.jonestimd.swing.table.TableSummary; import io.github.jonestimd.swing.table.model.ValidatedBeanListTableModel; import io.github.jonestimd.swing.window.StatusFrame; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static io.github.jonestimd.swing.ComponentFactory.*; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class ValidatedTablePanelTest { private static final String RESOURCE_GROUP = "ValidatedTablePanelTest"; private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("test-resources"); @Mock private Action saveAction; @Mock private ValidatedBeanListTableModel<TestBean> tableModel; private DecoratedTable<TestBean, ValidatedBeanListTableModel<TestBean>> table; private TestPanel testPanel; private List<TestBean> confirmedDeletes = new ArrayList<>(); @Before public void setupMocks() throws Exception { when(saveAction.getValue(Action.NAME)).thenReturn("Save"); when(saveAction.getValue(Action.ACCELERATOR_KEY)).thenReturn(KeyStroke.getKeyStroke("ctrl S")); when(saveAction.getValue(Action.MNEMONIC_KEY)).thenReturn((int) 'S'); } private void createPanel() { createPanel(RESOURCE_GROUP, tableModel); } private void createPanel(String resourceGroup, ValidatedBeanListTableModel<TestBean> model) { table = new DecoratedTable<>(model); testPanel = new TestPanel(table, resourceGroup); } @Test @SuppressWarnings("unchecked") public void addsTableModelSummaries() throws Exception { ValidatedBeanListTableModel model = mock(ValidatedBeanListTableModel.class, withSettings().extraInterfaces(TableSummary.class)); createPanel(RESOURCE_GROUP, model); final JFrame frame = new JFrame(); SwingUtilities.invokeAndWait(() -> { frame.setContentPane(testPanel); testPanel.addNotify(); }); verify((TableSummary) model).getSummaryProperties(); } @Test public void doesNotAddMenuIfMissingResource() throws Exception { createPanel("ValidatedTablePanelTest.noMenu", tableModel); final JFrame frame = new JFrame(); SwingUtilities.invokeAndWait(() -> { frame.setContentPane(testPanel); testPanel.addNotify(); }); assertThat(frame.getJMenuBar().getMenuCount()).isEqualTo(1); JToolBar toolBar = (JToolBar) frame.getJMenuBar().getComponent(0); assertThat(((JButton) toolBar.getComponentAtIndex(0)).getToolTipText()).isEqualTo("Add"); assertThat(((JButton) toolBar.getComponentAtIndex(1)).getToolTipText()).isEqualTo("Delete"); assertThat(((JButton) toolBar.getComponentAtIndex(2)).getToolTipText()).isEqualTo("Save (Ctrl" + ACCELERATOR_DELIMITER + "S)"); assertThat(((JButton) toolBar.getComponentAtIndex(3)).getToolTipText()).isEqualTo("Reload"); } @Test public void addsActionsToMenuAndToolbar() throws Exception { createPanel(); final JFrame frame = new JFrame(); SwingUtilities.invokeAndWait(() -> { frame.setContentPane(testPanel); testPanel.addNotify(); }); assertThat(frame.getJMenuBar().getMenuCount()).isEqualTo(3); JMenu menu = frame.getJMenuBar().getMenu(0); assertThat(menu.getText()).isEqualTo("Validated Table Panel Test"); assertThat(menu.getMnemonic()).isEqualTo('V'); assertThat(menu.getItemCount()).isEqualTo(4); checkMenuItem(menu.getItem(0), 'A', "Add"); checkMenuItem(menu.getItem(1), 'D', "Delete"); checkMenuItem(menu.getItem(2), 'S', "Save"); checkMenuItem(menu.getItem(3), 'R', "Reload"); assertThat(frame.getJMenuBar().getComponent(1)).isInstanceOf(JSeparator.class); JToolBar toolBar = (JToolBar) frame.getJMenuBar().getComponent(2); assertThat(toolBar.getComponentCount()).isEqualTo(4); assertThat(((JButton) toolBar.getComponentAtIndex(0)).getToolTipText()).isEqualTo("Add (Ctrl" + ACCELERATOR_DELIMITER + "A)"); assertThat(((JButton) toolBar.getComponentAtIndex(1)).getToolTipText()).isEqualTo("Delete (Ctrl" + ACCELERATOR_DELIMITER + "D)"); assertThat(((JButton) toolBar.getComponentAtIndex(2)).getToolTipText()).isEqualTo("Save (Ctrl" + ACCELERATOR_DELIMITER + "S)"); assertThat(((JButton) toolBar.getComponentAtIndex(3)).getToolTipText()).isEqualTo("Reload (Ctrl" + ACCELERATOR_DELIMITER + "R)"); } @Test public void getTableModel() throws Exception { createPanel(); assertThat(testPanel.getTableModel()).isSameAs(tableModel); assertThat(testPanel.getChangeBuffer()).isSameAs(tableModel); } @Test public void getRowSorter() throws Exception { createPanel(); TableRowSorter<ValidatedBeanListTableModel<TestBean>> sorter = new TableRowSorter<>(tableModel); table.setRowSorter(sorter); assertThat(testPanel.getRowSorter()).isSameAs(sorter); } @Test public void deleteEnabledForNonEmptySelection() throws Exception { createPanel(); when(tableModel.getRowCount()).thenReturn(3); JButton deleteButton = getToolBarButton(1); table.setRowSelectionInterval(1, 1); assertThat(deleteButton.isEnabled()).isTrue(); } @Test public void deleteDisabledForSelectionOfOnlyPendingDeletes() throws Exception { createPanel(); List<TestBean> beans = Lists.newArrayList(new TestBean(), new TestBean(), new TestBean()); when(tableModel.getRowCount()).thenReturn(3); when(tableModel.getBean(anyInt())).thenAnswer(invocation -> beans.get((Integer) invocation.getArguments()[0])); when(tableModel.getPendingDeletes()).thenReturn(Lists.newArrayList(beans.get(1))); JButton deleteButton = getToolBarButton(1); table.setRowSelectionInterval(1, 1); assertThat(deleteButton.isEnabled()).isFalse(); } @Test public void deleteActionPerformedWithNoRowsConfirmed() throws Exception { createPanel(); JButton deleteButton = getToolBarButton(1); deleteButton.getAction().actionPerformed(new ActionEvent(deleteButton, -1, null)); verify(tableModel, never()).queueDelete(any(TestBean.class)); } @Test public void deleteActionPerformedWithRowsConfirmed() throws Exception { createPanel(); confirmedDeletes.add(new TestBean()); when(tableModel.isChanged()).thenReturn(true); JButton deleteButton = getToolBarButton(1); deleteButton.getAction().actionPerformed(new ActionEvent(deleteButton, -1, null)); verify(tableModel).queueDelete(any(TestBean.class)); verify(saveAction).setEnabled(true); } private JButton getToolBarButton(int index) { JToolBar toolbar = new JToolBar(); testPanel.addActions(toolbar); return (JButton) toolbar.getComponentAtIndex(index); } @Test public void saveDisabledForNoPendingChanges() throws Exception { createPanel(); when(tableModel.isChanged()).thenReturn(false); ArgumentCaptor<TableModelListener> listener = ArgumentCaptor.forClass(TableModelListener.class); verify(tableModel, atLeast(2)).addTableModelListener(listener.capture()); reset(saveAction); listener.getValue().tableChanged(new TableModelEvent(tableModel, 0)); verify(saveAction).setEnabled(false); } @Test public void saveEnabledForPendingChangesAndNoErrors() throws Exception { createPanel(); when(tableModel.isChanged()).thenReturn(true); when(tableModel.isNoErrors()).thenReturn(true); ArgumentCaptor<TableModelListener> listener = ArgumentCaptor.forClass(TableModelListener.class); verify(tableModel, atLeast(2)).addTableModelListener(listener.capture()); verify(saveAction).setEnabled(false); reset(saveAction); listener.getValue().tableChanged(new TableModelEvent(tableModel, 0)); verify(saveAction).setEnabled(true); } @Test public void saveDisabledForPendingChangesAndErrors() throws Exception { createPanel(); when(tableModel.isChanged()).thenReturn(true); when(tableModel.isNoErrors()).thenReturn(false); ArgumentCaptor<TableModelListener> listener = ArgumentCaptor.forClass(TableModelListener.class); verify(tableModel, atLeast(2)).addTableModelListener(listener.capture()); reset(saveAction); listener.getValue().tableChanged(new TableModelEvent(tableModel, 0)); verify(saveAction).setEnabled(false); } @Test public void notifyUnsavedChangesIndicator() throws Exception { createPanel(); StatusFrame frame = new StatusFrame(BUNDLE, RESOURCE_GROUP); frame.setContentPane(testPanel); when(tableModel.isChanged()).thenReturn(true); ArgumentCaptor<TableModelListener> listener = ArgumentCaptor.forClass(TableModelListener.class); verify(tableModel, atLeast(2)).addTableModelListener(listener.capture()); listener.getValue().tableChanged(new TableModelEvent(tableModel, 0)); assertThat(frame.getTitle()).endsWith("*"); } @Test public void getSelectedBean() throws Exception { createPanel(); List<TestBean> beans = Lists.newArrayList(new TestBean(), new TestBean(), new TestBean()); when(tableModel.getRowCount()).thenReturn(3); when(tableModel.getRow(anyInt())).thenAnswer(invocation -> beans.get((Integer) invocation.getArguments()[0])); assertThat(testPanel.getSelectedBean()).isNull(); table.setRowSelectionInterval(1, 1); assertThat(testPanel.getSelectedBean()).isSameAs(beans.get(1)); table.setRowSelectionInterval(1, 2); assertThat(testPanel.getSelectedBean()).isSameAs(beans.get(1)); } @Test public void isSingleRowSelected() throws Exception { createPanel(); when(tableModel.getRowCount()).thenReturn(3); table.setRowSelectionInterval(1, 1); assertThat(testPanel.isSingleRowSelected()).isTrue(); table.setRowSelectionInterval(1, 2); assertThat(testPanel.isSingleRowSelected()).isFalse(); } private void checkMenuItem(JMenuItem item, char mnemonic, String text) { assertThat(item.getText()).isEqualTo(text); assertThat(item.getMnemonic()).isEqualTo(mnemonic); assertThat(item.getAccelerator()).isEqualTo(KeyStroke.getKeyStroke("ctrl " + mnemonic)); } private static class TestBean { } private class TestPanel extends ValidatedTablePanel<TestBean> { public TestPanel(DecoratedTable<TestBean, ValidatedBeanListTableModel<TestBean>> table, String resourceGroup) { super(BUNDLE, table, resourceGroup); } @Override protected Action createSaveAction() { return saveAction; } @Override protected TestBean newBean() { return null; } @Override protected List<TestBean> confirmDelete(List<TestBean> items) { return confirmedDeletes; } @Override protected List<TestBean> getTableData() { return new ArrayList<>(); } } }
/* * 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.hyracks.api.util; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; public class DotFormatBuilder { private final StringBuilder stringBuilder; private final Set<Node> nodes; private final List<Edge> edges; public DotFormatBuilder(StringValue graphName) { this.edges = new ArrayList<>(); this.nodes = new HashSet<>(); this.stringBuilder = new StringBuilder(); this.stringBuilder.append("digraph ").append(graphName).append(" {\n").append("rankdir=BT;\n"); this.stringBuilder.append("node [style=\"rounded,filled\",shape=box];\n"); } public String getDotDocument() { // print edges first for (Edge edge : edges) { stringBuilder.append(edge); } // print nodes for (Node node : nodes) { stringBuilder.append(node); } stringBuilder.append("\n}"); return stringBuilder.toString(); } // point of entry method public Node createNode(StringValue nodeId, StringValue nodeLabel) { Node node = new Node(nodeId, nodeLabel); for (Node existingNode : nodes) { if (node.equals(existingNode)) { existingNode.setNodeLabel(nodeLabel); return existingNode; } } nodes.add(node); return node; } // point of entry method public Edge createEdge(final Node source, final Node destination) { // sanity checks if any variable is null? if (source == null || destination == null || !nodes.contains(source) || !nodes.contains(destination)) { return null; } // append to edges list Edge newEdge = new Edge(source, destination); edges.add(newEdge); return newEdge; } public class Node { private final StringValue nodeId; private HashMap<String, AttributeValue> attributes = new HashMap<>(); // no instantiation private Node(StringValue nodeId, StringValue nodeLabel) { this.nodeId = nodeId; setNodeLabel(nodeLabel); } public StringValue getNodeId() { return nodeId; } public AttributeValue getNodeLabel() { return attributes.get(Attribute.LABEL); } public Node setNodeLabel(StringValue nodeLabel) { if (nodeLabel != null) { attributes.put(Attribute.LABEL, nodeLabel); } return this; } public Node setFillColor(Color color) { if (color != null) { attributes.put(Attribute.COLOR, color); } return this; } @Override public boolean equals(Object other) { if (!(other instanceof Node)) { return false; } Node otherNode = (Node) other; return nodeId.getValue().equals(otherNode.nodeId.getValue()); } @Override public int hashCode() { return nodeId.getValue().hashCode(); } @Override public String toString() { StringBuilder nodeString = new StringBuilder(); nodeString.append(nodeId).append(" ["); attributes.forEach((key, value) -> nodeString.append(key).append("=").append(value).append(",")); // remove last "," if (nodeString.charAt(nodeString.length() - 1) == ',') { nodeString.deleteCharAt(nodeString.length() - 1); } nodeString.append("];\n"); return nodeString.toString(); } } public class Edge { private final Node source; private final Node destination; private final HashMap<String, AttributeValue> attributes = new HashMap<>(); // no instantiation private Edge(Node source, Node destination) { this.source = source; this.destination = destination; } public Edge setLabel(StringValue edgeLabel) { if (edgeLabel != null) { attributes.put(Attribute.LABEL, edgeLabel); } return this; } public Edge setColor(Color color) { if (color != null) { attributes.put(Attribute.COLOR, color); } return this; } public Edge setDashed() { attributes.put(Attribute.STYLE, Style.DASHED); return this; } @Override public boolean equals(Object other) { if (!(other instanceof Edge)) { return false; } Edge otherEdge = (Edge) other; return source.equals(otherEdge.source) && destination.equals(otherEdge.destination); } @Override public int hashCode() { return source.hashCode() ^ destination.hashCode(); } @Override public String toString() { StringBuilder edgeString = new StringBuilder(); edgeString.append(source.getNodeId()).append("->").append(destination.getNodeId()).append(" ["); attributes.forEach((key, value) -> edgeString.append(key).append("=").append(value).append(",")); // remove last "," if (edgeString.charAt(edgeString.length() - 1) == ',') { edgeString.deleteCharAt(edgeString.length() - 1); } edgeString.append("];\n"); return edgeString.toString(); } } public abstract static class AttributeValue { private final String value; // no instantiation private AttributeValue(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return value; } } public static final class StringValue extends AttributeValue { // no instantiation private StringValue(String value) { super(value); } public static StringValue of(String value) { String newValue = value; if (value == null) { newValue = ""; } newValue = newValue.replace("\n", "\\n"); return new StringValue("\"" + newValue.replace("\"", "\'").trim() + "\""); } } public static final class Color extends AttributeValue { public static final Color RED = new Color("red"); public static final Color SKYBLUE = new Color("skyblue"); public static final Color BLUE = new Color("blue"); // no instantiation private Color(String color) { super(color); } } public static final class Style extends AttributeValue { public static final Style DASHED = new Style("dashed"); // no instantiation private Style(String style) { super(style); } } private static final class Attribute { private static final String COLOR = "color"; private static final String LABEL = "label"; private static final String STYLE = "style"; // no instantiation private Attribute() { } } }
/* * Copyright 2014-2015 Groupon, Inc * * Groupon licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.plugin.adyen.api; import com.google.common.base.MoreObjects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import org.joda.time.DateTime; import org.killbill.billing.account.api.Account; import org.killbill.billing.catalog.api.Currency; import org.killbill.billing.payment.api.Payment; import org.killbill.billing.payment.api.PaymentApiException; import org.killbill.billing.payment.api.PaymentMethod; import org.killbill.billing.payment.api.PaymentMethodPlugin; import org.killbill.billing.payment.api.PaymentTransaction; import org.killbill.billing.payment.api.PluginProperty; import org.killbill.billing.payment.api.TransactionType; import org.killbill.billing.payment.plugin.api.GatewayNotification; import org.killbill.billing.payment.plugin.api.HostedPaymentPageFormDescriptor; import org.killbill.billing.payment.plugin.api.PaymentMethodInfoPlugin; import org.killbill.billing.payment.plugin.api.PaymentPluginApiException; import org.killbill.billing.payment.plugin.api.PaymentPluginStatus; import org.killbill.billing.payment.plugin.api.PaymentTransactionInfoPlugin; import org.killbill.billing.plugin.adyen.client.AdyenConfigProperties; import org.killbill.billing.plugin.adyen.client.model.OrderData; import org.killbill.billing.plugin.adyen.client.model.PaymentData; import org.killbill.billing.plugin.adyen.client.model.PaymentInfo; import org.killbill.billing.plugin.adyen.client.model.PaymentModificationResponse; import org.killbill.billing.plugin.adyen.client.model.PaymentProvider; import org.killbill.billing.plugin.adyen.client.model.PaymentServiceProviderResult; import org.killbill.billing.plugin.adyen.client.model.PaymentType; import org.killbill.billing.plugin.adyen.client.model.PurchaseResult; import org.killbill.billing.plugin.adyen.client.model.RecurringType; import org.killbill.billing.plugin.adyen.client.model.SplitSettlementData; import org.killbill.billing.plugin.adyen.client.model.UserData; import org.killbill.billing.plugin.adyen.client.model.paymentinfo.CreditCard; import org.killbill.billing.plugin.adyen.client.model.paymentinfo.Elv; import org.killbill.billing.plugin.adyen.client.model.paymentinfo.OneClick; import org.killbill.billing.plugin.adyen.client.model.paymentinfo.Recurring; import org.killbill.billing.plugin.adyen.client.model.paymentinfo.SepaDirectDebit; import org.killbill.billing.plugin.adyen.client.model.paymentinfo.WebPaymentFrontend; import org.killbill.billing.plugin.adyen.client.notification.AdyenNotificationHandler; import org.killbill.billing.plugin.adyen.client.notification.AdyenNotificationService; import org.killbill.billing.plugin.adyen.client.payment.exception.SignatureGenerationException; import org.killbill.billing.plugin.adyen.client.payment.service.AdyenPaymentServiceProviderHostedPaymentPagePort; import org.killbill.billing.plugin.adyen.client.payment.service.AdyenPaymentServiceProviderPort; import org.killbill.billing.plugin.adyen.core.AdyenActivator; import org.killbill.billing.plugin.adyen.core.AdyenConfigurationHandler; import org.killbill.billing.plugin.adyen.core.AdyenHostedPaymentPageConfigurationHandler; import org.killbill.billing.plugin.adyen.core.KillbillAdyenNotificationHandler; import org.killbill.billing.plugin.adyen.dao.AdyenDao; import org.killbill.billing.plugin.adyen.dao.gen.tables.AdyenPaymentMethods; import org.killbill.billing.plugin.adyen.dao.gen.tables.AdyenResponses; import org.killbill.billing.plugin.adyen.dao.gen.tables.records.AdyenPaymentMethodsRecord; import org.killbill.billing.plugin.adyen.dao.gen.tables.records.AdyenResponsesRecord; import org.killbill.billing.plugin.api.PluginProperties; import org.killbill.billing.plugin.api.payment.PluginPaymentPluginApi; import org.killbill.billing.util.callcontext.CallContext; import org.killbill.billing.util.callcontext.TenantContext; import org.killbill.clock.Clock; import org.killbill.killbill.osgi.libs.killbill.OSGIConfigPropertiesService; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillAPI; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import org.osgi.service.log.LogService; import javax.annotation.Nullable; import javax.xml.bind.JAXBException; import java.math.BigDecimal; import java.net.URISyntaxException; import java.sql.SQLException; import java.util.Locale; import java.util.Map; import java.util.UUID; public class AdyenPaymentPluginApi extends PluginPaymentPluginApi<AdyenResponsesRecord, AdyenResponses, AdyenPaymentMethodsRecord, AdyenPaymentMethods> { public static final String PROPERTY_CUSTOMER_ID = "customerId"; public static final String PROPERTY_CUSTOMER_LOCALE = "customerLocale"; public static final String PROPERTY_EMAIL = "email"; public static final String PROPERTY_FIRST_NAME = "firstName"; public static final String PROPERTY_LAST_NAME = "lastName"; public static final String PROPERTY_IP = "ip"; public static final String PROPERTY_HOLDER_NAME = "holderName"; public static final String PROPERTY_SHIP_BEFORE_DATE = "shipBeforeDate"; public static final String PROPERTY_PAYMENT_PROVIDER_TYPE = "paymentProviderType"; public static final String PROPERTY_PAYMENT_EXTERNAL_KEY = "paymentExternalKey"; public static final String PROPERTY_SERVER_URL = "serverUrl"; public static final String PROPERTY_RESULT_URL = "resultUrl"; public static final String PROPERTY_ADDITIONAL_DATA = "additionalData"; public static final String PROPERTY_EVENT_CODE = "eventCode"; public static final String PROPERTY_EVENT_DATE = "eventDate"; public static final String PROPERTY_MERCHANT_ACCOUNT_CODE = "merchantAccountCode"; public static final String PROPERTY_MERCHANT_REFERENCE = "merchantReference"; public static final String PROPERTY_OPERATIONS = "operations"; public static final String PROPERTY_ORIGINAL_REFERENCE = "originalReference"; public static final String PROPERTY_PAYMENT_METHOD = "paymentMethod"; public static final String PROPERTY_PSP_REFERENCE = "pspReference"; public static final String PROPERTY_REASON = "reason"; public static final String PROPERTY_SUCCESS = "success"; public static final String PROPERTY_CREATE_PENDING_PAYMENT = "createPendingPayment"; public static final String PROPERTY_FROM_HPP = "fromHPP"; public static final String PROPERTY_FROM_HPP_TRANSACTION_STATUS = "fromHPPTransactionStatus"; public static final String PROPERTY_RECURRING_DETAIL_ID = "recurringDetailId"; public static final String PROPERTY_RECURRING_TYPE = "recurringType"; // 3-D Secure public static final String PROPERTY_PA_REQ = "PaReq"; public static final String PROPERTY_MD = "MD"; public static final String PROPERTY_DCC_AMOUNT_VALUE = "dccAmount"; public static final String PROPERTY_DCC_AMOUNT_CURRENCY = "dccCurrency"; public static final String PROPERTY_DCC_SIGNATURE = "dccSignature"; public static final String PROPERTY_ISSUER_URL = "issuerUrl"; public static final String PROPERTY_TERM_URL = "TermUrl"; public static final String PROPERTY_DD_HOLDER_NAME = "ddHolderName"; public static final String PROPERTY_DD_ACCOUNT_NUMBER = "ddNumber"; public static final String PROPERTY_DD_BANK_IDENTIFIER_CODE = "ddBic"; public static final String PROPERTY_DD_BANKLEITZAHL = "ddBlz"; private final AdyenConfigurationHandler adyenConfigurationHandler; private final AdyenHostedPaymentPageConfigurationHandler adyenHppConfigurationHandler; private final AdyenDao dao; private final AdyenNotificationService adyenNotificationService; public AdyenPaymentPluginApi(final AdyenConfigurationHandler adyenConfigurationHandler, final AdyenHostedPaymentPageConfigurationHandler adyenHppConfigurationHandler, final OSGIKillbillAPI killbillApi, final OSGIConfigPropertiesService osgiConfigPropertiesService, final OSGIKillbillLogService logService, final Clock clock, final AdyenDao dao) throws JAXBException { super(killbillApi, osgiConfigPropertiesService, logService, clock, dao); this.adyenConfigurationHandler = adyenConfigurationHandler; this.adyenHppConfigurationHandler = adyenHppConfigurationHandler; this.dao = dao; final KillbillAdyenNotificationHandler adyenNotificationHandler = new KillbillAdyenNotificationHandler(killbillApi, dao, clock); this.adyenNotificationService = new AdyenNotificationService(ImmutableList.<AdyenNotificationHandler>of(adyenNotificationHandler)); } private static String holderName(final String firstName, final String lastName) { return String.format("%s%s", firstName == null ? "" : firstName + " ", lastName); } @Override protected PaymentTransactionInfoPlugin buildPaymentTransactionInfoPlugin(final AdyenResponsesRecord adyenResponsesRecord) { return new AdyenPaymentTransactionInfoPlugin(adyenResponsesRecord); } @Override protected PaymentMethodPlugin buildPaymentMethodPlugin(final AdyenPaymentMethodsRecord paymentMethodsRecord) { return new AdyenPaymentMethodPlugin(paymentMethodsRecord); } @Override protected PaymentMethodInfoPlugin buildPaymentMethodInfoPlugin(final AdyenPaymentMethodsRecord paymentMethodsRecord) { return new AdyenPaymentMethodInfoPlugin(paymentMethodsRecord); } @Override protected String getPaymentMethodId(final AdyenPaymentMethodsRecord paymentMethodsRecord) { return paymentMethodsRecord.getKbPaymentMethodId(); } @Override public PaymentTransactionInfoPlugin authorizePayment(final UUID kbAccountId, final UUID kbPaymentId, final UUID kbTransactionId, final UUID kbPaymentMethodId, final BigDecimal amount, final Currency currency, final Iterable<PluginProperty> properties, final CallContext context) throws PaymentPluginApiException { return executeInitialTransaction(TransactionType.AUTHORIZE, new TransactionExecutor<PurchaseResult>() { @Override public PurchaseResult execute(final Long amount, final PaymentData paymentData, final OrderData orderData, final UserData userData, final String termUrl, final SplitSettlementData splitSettlementData) { AdyenPaymentServiceProviderPort adyenPort = adyenConfigurationHandler.getConfigurable(context.getTenantId()); return adyenPort.authorise(amount, paymentData, orderData, userData, termUrl, splitSettlementData); } }, kbAccountId, kbPaymentId, kbTransactionId, kbPaymentMethodId, amount, currency, properties, context); } @Override public PaymentTransactionInfoPlugin capturePayment(final UUID kbAccountId, final UUID kbPaymentId, final UUID kbTransactionId, final UUID kbPaymentMethodId, final BigDecimal amount, final Currency currency, final Iterable<PluginProperty> properties, final CallContext context) throws PaymentPluginApiException { return executeFollowUpTransaction(TransactionType.CAPTURE, new TransactionExecutor<PaymentModificationResponse>() { @Override public PaymentModificationResponse execute(@Nullable final Long transactionAmount, final PaymentProvider paymentProvider, final String pspReference, final SplitSettlementData splitSettlementData) { AdyenPaymentServiceProviderPort port = adyenConfigurationHandler.getConfigurable(context.getTenantId()); return port.capture(transactionAmount, paymentProvider, pspReference, splitSettlementData); } }, kbAccountId, kbPaymentId, kbTransactionId, kbPaymentMethodId, amount, currency, properties, context); } @Override public PaymentTransactionInfoPlugin purchasePayment(final UUID kbAccountId, final UUID kbPaymentId, final UUID kbTransactionId, final UUID kbPaymentMethodId, final BigDecimal amount, final Currency currency, final Iterable<PluginProperty> properties, final CallContext context) throws PaymentPluginApiException { final AdyenResponsesRecord adyenResponsesRecord; final boolean fromHPP = Boolean.valueOf(PluginProperties.findPluginPropertyValue(PROPERTY_FROM_HPP, properties)); if (!fromHPP) { // We already have a record for that payment transaction, update the response row with additional properties // (the API can be called for instance after the user is redirected back from the HPP to store the PSP reference) try { adyenResponsesRecord = dao.updateResponse(kbTransactionId, properties, context.getTenantId()); } catch (final SQLException e) { throw new PaymentPluginApiException("HPP notification came through, but we encountered a database error", e); } } else { // We are either processing a notification (see KillbillAdyenNotificationHandler) or creating a PENDING payment for HPP (see buildFormDescriptor) final DateTime utcNow = clock.getUTCNow(); try { //noinspection unchecked adyenResponsesRecord = dao.addAdyenResponse(kbAccountId, kbPaymentId, kbTransactionId, TransactionType.PURCHASE, amount, currency, PluginProperties.toMap(properties), utcNow, context.getTenantId()); } catch (final SQLException e) { throw new PaymentPluginApiException("HPP notification came through, but we encountered a database error", e); } } return buildPaymentTransactionInfoPlugin(adyenResponsesRecord); } @Override public PaymentTransactionInfoPlugin voidPayment(final UUID kbAccountId, final UUID kbPaymentId, final UUID kbTransactionId, final UUID kbPaymentMethodId, final Iterable<PluginProperty> properties, final CallContext context) throws PaymentPluginApiException { return executeFollowUpTransaction(TransactionType.VOID, new TransactionExecutor<PaymentModificationResponse>() { @Override public PaymentModificationResponse execute(@Nullable final Long transactionAmount, final PaymentProvider paymentProvider, final String pspReference, final SplitSettlementData splitSettlementData) { AdyenPaymentServiceProviderPort port = adyenConfigurationHandler.getConfigurable(context.getTenantId()); return port.cancel(paymentProvider, pspReference, splitSettlementData); } }, kbAccountId, kbPaymentId, kbTransactionId, kbPaymentMethodId, null, null, properties, context); } @Override public PaymentTransactionInfoPlugin creditPayment(final UUID kbAccountId, final UUID kbPaymentId, final UUID kbTransactionId, final UUID kbPaymentMethodId, final BigDecimal amount, final Currency currency, final Iterable<PluginProperty> properties, final CallContext context) throws PaymentPluginApiException { throw new PaymentPluginApiException(null, "CREDIT: unsupported operation"); } // HPP @Override public PaymentTransactionInfoPlugin refundPayment(final UUID kbAccountId, final UUID kbPaymentId, final UUID kbTransactionId, final UUID kbPaymentMethodId, final BigDecimal amount, final Currency currency, final Iterable<PluginProperty> properties, final CallContext context) throws PaymentPluginApiException { return executeFollowUpTransaction(TransactionType.REFUND, new TransactionExecutor<PaymentModificationResponse>() { @Override public PaymentModificationResponse execute(@Nullable final Long transactionAmount, final PaymentProvider paymentProvider, final String pspReference, final SplitSettlementData splitSettlementData) { AdyenPaymentServiceProviderPort providerPort = adyenConfigurationHandler.getConfigurable(context.getTenantId()); return providerPort.refund(transactionAmount, paymentProvider, pspReference, splitSettlementData); } }, kbAccountId, kbPaymentId, kbTransactionId, kbPaymentMethodId, amount, currency, properties, context); } @Override public HostedPaymentPageFormDescriptor buildFormDescriptor(final UUID kbAccountId, final Iterable<PluginProperty> customFields, final Iterable<PluginProperty> properties, final CallContext context) throws PaymentPluginApiException { //noinspection unchecked final Iterable<PluginProperty> mergedProperties = PluginProperties.merge(customFields, properties); final String amountString = PluginProperties.findPluginPropertyValue(PROPERTY_AMOUNT, mergedProperties); Preconditions.checkState(!Strings.isNullOrEmpty(amountString), "amount not specified"); final BigDecimal amountBD = new BigDecimal(amountString); final long amount = amountBD.longValue(); final Account account = getAccount(kbAccountId, context); final PaymentData paymentData = buildPaymentData(account, mergedProperties, context); final OrderData orderData = buildOrderData(account, mergedProperties); final UserData userData = buildUserData(account, mergedProperties); final boolean shouldCreatePendingPayment = Boolean.valueOf(PluginProperties.findPluginPropertyValue(PROPERTY_CREATE_PENDING_PAYMENT, mergedProperties)); if (shouldCreatePendingPayment) { createPendingPayment(account, amountBD, paymentData, context); } final String serverUrl = PluginProperties.findPluginPropertyValue(PROPERTY_SERVER_URL, mergedProperties); Preconditions.checkState(!Strings.isNullOrEmpty(serverUrl), "serverUrl not specified"); final String resultUrl = PluginProperties.findPluginPropertyValue(PROPERTY_RESULT_URL, mergedProperties); try { // Need to store on disk the mapping payment <-> user because Adyen's notification won't provide the latter //noinspection unchecked dao.addHppRequest(kbAccountId, paymentData.getPaymentTxnInternalRef(), PluginProperties.toMap(mergedProperties), clock.getUTCNow(), context.getTenantId()); } catch (final SQLException e) { throw new PaymentPluginApiException("Unable to store HPP request", e); } final AdyenPaymentServiceProviderHostedPaymentPagePort hostedPaymentPagePort = adyenHppConfigurationHandler.getConfigurable(context.getTenantId()); final Map<String, String> formParameter; try { formParameter = hostedPaymentPagePort.getFormParameter(amount, paymentData, orderData, userData, serverUrl, resultUrl); } catch (final SignatureGenerationException e) { throw new PaymentPluginApiException("Unable to generate signature", e); } final String formUrl = hostedPaymentPagePort.getFormUrl(paymentData); try { return new AdyenHostedPaymentPageFormDescriptor(kbAccountId, formUrl, formParameter); } catch (final URISyntaxException e) { throw new PaymentPluginApiException("Unable to generate valid HPP url", e); } } @Override public GatewayNotification processNotification(final String notification, final Iterable<PluginProperty> properties, final CallContext context) throws PaymentPluginApiException { final String notificationResponse = adyenNotificationService.handleNotifications(notification); return new AdyenGatewayNotification(notificationResponse); } private PaymentTransactionInfoPlugin executeInitialTransaction(final TransactionType transactionType, final TransactionExecutor<PurchaseResult> transactionExecutor, final UUID kbAccountId, final UUID kbPaymentId, final UUID kbTransactionId, final UUID kbPaymentMethodId, final BigDecimal amount, final Currency currency, final Iterable<PluginProperty> properties, final CallContext context) throws PaymentPluginApiException { final Account account = getAccount(kbAccountId, context); final Long transactionAmount = (amount == null ? null : amount.longValue()); final PaymentData paymentData = buildPaymentData(account, kbPaymentId, kbTransactionId, kbPaymentMethodId, currency, properties, context); final OrderData orderData = buildOrderData(account, properties); final UserData userData = buildUserData(account, properties); final String termUrl = PluginProperties.findPluginPropertyValue(PROPERTY_TERM_URL, properties); final SplitSettlementData splitSettlementData = null; final DateTime utcNow = clock.getUTCNow(); final PurchaseResult response = transactionExecutor.execute(transactionAmount, paymentData, orderData, userData, termUrl, splitSettlementData); try { dao.addResponse(kbAccountId, kbPaymentId, kbTransactionId, transactionType, amount, currency, response, utcNow, context.getTenantId()); return new AdyenPaymentTransactionInfoPlugin(kbPaymentId, kbTransactionId, transactionType, amount, currency, utcNow, response); } catch (final SQLException e) { throw new PaymentPluginApiException("Payment went through, but we encountered a database error. Payment details: " + response.toString(), e); } } private PaymentTransactionInfoPlugin executeFollowUpTransaction(final TransactionType transactionType, final TransactionExecutor<PaymentModificationResponse> transactionExecutor, final UUID kbAccountId, final UUID kbPaymentId, final UUID kbTransactionId, final UUID kbPaymentMethodId, @Nullable final BigDecimal amount, @Nullable final Currency currency, final Iterable<PluginProperty> properties, final CallContext context) throws PaymentPluginApiException { final Account account = getAccount(kbAccountId, context); final Long transactionAmount = amount == null ? null : amount.longValue(); final PaymentProvider paymentProvider = buildPaymentProvider(account, kbPaymentMethodId, currency, properties, context); final SplitSettlementData splitSettlementData = null; final String pspReference; try { final AdyenResponsesRecord previousResponse = dao.getSuccessfulAuthorizationResponse(kbPaymentId, context.getTenantId()); if (previousResponse == null) { throw new PaymentPluginApiException(null, "Unable to retrieve previous payment response for kbTransactionId " + kbTransactionId); } pspReference = previousResponse.getPspReference(); } catch (final SQLException e) { throw new PaymentPluginApiException("Unable to retrieve previous payment response for kbTransactionId " + kbTransactionId, e); } final DateTime utcNow = clock.getUTCNow(); final PaymentModificationResponse response; response = transactionExecutor.execute(transactionAmount, paymentProvider, pspReference, splitSettlementData); if (!response.isSuccess()) { return new AdyenPaymentTransactionInfoPlugin(kbPaymentId, kbTransactionId, transactionType, amount, currency, Optional.<PaymentServiceProviderResult>absent(), utcNow, response); } try { dao.addResponse(kbAccountId, kbPaymentId, kbTransactionId, transactionType, amount, currency, response, utcNow, context.getTenantId()); return new AdyenPaymentTransactionInfoPlugin(kbPaymentId, kbTransactionId, transactionType, amount, currency, Optional.of(PaymentServiceProviderResult.RECEIVED), utcNow, response); } catch (final SQLException e) { throw new PaymentPluginApiException("Payment went through, but we encountered a database error. Payment details: " + (response.toString()), e); } } // For API private PaymentData buildPaymentData(final Account account, final UUID kbPaymentId, final UUID kbTransactionId, final UUID kbPaymentMethodId, final Currency currency, final Iterable<PluginProperty> properties, final CallContext context) { final PaymentData<PaymentInfo> paymentData = new PaymentData<PaymentInfo>(); Payment payment = null; PaymentTransaction paymentTransaction = null; try { payment = killbillAPI.getPaymentApi().getPayment(kbPaymentId, false, properties, context); paymentTransaction = Iterables.find(payment.getTransactions(), new Predicate<PaymentTransaction>() { @Override public boolean apply(final PaymentTransaction input) { return kbTransactionId.equals(input.getId()); } }); } catch (final PaymentApiException e) { logService.log(LogService.LOG_WARNING, "Failed to retrieve payment " + kbPaymentId, e); } Preconditions.checkNotNull(payment); Preconditions.checkNotNull(paymentTransaction); paymentData.setPaymentId(kbPaymentId); paymentData.setPaymentInternalRef(payment.getExternalKey()); paymentData.setPaymentTxnInternalRef(paymentTransaction.getExternalKey()); paymentData.setPaymentInfo(buildPaymentInfo(account, kbPaymentMethodId, currency, properties, context)); return paymentData; } // For HPP private PaymentData buildPaymentData(final Account account, final Iterable<PluginProperty> properties, final CallContext context) { final PaymentData<WebPaymentFrontend> paymentData = new PaymentData<WebPaymentFrontend>(); final String internalRef = PluginProperties.getValue(PROPERTY_PAYMENT_EXTERNAL_KEY, UUID.randomUUID().toString(), properties); paymentData.setPaymentInternalRef(internalRef); paymentData.setPaymentTxnInternalRef(internalRef); paymentData.setPaymentInfo(buildPaymentInfo(account, properties, context)); return paymentData; } // For API private PaymentInfo buildPaymentInfo(final Account account, final UUID kbPaymentMethodId, final Currency currency, final Iterable<PluginProperty> properties, final CallContext context) { final AdyenPaymentMethodsRecord paymentMethodsRecord = getAdyenPaymentMethodsRecord(kbPaymentMethodId, context); final AdyenPaymentMethodsRecord nonNullPaymentMethodsRecord = paymentMethodsRecord == null ? emptyRecord(kbPaymentMethodId) : paymentMethodsRecord; final Iterable<PluginProperty> additionalPropertiesFromRecord = buildPaymentMethodPlugin(nonNullPaymentMethodsRecord).getProperties(); //noinspection unchecked final Iterable<PluginProperty> mergedProperties = PluginProperties.merge(additionalPropertiesFromRecord, properties); final PaymentProvider paymentProvider = buildPaymentProvider(account, nonNullPaymentMethodsRecord, currency, properties, context); final String paymentMethodsRecordCcType = nonNullPaymentMethodsRecord.getCcType(); final String ccType = PluginProperties.getValue(PROPERTY_CC_TYPE, paymentMethodsRecordCcType, properties); final String recurringDetailId = PluginProperties.findPluginPropertyValue(PROPERTY_RECURRING_DETAIL_ID, mergedProperties); if (recurringDetailId != null) { return buildRecurring(paymentMethodsRecord, paymentProvider, mergedProperties); } else if ("sepadirectdebit".equals(ccType)) { return buildSepaDirectDebit(nonNullPaymentMethodsRecord, paymentProvider, mergedProperties); } else if ("elv".equals(ccType)) { return buildElv(nonNullPaymentMethodsRecord, paymentProvider, mergedProperties); } else { return buildCreditCard(nonNullPaymentMethodsRecord, paymentProvider, mergedProperties); } } /** * There is the option not to use the adyen payment method table to retrieve payment data but to always provide * it as plugin properties. In this case an empty record (null object) could help. */ private AdyenPaymentMethodsRecord emptyRecord(UUID kbPaymentMethodId) { AdyenPaymentMethodsRecord record = new AdyenPaymentMethodsRecord(); record.setKbPaymentMethodId(kbPaymentMethodId.toString()); return record; } private CreditCard buildCreditCard(final AdyenPaymentMethodsRecord paymentMethodsRecord, final PaymentProvider paymentProvider, final Iterable<PluginProperty> properties) { final CreditCard creditCard = new CreditCard(paymentProvider); // By convention, support the same keys as the Ruby plugins (https://github.com/killbill/killbill-plugin-framework-ruby/blob/master/lib/killbill/helpers/active_merchant/payment_plugin.rb) final String ccNumber = PluginProperties.getValue(PROPERTY_CC_NUMBER, paymentMethodsRecord.getCcNumber(), properties); creditCard.setCcNumber(ccNumber); final String ccFirstName = PluginProperties.getValue(PROPERTY_CC_FIRST_NAME, paymentMethodsRecord.getCcFirstName(), properties); final String ccLastName = PluginProperties.getValue(PROPERTY_CC_LAST_NAME, paymentMethodsRecord.getCcLastName(), properties); creditCard.setCcHolderName(holderName(ccFirstName, ccLastName)); final String ccExpirationMonth = PluginProperties.getValue(PROPERTY_CC_EXPIRATION_MONTH, paymentMethodsRecord.getCcExpMonth(), properties); if (ccExpirationMonth != null) { creditCard.setValidUntilMonth(Integer.valueOf(ccExpirationMonth)); } final String ccExpirationYear = PluginProperties.getValue(PROPERTY_CC_EXPIRATION_YEAR, paymentMethodsRecord.getCcExpYear(), properties); if (ccExpirationYear != null) { creditCard.setValidUntilYear(Integer.valueOf(ccExpirationYear)); } final String ccVerificationValue = PluginProperties.getValue(PROPERTY_CC_VERIFICATION_VALUE, paymentMethodsRecord.getCcVerificationValue(), properties); if (ccVerificationValue != null) { creditCard.setCcSecCode(ccVerificationValue); } return creditCard; } private SepaDirectDebit buildSepaDirectDebit(final AdyenPaymentMethodsRecord paymentMethodsRecord, final PaymentProvider paymentProvider, final Iterable<PluginProperty> properties) { final SepaDirectDebit sepaDirectDebit = new SepaDirectDebit(paymentProvider); final String ddAccountNumber = PluginProperties.getValue(PROPERTY_DD_ACCOUNT_NUMBER, paymentMethodsRecord.getCcNumber(), properties); sepaDirectDebit.setIban(ddAccountNumber); final String paymentMethodHolderName = holderName(paymentMethodsRecord.getCcFirstName(), paymentMethodsRecord.getCcLastName()); final String ddHolderName = PluginProperties.getValue(PROPERTY_DD_HOLDER_NAME, paymentMethodHolderName, properties); sepaDirectDebit.setSepaAccountHolder(ddHolderName); final String paymentMethodBic = PluginProperties.findPluginPropertyValue(PROPERTY_DD_BANK_IDENTIFIER_CODE, properties); final String ddBic = PluginProperties.getValue(PROPERTY_DD_BANK_IDENTIFIER_CODE, paymentMethodBic, properties); sepaDirectDebit.setBic(ddBic); final String countryCode = MoreObjects.firstNonNull(paymentMethodsRecord.getCountry(), paymentProvider.getCountryIsoCode()); sepaDirectDebit.setCountryCode(countryCode); return sepaDirectDebit; } private Elv buildElv(final AdyenPaymentMethodsRecord paymentMethodsRecord, final PaymentProvider paymentProvider, final Iterable<PluginProperty> properties) { final Elv elv = new Elv(paymentProvider); final String ddAccountNumber = PluginProperties.getValue(PROPERTY_DD_ACCOUNT_NUMBER, paymentMethodsRecord.getCcNumber(), properties); elv.setElvKontoNummer(ddAccountNumber); final String paymentMethodHolderName = holderName(paymentMethodsRecord.getCcFirstName(), paymentMethodsRecord.getCcLastName()); final String ddHolderName = PluginProperties.getValue(PROPERTY_DD_HOLDER_NAME, paymentMethodHolderName, properties); elv.setElvAccountHolder(ddHolderName); final String paymentMethodBlz = PluginProperties.findPluginPropertyValue(PROPERTY_DD_BANKLEITZAHL, properties); final String ddBlz = PluginProperties.getValue(PROPERTY_DD_BANKLEITZAHL, paymentMethodBlz, properties); elv.setElvBlz(ddBlz); return elv; } private Recurring buildRecurring(final AdyenPaymentMethodsRecord paymentMethodsRecord, final PaymentProvider paymentProvider, final Iterable<PluginProperty> properties) { final String recurringDetailId = PluginProperties.findPluginPropertyValue(PROPERTY_RECURRING_DETAIL_ID, properties); final String ccVerificationValue = PluginProperties.getValue(PROPERTY_CC_VERIFICATION_VALUE, paymentMethodsRecord.getCcVerificationValue(), properties); if (RecurringType.ONECLICK.equals(paymentProvider.getRecurringType())) { final OneClick oneClick = new OneClick(paymentProvider); oneClick.setRecurringDetailId(recurringDetailId); oneClick.setCcSecCode(ccVerificationValue); return oneClick; } else { final Recurring recurring = new Recurring(paymentProvider); recurring.setRecurringDetailId(recurringDetailId); return recurring; } } // For HPP private WebPaymentFrontend buildPaymentInfo(final Account account, final Iterable<PluginProperty> properties, final CallContext context) { final PaymentProvider paymentProvider = buildPaymentProvider(account, (UUID) null, null, properties, context); return new WebPaymentFrontend(paymentProvider); } private AdyenPaymentMethodsRecord getAdyenPaymentMethodsRecord(final UUID kbPaymentMethodId, final CallContext context) { AdyenPaymentMethodsRecord paymentMethodsRecord = null; try { paymentMethodsRecord = dao.getPaymentMethod(kbPaymentMethodId, context.getTenantId()); } catch (final SQLException e) { logService.log(LogService.LOG_WARNING, "Failed to retrieve payment method " + kbPaymentMethodId, e); } return paymentMethodsRecord; } private PaymentProvider buildPaymentProvider(final Account account, @Nullable final UUID kbPaymentMethodId, @Nullable final Currency currency, final Iterable<PluginProperty> properties, final CallContext context) { final AdyenPaymentMethodsRecord paymentMethodsRecord = kbPaymentMethodId == null ? null : getAdyenPaymentMethodsRecord(kbPaymentMethodId, context); return buildPaymentProvider(account, paymentMethodsRecord, currency, properties, context); } private PaymentProvider buildPaymentProvider(final Account account, @Nullable final AdyenPaymentMethodsRecord paymentMethodsRecord, @Nullable final Currency currency, final Iterable<PluginProperty> properties, final CallContext context) { final String pluginPropertyCurrency = PluginProperties.findPluginPropertyValue(PROPERTY_CURRENCY, properties); final String paymentProviderCurrency = pluginPropertyCurrency == null ? (currency == null ? null : currency.name()) : pluginPropertyCurrency; final String pluginPropertyCountry = PluginProperties.findPluginPropertyValue(PROPERTY_COUNTRY, properties); final String paymentProviderCountryIsoCode = pluginPropertyCountry == null ? account.getCountry() : pluginPropertyCountry; final String pluginPropertyPaymentProviderType = PluginProperties.findPluginPropertyValue(PROPERTY_PAYMENT_PROVIDER_TYPE, properties); final String recurringDetailId = PluginProperties.findPluginPropertyValue(PROPERTY_RECURRING_DETAIL_ID, properties); final String pluginPropertyPaymentRecurringType = PluginProperties.findPluginPropertyValue(PROPERTY_RECURRING_TYPE, properties); final PaymentType paymentProviderPaymentType; if (recurringDetailId != null) { paymentProviderPaymentType = PaymentType.EMPTY; } else if (pluginPropertyPaymentProviderType != null) { paymentProviderPaymentType = PaymentType.getByName(pluginPropertyPaymentProviderType); } else { final String pluginPropertyCCType = PluginProperties.findPluginPropertyValue(PROPERTY_CC_TYPE, properties); final String paymentMethodCCType = paymentMethodsRecord == null || paymentMethodsRecord.getCcType() == null ? null : paymentMethodsRecord.getCcType(); paymentProviderPaymentType = pluginPropertyCCType == null ? (paymentMethodCCType == null ? PaymentType.CREDITCARD : PaymentType.getByName(paymentMethodCCType)) : PaymentType.getByName(pluginPropertyCCType); } final RecurringType paymentProviderRecurringType; if (pluginPropertyPaymentRecurringType != null) { paymentProviderRecurringType = RecurringType.valueOf(pluginPropertyPaymentRecurringType); } else { paymentProviderRecurringType = null; } // A bit of a hack - it would be nice to be able to isolate AdyenConfigProperties final AdyenConfigProperties adyenConfigProperties = adyenHppConfigurationHandler.getConfigurable(context.getTenantId()).getAdyenConfigProperties(); final PaymentProvider paymentProvider = new PaymentProvider(adyenConfigProperties); if (paymentProviderCurrency != null) { paymentProvider.setCurrency(java.util.Currency.getInstance(paymentProviderCurrency)); } paymentProvider.setCountryIsoCode(paymentProviderCountryIsoCode); paymentProvider.setPaymentType(paymentProviderPaymentType); paymentProvider.setRecurringType(paymentProviderRecurringType); return paymentProvider; } private UserData buildUserData(@Nullable final Account account, final Iterable<PluginProperty> properties) { final UserData userData = new UserData(); final String accountCustomerId = account == null ? null : (account.getExternalKey() == null ? account.getId().toString() : account.getExternalKey()); userData.setCustomerId(PluginProperties.getValue(PROPERTY_CUSTOMER_ID, accountCustomerId, properties)); final String propertyLocaleString = PluginProperties.findPluginPropertyValue(PROPERTY_CUSTOMER_LOCALE, properties); final Locale propertyCustomerLocale = propertyLocaleString == null ? null : Locale.forLanguageTag(propertyLocaleString); final Locale accountLocale = account == null || account.getLocale() == null ? null : new Locale(account.getLocale()); userData.setCustomerLocale(propertyCustomerLocale == null ? accountLocale : propertyCustomerLocale); final String accountEmail = account == null ? null : account.getEmail(); userData.setEmail(PluginProperties.getValue(PROPERTY_EMAIL, accountEmail, properties)); final String accountFirstName = account == null || account.getName() == null ? null : account.getName().substring(0, MoreObjects.firstNonNull(account.getFirstNameLength(), account.getName().length())); userData.setFirstName(PluginProperties.getValue(PROPERTY_FIRST_NAME, accountFirstName, properties)); final String accountLastName = account == null || account.getName() == null ? null : account.getName().substring(MoreObjects.firstNonNull(account.getFirstNameLength(), account.getName().length()), account.getName().length()); userData.setLastName(PluginProperties.getValue(PROPERTY_LAST_NAME, accountLastName, properties)); userData.setIP(PluginProperties.findPluginPropertyValue(PROPERTY_IP, properties)); return userData; } private OrderData buildOrderData(@Nullable final Account account, final Iterable<PluginProperty> properties) { final OrderData orderData = new OrderData(); final String accountName = account == null ? null : account.getName(); orderData.setHolderName(PluginProperties.getValue(PROPERTY_HOLDER_NAME, accountName, properties)); final String propertyShipBeforeDate = PluginProperties.findPluginPropertyValue(PROPERTY_SHIP_BEFORE_DATE, properties); // Mandatory for HPP orderData.setShipBeforeDate(propertyShipBeforeDate == null ? clock.getUTCNow().plusHours(1) : new DateTime(propertyShipBeforeDate)); return orderData; } private void createPendingPayment(final Account account, final BigDecimal amount, final PaymentData paymentData, final CallContext context) throws PaymentPluginApiException { final UUID kbPaymentId = null; final Currency currency = Currency.valueOf(paymentData.getPaymentInfo().getPaymentProvider().getCurrency().toString()); final String paymentExternalKey = paymentData.getPaymentTxnInternalRef(); final ImmutableMap<String, Object> purchasePropertiesMap = ImmutableMap.<String, Object>of(AdyenPaymentPluginApi.PROPERTY_FROM_HPP, true, AdyenPaymentPluginApi.PROPERTY_FROM_HPP_TRANSACTION_STATUS, PaymentPluginStatus.PENDING.toString()); final Iterable<PluginProperty> purchaseProperties = PluginProperties.buildPluginProperties(purchasePropertiesMap); try { final UUID kbPaymentMethodId = getAdyenKbPaymentMethodId(account.getId(), context); killbillAPI.getPaymentApi().createPurchase(account, kbPaymentMethodId, kbPaymentId, amount, currency, paymentExternalKey, paymentExternalKey, purchaseProperties, context); } catch (final PaymentApiException e) { throw new PaymentPluginApiException("Failed to record purchase", e); } } // Could be shared (see KillbillAdyenNotificationHandler) private UUID getAdyenKbPaymentMethodId(final UUID kbAccountId, final TenantContext context) throws PaymentApiException { return Iterables.find(killbillAPI.getPaymentApi().getAccountPaymentMethods(kbAccountId, false, ImmutableList.<PluginProperty>of(), context), new Predicate<PaymentMethod>() { @Override public boolean apply(final PaymentMethod paymentMethod) { return AdyenActivator.PLUGIN_NAME.equals(paymentMethod.getPluginName()); } }).getId(); } private static abstract class TransactionExecutor<T> { public T execute(final Long amount, final PaymentData paymentData, final OrderData orderData, final UserData userData, final String termUrl, final SplitSettlementData splitSettlementData) { throw new UnsupportedOperationException(); } public T execute(@Nullable final Long transactionAmount, final PaymentProvider paymentProvider, final String pspReference, final SplitSettlementData splitSettlementData) { throw new UnsupportedOperationException(); } } }
package com.akdeniz.googleplaycrawler; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.impl.conn.SchemeRegistryFactory; import org.apache.http.message.BasicNameValuePair; import com.akdeniz.googleplaycrawler.GooglePlay.AndroidAppDeliveryData; import com.akdeniz.googleplaycrawler.GooglePlay.AndroidCheckinRequest; import com.akdeniz.googleplaycrawler.GooglePlay.AndroidCheckinResponse; import com.akdeniz.googleplaycrawler.GooglePlay.BrowseResponse; import com.akdeniz.googleplaycrawler.GooglePlay.BulkDetailsRequest; import com.akdeniz.googleplaycrawler.GooglePlay.BulkDetailsRequest.Builder; import com.akdeniz.googleplaycrawler.GooglePlay.BulkDetailsResponse; import com.akdeniz.googleplaycrawler.GooglePlay.BuyResponse; import com.akdeniz.googleplaycrawler.GooglePlay.DetailsResponse; import com.akdeniz.googleplaycrawler.GooglePlay.ListResponse; import com.akdeniz.googleplaycrawler.GooglePlay.ResponseWrapper; import com.akdeniz.googleplaycrawler.GooglePlay.ReviewResponse; import com.akdeniz.googleplaycrawler.GooglePlay.SearchResponse; import com.akdeniz.googleplaycrawler.GooglePlay.UploadDeviceConfigRequest; import com.akdeniz.googleplaycrawler.GooglePlay.UploadDeviceConfigResponse; /** * This class provides * <code>checkin, search, details, bulkDetails, browse, list and download</code> * capabilities. It uses <code>Apache Commons HttpClient</code> for POST and GET * requests. * * <p> * <b>XXX : DO NOT call checkin, login and download consecutively. To allow * server to catch up, sleep for a while before download! (5 sec will do!) Also * it is recommended to call checkin once and use generated android-id for * further operations.</b> * </p> * * @author akdeniz * */ public class GooglePlayAPI { private static final String CHECKIN_URL = "https://android.clients.google.com/checkin"; private static final String URL_LOGIN = "https://android.clients.google.com/auth"; private static final String C2DM_REGISTER_URL = "https://android.clients.google.com/c2dm/register2"; private static final String FDFE_URL = "https://android.clients.google.com/fdfe/"; private static final String LIST_URL = FDFE_URL + "list"; private static final String BROWSE_URL = FDFE_URL + "browse"; private static final String DETAILS_URL = FDFE_URL + "details"; private static final String SEARCH_URL = FDFE_URL + "search"; private static final String BULKDETAILS_URL = FDFE_URL + "bulkDetails"; private static final String PURCHASE_URL = FDFE_URL + "purchase"; private static final String REVIEWS_URL = FDFE_URL + "rev"; private static final String UPLOADDEVICECONFIG_URL = FDFE_URL + "uploadDeviceConfig"; private static final String RECOMMENDATIONS_URL = FDFE_URL + "rec"; private static final String DELIVERY_URL = FDFE_URL + "delivery"; private static final String ACCOUNT_TYPE_HOSTED_OR_GOOGLE = "HOSTED_OR_GOOGLE"; public static enum REVIEW_SORT { NEWEST(0), HIGHRATING(1), HELPFUL(2); public int value; private REVIEW_SORT(int value) { this.value = value; } } public static enum RECOMMENDATION_TYPE { ALSO_VIEWED(1), ALSO_INSTALLED(2); public int value; private RECOMMENDATION_TYPE(int value) { this.value = value; } } private String token; private String androidID; private String email; private String password; private HttpClient client; private String securityToken; private String localization; private String useragent; /** * Default constructor. ANDROID ID and Authentication token must be supplied * before any other operation. */ public GooglePlayAPI() { } /** * Constructs a ready to login {@link GooglePlayAPI}. */ public GooglePlayAPI(String email, String password, String androidID) { this(email, password); this.setAndroidID(androidID); } /** * If this constructor is used, Android ID must be generated by calling * <code>checkin()</code> or set by using <code>setAndroidID</code> before * using other abilities. */ public GooglePlayAPI(String email, String password) { this.setEmail(email); this.password = password; setClient(new DefaultHttpClient(getConnectionManager())); // setUseragent("Android-Finsky/3.10.14 (api=3,versionCode=8016014,sdk=15,device=GT-I9300,hardware=aries,product=GT-I9300)"); setUseragent("Android-Finsky/6.5.08.D-all (versionCode=80650800,sdk=23,device=noblelte,hardware=noblelte,product=noblelte,build=MMB29K:user)"); } /** * Connection manager to allow concurrent connections. * * @return {@link ClientConnectionManager} instance */ public static ClientConnectionManager getConnectionManager() { PoolingClientConnectionManager connManager = new PoolingClientConnectionManager( SchemeRegistryFactory.createDefault()); connManager.setMaxTotal(100); connManager.setDefaultMaxPerRoute(30); return connManager; } /** * Performs authentication on "ac2dm" service and match up android id, * security token and email by checking them in on this server. * * This function sets check-inded android ID and that can be taken either by * using <code>getToken()</code> or from returned * {@link AndroidCheckinResponse} instance. * */ public AndroidCheckinResponse checkin() throws Exception { // this first checkin is for generating android-id AndroidCheckinResponse checkinResponse = postCheckin(Utils.generateAndroidCheckinRequest() .toByteArray()); this.setAndroidID(BigInteger.valueOf(checkinResponse.getAndroidId()).toString(16)); setSecurityToken((BigInteger.valueOf(checkinResponse.getSecurityToken()).toString(16))); String c2dmAuth = loginAC2DM(); AndroidCheckinRequest.Builder checkInbuilder = AndroidCheckinRequest.newBuilder(Utils .generateAndroidCheckinRequest()); AndroidCheckinRequest build = checkInbuilder .setId(new BigInteger(this.getAndroidID(), 16).longValue()) .setSecurityToken(new BigInteger(getSecurityToken(), 16).longValue()) .addAccountCookie("[" + getEmail() + "]").addAccountCookie(c2dmAuth).build(); // this is the second checkin to match credentials with android-id return postCheckin(build.toByteArray()); } /** * Logins AC2DM server and returns authentication string. */ public String loginAC2DM() throws IOException { HttpEntity c2dmResponseEntity = executePost(URL_LOGIN, new String[][] { { "Email", this.getEmail() }, { "Passwd", this.password }, { "add_account", "1"}, { "service", "ac2dm" }, { "accountType", ACCOUNT_TYPE_HOSTED_OR_GOOGLE }, { "has_permission", "1" }, { "source", "android" }, { "app", "com.google.android.gsf" }, { "device_country", "us" }, { "device_country", "us" }, { "lang", "en" }, { "sdk_version", "17" }, }, null); Map<String, String> c2dmAuth = Utils.parseResponse(new String(Utils.readAll(c2dmResponseEntity .getContent()))); return c2dmAuth.get("Auth"); } public Map<String, String> c2dmRegister(String application, String sender) throws IOException { String c2dmAuth = loginAC2DM(); String[][] data = new String[][] { { "app", application }, { "sender", sender }, { "device", new BigInteger(this.getAndroidID(), 16).toString() } }; HttpEntity responseEntity = executePost(C2DM_REGISTER_URL, data, getHeaderParameters(c2dmAuth, null)); return Utils.parseResponse(new String(Utils.readAll(responseEntity.getContent()))); } /** * Equivalent of <code>setToken</code>. This function does not performs * authentication, it simply sets authentication token. */ public void login(String token) throws Exception { setToken(token); } /** * Authenticates on server with given email and password and sets * authentication token. This token can be used to login instead of using * email and password every time. */ public void login() throws Exception { HttpEntity responseEntity = executePost(URL_LOGIN, new String[][] { { "Email", this.getEmail() }, { "Passwd", this.password }, { "service", "androidmarket" }, { "add_account", "1"}, { "accountType", ACCOUNT_TYPE_HOSTED_OR_GOOGLE }, { "has_permission", "1" }, { "source", "android" }, { "androidId", this.getAndroidID() }, { "app", "com.android.vending" }, { "device_country", "en" }, { "lang", "en" }, { "sdk_version", "17" }, }, null); Map<String, String> response = Utils.parseResponse(new String(Utils.readAll(responseEntity .getContent()))); if (response.containsKey("Auth")) { setToken(response.get("Auth")); } else { throw new GooglePlayException("Authentication failed!"); } } /** * Equivalent of <code>search(query, null, null)</code> */ public SearchResponse search(String query) throws IOException { return search(query, null, null); } /** * Fetches a search results for given query. Offset and numberOfResult * parameters are optional and <code>null</code> can be passed! */ public SearchResponse search(String query, Integer offset, Integer numberOfResult) throws IOException { ResponseWrapper responseWrapper = executeGETRequest(SEARCH_URL, new String[][] { { "c", "3" }, { "q", query }, { "o", (offset == null) ? null : String.valueOf(offset) }, { "n", (numberOfResult == null) ? null : String.valueOf(numberOfResult) }, }); return responseWrapper.getPayload().getSearchResponse(); } /** * Fetches detailed information about passed package name. If it is needed to * fetch information about more than one application, consider to use * <code>bulkDetails</code>. */ public DetailsResponse details(String packageName) throws IOException { ResponseWrapper responseWrapper = executeGETRequest(DETAILS_URL, new String[][] { { "doc", packageName }, }); return responseWrapper.getPayload().getDetailsResponse(); } /** Equivalent of details but bulky one! */ public BulkDetailsResponse bulkDetails(List<String> packageNames) throws IOException { Builder bulkDetailsRequestBuilder = BulkDetailsRequest.newBuilder(); bulkDetailsRequestBuilder.addAllDocid(packageNames); ResponseWrapper responseWrapper = executePOSTRequest(BULKDETAILS_URL, bulkDetailsRequestBuilder .build().toByteArray(), "application/x-protobuf"); return responseWrapper.getPayload().getBulkDetailsResponse(); } /** Fetches available categories */ public BrowseResponse browse() throws IOException { return browse(null, null); } public BrowseResponse browse(String categoryId, String subCategoryId) throws IOException { ResponseWrapper responseWrapper = executeGETRequest(BROWSE_URL, new String[][] { { "c", "3" }, { "cat", categoryId }, { "ctr", subCategoryId } }); return responseWrapper.getPayload().getBrowseResponse(); } /** * Equivalent of <code>list(categoryId, null, null, null)</code>. It fetches * sub-categories of given category! */ public ListResponse list(String categoryId) throws IOException { return list(categoryId, null, null, null); } /** * Fetches applications within supplied category and sub-category. If * <code>null</code> is given for sub-category, it fetches sub-categories of * passed category. * * Default values for offset and numberOfResult are "0" and "20" respectively. * These values are determined by Google Play Store. */ public ListResponse list(String categoryId, String subCategoryId, Integer offset, Integer numberOfResult) throws IOException { ResponseWrapper responseWrapper = executeGETRequest(LIST_URL, new String[][] { { "c", "3" }, { "cat", categoryId }, { "ctr", subCategoryId }, { "o", (offset == null) ? null : String.valueOf(offset) }, { "n", (numberOfResult == null) ? null : String.valueOf(numberOfResult) }, }); return responseWrapper.getPayload().getListResponse(); } /** * Downloads given application package name, version and offer type. Version * code and offer type can be fetch by <code>details</code> interface. **/ public DownloadData download(String packageName, int versionCode, int offerType) throws IOException { BuyResponse buyResponse = purchase(packageName, versionCode, offerType); return new DownloadData(this, buyResponse.getPurchaseStatusResponse().getAppDeliveryData()); } public DownloadData delivery(String packageName, int versionCode, int offerType) throws IOException { ResponseWrapper responseWrapper = executeGETRequest(DELIVERY_URL, new String[][] { { "ot", String.valueOf(offerType) }, { "doc", packageName }, { "vc", String.valueOf(versionCode) }, }); AndroidAppDeliveryData appDeliveryData = responseWrapper.getPayload().getDeliveryResponse() .getAppDeliveryData(); return new DownloadData(this, appDeliveryData); } /** * Posts given check-in request content and returns * {@link AndroidCheckinResponse}. */ private AndroidCheckinResponse postCheckin(byte[] request) throws IOException { HttpEntity httpEntity = executePost(CHECKIN_URL, new ByteArrayEntity(request), new String[][] { { "User-Agent", "Android-Checkin/2.0 (generic JRO03E); gzip" }, { "Host", "android.clients.google.com" }, { "Content-Type", "application/x-protobuffer" } }); return AndroidCheckinResponse.parseFrom(httpEntity.getContent()); } /** * This function is used for fetching download url and donwload cookie, rather * than actual purchasing. */ private BuyResponse purchase(String packageName, int versionCode, int offerType) throws IOException { ResponseWrapper responseWrapper = executePOSTRequest(PURCHASE_URL, new String[][] { { "ot", String.valueOf(offerType) }, { "doc", packageName }, { "vc", String.valueOf(versionCode) }, }); return responseWrapper.getPayload().getBuyResponse(); } /** * Fetches url content by executing GET request with provided cookie string. */ public InputStream executeDownload(String url, String cookie) throws IOException { String[][] headerParams = new String[][] { { "Cookie", cookie }, { "User-Agent", "AndroidDownloadManager/4.1.1 (Linux; U; Android 4.1.1; Nexus S Build/JRO03E)" }, }; HttpEntity httpEntity = executeGet(url, null, headerParams); return httpEntity.getContent(); } /** * Fetches the reviews of given package name by sorting passed choice. * * Default values for offset and numberOfResult are "0" and "20" respectively. * These values are determined by Google Play Store. */ public ReviewResponse reviews(String packageName, REVIEW_SORT sort, Integer offset, Integer numberOfResult) throws IOException { ResponseWrapper responseWrapper = executeGETRequest(REVIEWS_URL, new String[][] { { "doc", packageName }, { "sort", (sort == null) ? null : String.valueOf(sort.value) }, { "o", (offset == null) ? null : String.valueOf(offset) }, { "n", (numberOfResult == null) ? null : String.valueOf(numberOfResult) } }); return responseWrapper.getPayload().getReviewResponse(); } /** * Uploads device configuration to google server so that can be seen from web * as a registered device!! * * @see https://play.google.com/store/account */ public UploadDeviceConfigResponse uploadDeviceConfig() throws Exception { UploadDeviceConfigRequest request = UploadDeviceConfigRequest.newBuilder() .setDeviceConfiguration(Utils.getDeviceConfigurationProto()).build(); ResponseWrapper responseWrapper = executePOSTRequest(UPLOADDEVICECONFIG_URL, request.toByteArray(), "application/x-protobuf"); return responseWrapper.getPayload().getUploadDeviceConfigResponse(); } /** * Fetches the recommendations of given package name. * * Default values for offset and numberOfResult are "0" and "20" respectively. * These values are determined by Google Play Store. */ public ListResponse recommendations(String packageName, RECOMMENDATION_TYPE type, Integer offset, Integer numberOfResult) throws IOException { ResponseWrapper responseWrapper = executeGETRequest(RECOMMENDATIONS_URL, new String[][] { { "c", "3" }, { "doc", packageName }, { "rt", (type == null) ? null : String.valueOf(type.value) }, { "o", (offset == null) ? null : String.valueOf(offset) }, { "n", (numberOfResult == null) ? null : String.valueOf(numberOfResult) } }); return responseWrapper.getPayload().getListResponse(); } /* =======================Helper Functions====================== */ /** * Executes GET request and returns result as {@link ResponseWrapper}. * Standard header parameters will be used for request. * * @see getHeaderParameters * */ private ResponseWrapper executeGETRequest(String path, String[][] datapost) throws IOException { HttpEntity httpEntity = executeGet(path, datapost, getHeaderParameters(this.getToken(), null)); return GooglePlay.ResponseWrapper.parseFrom(httpEntity.getContent()); } /** * Executes POST request and returns result as {@link ResponseWrapper}. * Standard header parameters will be used for request. * * @see getHeaderParameters * */ private ResponseWrapper executePOSTRequest(String path, String[][] datapost) throws IOException { HttpEntity httpEntity = executePost(path, datapost, getHeaderParameters(this.getToken(), null)); return GooglePlay.ResponseWrapper.parseFrom(httpEntity.getContent()); } /** * Executes POST request and returns result as {@link ResponseWrapper}. * Content type can be specified for given byte array. */ private ResponseWrapper executePOSTRequest(String url, byte[] datapost, String contentType) throws IOException { HttpEntity httpEntity = executePost(url, new ByteArrayEntity(datapost), getHeaderParameters(this.getToken(), contentType)); return GooglePlay.ResponseWrapper.parseFrom(httpEntity.getContent()); } /** * Executes POST request on given URL with POST parameters and header * parameters. */ private HttpEntity executePost(String url, String[][] postParams, String[][] headerParams) throws IOException { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (String[] param : postParams) { if (param[0] != null && param[1] != null) { formparams.add(new BasicNameValuePair(param[0], param[1])); } } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); return executePost(url, entity, headerParams); } /** * Executes POST request on given URL with {@link HttpEntity} typed POST * parameters and header parameters. */ private HttpEntity executePost(String url, HttpEntity postData, String[][] headerParams) throws IOException { HttpPost httppost = new HttpPost(url); if (headerParams != null) { for (String[] param : headerParams) { if (param[0] != null && param[1] != null) { httppost.setHeader(param[0], param[1]); } } } httppost.setEntity(postData); return executeHttpRequest(httppost); } /** * Executes GET request on given URL with GET parameters and header * parameters. */ private HttpEntity executeGet(String url, String[][] getParams, String[][] headerParams) throws IOException { if (getParams != null) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (String[] param : getParams) { if (param[0] != null && param[1] != null) { formparams.add(new BasicNameValuePair(param[0], param[1])); } } url = url + "?" + URLEncodedUtils.format(formparams, "UTF-8"); } HttpGet httpget = new HttpGet(url); if (headerParams != null) { for (String[] param : headerParams) { if (param[0] != null && param[1] != null) { httpget.setHeader(param[0], param[1]); } } } return executeHttpRequest(httpget); } /** Executes given GET/POST request */ private HttpEntity executeHttpRequest(HttpUriRequest request) throws ClientProtocolException, IOException { HttpResponse response = getClient().execute(request); if (response.getStatusLine().getStatusCode() != 200) { throw new GooglePlayException(new String(Utils.readAll(response.getEntity().getContent()))); } return response.getEntity(); } /** * Gets header parameters for GET/POST requests. If no content type is given, * default one is used! */ private String[][] getHeaderParameters(String token, String contentType) { return new String[][] { { "Accept-Language", getLocalization() != null ? getLocalization() : "en-EN" }, { "Authorization", "GoogleLogin auth=" + token }, { "X-DFE-Enabled-Experiments", "cl:billing.select_add_instrument_by_default" }, { "X-DFE-Unsupported-Experiments", "nocache:billing.use_charging_poller,market_emails,buyer_currency,prod_baseline,checkin.set_asset_paid_app_field,shekel_test,content_ratings,buyer_currency_in_app,nocache:encrypted_apk,recent_changes" }, { "X-DFE-Device-Id", this.getAndroidID() }, { "X-DFE-Client-Id", "am-android-google" }, { "User-Agent", getUseragent() }, { "X-DFE-SmallestScreenWidthDp", "320" }, { "X-DFE-Filter-Level", "3" }, { "Host", "android.clients.google.com" }, { "Content-Type", (contentType != null) ? contentType : "application/x-www-form-urlencoded; charset=UTF-8" } }; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getAndroidID() { return androidID; } public void setAndroidID(String androidID) { this.androidID = androidID; } public String getSecurityToken() { return securityToken; } public void setSecurityToken(String securityToken) { this.securityToken = securityToken; } public HttpClient getClient() { return client; } /** * Sets {@link HttpClient} instance for internal usage of GooglePlayAPI. It is * important to note that this instance should allow concurrent connections. * * @see getConnectionManager * * @param client */ public void setClient(HttpClient client) { this.client = client; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getLocalization() { return localization; } /** * Localization string that will be used in each request to server. Using this * option you can fetch localized informations such as reviews and * descriptions. * <p> * Note that changing this value has no affect on localized application list * that server provides. It depends on only your IP location. * <p> * * @param localization * can be <b>en-EN, en-US, tr-TR, fr-FR ... (default : en-EN)</b> */ public void setLocalization(String localization) { this.localization = localization; } /** * @return the useragent */ public String getUseragent() { return useragent; } /** * @param useragent * the useragent to set */ public void setUseragent(String useragent) { this.useragent = useragent; } }
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.append; import java.util.List; import java.util.Map; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Counter; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.TransMeta.TransformationType; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepIOMeta; import org.pentaho.di.trans.step.StepIOMetaInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.step.errorhandling.Stream; import org.pentaho.di.trans.step.errorhandling.StreamIcon; import org.pentaho.di.trans.step.errorhandling.StreamInterface; import org.pentaho.di.trans.step.errorhandling.StreamInterface.StreamType; import org.w3c.dom.Node; /** * @author Sven Boden * @since 3-june-2007 */ public class AppendMeta extends BaseStepMeta implements StepMetaInterface { private static Class<?> PKG = Append.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ public AppendMeta() { super(); // allocate BaseStepMeta } public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException { readData(stepnode); } public Object clone() { AppendMeta retval = (AppendMeta)super.clone(); return retval; } public String getXML() { StringBuilder retval = new StringBuilder(); List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams(); retval.append(XMLHandler.addTagValue("head_name", infoStreams.get(0).getStepname())); //$NON-NLS-1$ retval.append(XMLHandler.addTagValue("tail_name", infoStreams.get(1).getStepname())); //$NON-NLS-1$ return retval.toString(); } private void readData(Node stepnode) throws KettleXMLException { try { List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams(); StreamInterface headStream = infoStreams.get(0); StreamInterface tailStream = infoStreams.get(1); headStream.setSubject( XMLHandler.getTagValue(stepnode, "head_name") ); //$NON-NLS-1$ tailStream.setSubject( XMLHandler.getTagValue(stepnode, "tail_name") ); //$NON-NLS-1$ } catch(Exception e) { throw new KettleXMLException(BaseMessages.getString(PKG, "AppendMeta.Exception.UnableToLoadStepInfo"), e); //$NON-NLS-1$ } } public void setDefault() { } public void readRep(Repository rep, ObjectId id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException { try { List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams(); StreamInterface headStream = infoStreams.get(0); StreamInterface tailStream = infoStreams.get(1); headStream.setSubject( rep.getStepAttributeString (id_step, "head_name") ); //$NON-NLS-1$ tailStream.setSubject( rep.getStepAttributeString (id_step, "tail_name") ); //$NON-NLS-1$ } catch(Exception e) { throw new KettleException(BaseMessages.getString(PKG, "AppendMeta.Exception.UnexpectedErrorReadingStepInfo"), e); //$NON-NLS-1$ } } public void saveRep(Repository rep, ObjectId id_transformation, ObjectId id_step) throws KettleException { try { List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams(); StreamInterface headStream = infoStreams.get(0); StreamInterface tailStream = infoStreams.get(1); rep.saveStepAttribute(id_transformation, id_step, "head_name", headStream.getStepname()); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "tail_name", tailStream.getStepname()); //$NON-NLS-1$ } catch(Exception e) { throw new KettleException(BaseMessages.getString(PKG, "AppendMeta.Exception.UnableToSaveStepInfo")+id_step, e); //$NON-NLS-1$ } } @Override public void searchInfoAndTargetSteps(List<StepMeta> steps) { for (StreamInterface stream : getStepIOMeta().getInfoStreams()) { stream.setStepMeta(StepMeta.findStep(steps, (String) stream.getSubject())); } } public boolean chosesTargetSteps() { return false; } public String[] getTargetSteps() { return null; } public void getFields(RowMetaInterface r, String name, RowMetaInterface info[], StepMeta nextStep, VariableSpace space) throws KettleStepException { // We don't have any input fields here in "r" as they are all info fields. // So we just take the info fields. // if (info!=null) { if ( info.length > 0 && info[0]!=null) { r.mergeRowMeta(info[0]); } } } public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info) { CheckResult cr; List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams(); StreamInterface headStream = infoStreams.get(0); StreamInterface tailStream = infoStreams.get(1); if (headStream.getStepname()!=null && tailStream.getStepname()!=null) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "AppendMeta.CheckResult.SourceStepsOK"), stepMeta); remarks.add(cr); } else if (headStream.getStepname()==null && tailStream.getStepname()==null) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString(PKG, "AppendMeta.CheckResult.SourceStepsMissing"), stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "AppendMeta.CheckResult.OneSourceStepMissing"), stepMeta); remarks.add(cr); } } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta tr, Trans trans) { return new Append(stepMeta, stepDataInterface, cnr, tr, trans); } public StepDataInterface getStepData() { return new AppendData(); } /** * Returns the Input/Output metadata for this step. */ public StepIOMetaInterface getStepIOMeta() { if (ioMeta==null) { ioMeta = new StepIOMeta(true, true, false, false, false, false); ioMeta.addStream( new Stream(StreamType.INFO, null, BaseMessages.getString(PKG, "AppendMeta.InfoStream.FirstStream.Description"), StreamIcon.INFO, null) ); ioMeta.addStream( new Stream(StreamType.INFO, null, BaseMessages.getString(PKG, "AppendMeta.InfoStream.SecondStream.Description"), StreamIcon.INFO, null) ); } return ioMeta; } @Override public void resetStepIoMeta() { } public TransformationType[] getSupportedTransformationTypes() { return new TransformationType[] { TransformationType.Normal, }; } }
package org.apache.lucene.util; /* * 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.text.ParseException; import java.util.Locale; /** * Use by certain classes to match version compatibility * across releases of Lucene. * * <p><b>WARNING</b>: When changing the version parameter * that you supply to components in Lucene, do not simply * change the version at search-time, but instead also adjust * your indexing code to match, and re-index. */ public final class Version { /** * Match settings and bugs in Lucene's 4.0.0-ALPHA release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_0_0_ALPHA = new Version(4, 0, 0, 0); /** * Match settings and bugs in Lucene's 4.0.0-BETA release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_0_0_BETA = new Version(4, 0, 0, 1); /** * Match settings and bugs in Lucene's 4.0.0 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_0_0 = new Version(4, 0, 0, 2); /** * Match settings and bugs in Lucene's 4.1.0 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_1_0 = new Version(4, 1, 0); /** * Match settings and bugs in Lucene's 4.2.0 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_2_0 = new Version(4, 2, 0); /** * Match settings and bugs in Lucene's 4.2.1 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_2_1 = new Version(4, 2, 1); /** * Match settings and bugs in Lucene's 4.3.0 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_3_0 = new Version(4, 3, 0); /** * Match settings and bugs in Lucene's 4.3.1 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_3_1 = new Version(4, 3, 1); /** * Match settings and bugs in Lucene's 4.4.0 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_4_0 = new Version(4, 4, 0); /** * Match settings and bugs in Lucene's 4.5.0 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_5_0 = new Version(4, 5, 0); /** * Match settings and bugs in Lucene's 4.5.1 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_5_1 = new Version(4, 5, 1); /** * Match settings and bugs in Lucene's 4.6.0 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_6_0 = new Version(4, 6, 0); /** * Match settings and bugs in Lucene's 4.6.1 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_6_1 = new Version(4, 6, 1); /** * Match settings and bugs in Lucene's 4.7.0 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_7_0 = new Version(4, 7, 0); /** * Match settings and bugs in Lucene's 4.7.1 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_7_1 = new Version(4, 7, 1); /** * Match settings and bugs in Lucene's 4.7.2 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_7_2 = new Version(4, 7, 2); /** * Match settings and bugs in Lucene's 4.8.0 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_8_0 = new Version(4, 8, 0); /** * Match settings and bugs in Lucene's 4.8.1 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_8_1 = new Version(4, 8, 1); /** * Match settings and bugs in Lucene's 4.9.0 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_9_0 = new Version(4, 9, 0); /** * Match settings and bugs in Lucene's 4.9.1 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_9_1 = new Version(4, 9, 1); /** * Match settings and bugs in Lucene's 4.10.0 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_10_0 = new Version(4, 10, 0); /** * Match settings and bugs in Lucene's 4.10.1 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_10_1 = new Version(4, 10, 1); /** * Match settings and bugs in Lucene's 4.10.2 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_10_2 = new Version(4, 10, 2); /** * Match settings and bugs in Lucene's 4.10.3 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_10_3 = new Version(4, 10, 3); /** * Match settings and bugs in Lucene's 4.10.4 release. * @deprecated (5.0) Use latest */ @Deprecated public static final Version LUCENE_4_10_4 = new Version(4, 10, 4); /** Match settings and bugs in Lucene's 5.0 release. * <p> * Use this to get the latest &amp; greatest settings, bug * fixes, etc, for Lucene. * @deprecated (5.1.0) Use latest */ @Deprecated public static final Version LUCENE_5_0_0 = new Version(5, 0, 0); /** * Match settings and bugs in Lucene's 5.1.0 release. * @deprecated (5.2.0) Use latest */ @Deprecated public static final Version LUCENE_5_1_0 = new Version(5, 1, 0); /** * Match settings and bugs in Lucene's 5.2.0 release. */ public static final Version LUCENE_5_2_0 = new Version(5, 2, 0); // To add a new version: // * Only add above this comment // * If the new version is the newest, change LATEST below and deprecate the previous LATEST /** * <p><b>WARNING</b>: if you use this setting, and then * upgrade to a newer release of Lucene, sizable changes * may happen. If backwards compatibility is important * then you should instead explicitly specify an actual * version. * <p> * If you use this constant then you may need to * <b>re-index all of your documents</b> when upgrading * Lucene, as the way text is indexed may have changed. * Additionally, you may need to <b>re-test your entire * application</b> to ensure it behaves as expected, as * some defaults may have changed and may break functionality * in your application. */ public static final Version LATEST = LUCENE_5_2_0; /** * Constant for backwards compatibility. * @deprecated Use {@link #LATEST} */ @Deprecated public static final Version LUCENE_CURRENT = LATEST; /** @deprecated Bad naming of constant; use {@link #LUCENE_4_0_0} instead (this constant actually points to {@link #LUCENE_4_0_0_ALPHA} to match whole 4.0 series). */ @Deprecated public static final Version LUCENE_4_0 = LUCENE_4_0_0_ALPHA; /** @deprecated Bad naming of constant; use {@link #LUCENE_4_1_0} instead. */ @Deprecated public static final Version LUCENE_4_1 = LUCENE_4_1_0; /** @deprecated Bad naming of constant; use {@link #LUCENE_4_2_0} instead. */ @Deprecated public static final Version LUCENE_4_2 = LUCENE_4_2_0; /** @deprecated Bad naming of constant; use {@link #LUCENE_4_3_0} instead. */ @Deprecated public static final Version LUCENE_4_3 = LUCENE_4_3_0; /** @deprecated Bad naming of constant; use {@link #LUCENE_4_4_0} instead. */ @Deprecated public static final Version LUCENE_4_4 = LUCENE_4_4_0; /** @deprecated Bad naming of constant; use {@link #LUCENE_4_5_0} instead. */ @Deprecated public static final Version LUCENE_4_5 = LUCENE_4_5_0; /** @deprecated Bad naming of constant; use {@link #LUCENE_4_6_0} instead. */ @Deprecated public static final Version LUCENE_4_6 = LUCENE_4_6_0; /** @deprecated Bad naming of constant; use {@link #LUCENE_4_7_0} instead. */ @Deprecated public static final Version LUCENE_4_7 = LUCENE_4_7_0; /** @deprecated Bad naming of constant; use {@link #LUCENE_4_8_0} instead. */ @Deprecated public static final Version LUCENE_4_8 = LUCENE_4_8_0; /** @deprecated Bad naming of constant; use {@link #LUCENE_4_9_0} instead. */ @Deprecated public static final Version LUCENE_4_9 = LUCENE_4_9_0; /** * Parse a version number of the form {@code "major.minor.bugfix.prerelease"}. * * Part {@code ".bugfix"} and part {@code ".prerelease"} are optional. * Note that this is forwards compatible: the parsed version does not have to exist as * a constant. * * @lucene.internal */ public static Version parse(String version) throws ParseException { StrictStringTokenizer tokens = new StrictStringTokenizer(version, '.'); if (tokens.hasMoreTokens() == false) { throw new ParseException("Version is not in form major.minor.bugfix(.prerelease) (got: " + version + ")", 0); } int major; String token = tokens.nextToken(); try { major = Integer.parseInt(token); } catch (NumberFormatException nfe) { ParseException p = new ParseException("Failed to parse major version from \"" + token + "\" (got: " + version + ")", 0); p.initCause(nfe); throw p; } if (tokens.hasMoreTokens() == false) { throw new ParseException("Version is not in form major.minor.bugfix(.prerelease) (got: " + version + ")", 0); } int minor; token = tokens.nextToken(); try { minor = Integer.parseInt(token); } catch (NumberFormatException nfe) { ParseException p = new ParseException("Failed to parse minor version from \"" + token + "\" (got: " + version + ")", 0); p.initCause(nfe); throw p; } int bugfix = 0; int prerelease = 0; if (tokens.hasMoreTokens()) { token = tokens.nextToken(); try { bugfix = Integer.parseInt(token); } catch (NumberFormatException nfe) { ParseException p = new ParseException("Failed to parse bugfix version from \"" + token + "\" (got: " + version + ")", 0); p.initCause(nfe); throw p; } if (tokens.hasMoreTokens()) { token = tokens.nextToken(); try { prerelease = Integer.parseInt(token); } catch (NumberFormatException nfe) { ParseException p = new ParseException("Failed to parse prerelease version from \"" + token + "\" (got: " + version + ")", 0); p.initCause(nfe); throw p; } if (prerelease == 0) { throw new ParseException("Invalid value " + prerelease + " for prerelease; should be 1 or 2 (got: " + version + ")", 0); } if (tokens.hasMoreTokens()) { // Too many tokens! throw new ParseException("Version is not in form major.minor.bugfix(.prerelease) (got: " + version + ")", 0); } } } try { return new Version(major, minor, bugfix, prerelease); } catch (IllegalArgumentException iae) { ParseException pe = new ParseException("failed to parse version string \"" + version + "\": " + iae.getMessage(), 0); pe.initCause(iae); throw pe; } } /** * Parse the given version number as a constant or dot based version. * <p>This method allows to use {@code "LUCENE_X_Y"} constant names, * or version numbers in the format {@code "x.y.z"}. * * @lucene.internal */ public static Version parseLeniently(String version) throws ParseException { String versionOrig = version; version = version.toUpperCase(Locale.ROOT); switch (version) { case "LATEST": case "LUCENE_CURRENT": return LATEST; case "LUCENE_4_0_0": return LUCENE_4_0_0; case "LUCENE_4_0_0_ALPHA": return LUCENE_4_0_0_ALPHA; case "LUCENE_4_0_0_BETA": return LUCENE_4_0_0_BETA; default: version = version .replaceFirst("^LUCENE_(\\d+)_(\\d+)_(\\d+)$", "$1.$2.$3") .replaceFirst("^LUCENE_(\\d+)_(\\d+)$", "$1.$2.0") .replaceFirst("^LUCENE_(\\d)(\\d)$", "$1.$2.0"); try { return parse(version); } catch (ParseException pe) { ParseException pe2 = new ParseException("failed to parse lenient version string \"" + versionOrig + "\": " + pe.getMessage(), 0); pe2.initCause(pe); throw pe2; } } } /** Returns a new version based on raw numbers * * @lucene.internal */ public static Version fromBits(int major, int minor, int bugfix) { return new Version(major, minor, bugfix); } /** Major version, the difference between stable and trunk */ public final int major; /** Minor version, incremented within the stable branch */ public final int minor; /** Bugfix number, incremented on release branches */ public final int bugfix; /** Prerelease version, currently 0 (alpha), 1 (beta), or 2 (final) */ public final int prerelease; // stores the version pieces, with most significant pieces in high bits // ie: | 1 byte | 1 byte | 1 byte | 2 bits | // major minor bugfix prerelease private final int encodedValue; private Version(int major, int minor, int bugfix) { this(major, minor, bugfix, 0); } private Version(int major, int minor, int bugfix, int prerelease) { this.major = major; this.minor = minor; this.bugfix = bugfix; this.prerelease = prerelease; // NOTE: do not enforce major version so we remain future proof, except to // make sure it fits in the 8 bits we encode it into: if (major > 255 || major < 0) { throw new IllegalArgumentException("Illegal major version: " + major); } if (minor > 255 || minor < 0) { throw new IllegalArgumentException("Illegal minor version: " + minor); } if (bugfix > 255 || bugfix < 0) { throw new IllegalArgumentException("Illegal bugfix version: " + bugfix); } if (prerelease > 2 || prerelease < 0) { throw new IllegalArgumentException("Illegal prerelease version: " + prerelease); } if (prerelease != 0 && (minor != 0 || bugfix != 0)) { throw new IllegalArgumentException("Prerelease version only supported with major release (got prerelease: " + prerelease + ", minor: " + minor + ", bugfix: " + bugfix + ")"); } encodedValue = major << 18 | minor << 10 | bugfix << 2 | prerelease; assert encodedIsValid(); } /** * Returns true if this version is the same or after the version from the argument. */ public boolean onOrAfter(Version other) { return encodedValue >= other.encodedValue; } @Override public String toString() { if (prerelease == 0) { return "" + major + "." + minor + "." + bugfix; } return "" + major + "." + minor + "." + bugfix + "." + prerelease; } @Override public boolean equals(Object o) { return o != null && o instanceof Version && ((Version)o).encodedValue == encodedValue; } // Used only by assert: private boolean encodedIsValid() { assert major == ((encodedValue >>> 18) & 0xFF); assert minor == ((encodedValue >>> 10) & 0xFF); assert bugfix == ((encodedValue >>> 2) & 0xFF); assert prerelease == (encodedValue & 0x03); return true; } @Override public int hashCode() { return encodedValue; } }
/* * Copyright (c) 2010-2017 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.model.impl.sync; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; import org.testng.annotations.Test; import com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.PropertyDelta; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConditionalSearchFilterType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectSynchronizationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestCorrelationConfiramtionEvaluator extends AbstractInternalModelIntegrationTest{ private static final String TEST_DIR = "src/test/resources/sync"; private static final String CORRELATION_OR_FILTER = TEST_DIR + "/correlation-or-filter.xml"; private static final String CORRELATION_CASE_INSENSITIVE = TEST_DIR + "/correlation-case-insensitive.xml"; private static final String CORRELATION_CASE_INSENSITIVE_EMPL_NUMBER = TEST_DIR + "/correlation-case-insensitive_empl_number.xml"; private static final String CORRELATION_FIRST_FILTER = TEST_DIR + "/correlation-first-filter.xml"; private static final String CORRELATION_SECOND_FILTER = TEST_DIR + "/correlation-second-filter.xml"; private static final String CORRELATION_WITH_CONDITION = TEST_DIR + "/correlation-with-condition.xml"; private static final String CORRELATION_WITH_CONDITION_EMPL_NUMBER = TEST_DIR + "/correlation-with-condition-emplNumber.xml"; @Autowired(required=true) private RepositoryService repositoryService; @Autowired(required = true) private CorrelationConfirmationEvaluator evaluator; @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { // super.initSystem(initTask, initResult); // Administrator userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, initResult); repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); login(userAdministrator); } @Test public void test001CorrelationOrFilter() throws Exception{ String TEST_NAME = "test001CorrelationOrFilter"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); importObjectFromFile(USER_JACK_FILE); PrismObject<UserType> userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); ConditionalSearchFilterType filter = PrismTestUtil.parseAtomicValue(new File(CORRELATION_OR_FILTER), ConditionalSearchFilterType.COMPLEX_TYPE); List<ConditionalSearchFilterType> filters = new ArrayList<>(); filters.add(filter); ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); IntegrationTestTools.display("Queries", filters); // WHEN List<PrismObject<UserType>> matchedUsers = evaluator.findFocusesByCorrelationRule(UserType.class, shadow, filters, resourceType, getSystemConfiguration(), task, result); // THEN assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); assertEquals("Found more than one user.", 1, matchedUsers.size()); PrismObject<UserType> jack = matchedUsers.get(0); assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "jack", "Jack Sparrow", "Jack", "Sparrow"); } @Test public void test002CorrelationMoreThanOne() throws Exception{ String TEST_NAME = "test002CorrelationMoreThanOne"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); // importObjectFromFile(USER_JACK_FILENAME); PrismObject<UserType> userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); List<ConditionalSearchFilterType> filters = new ArrayList<>(); ConditionalSearchFilterType filter = PrismTestUtil.parseAtomicValue(new File(CORRELATION_FIRST_FILTER), ConditionalSearchFilterType.COMPLEX_TYPE); filters.add(filter); filter = PrismTestUtil.parseAtomicValue(new File(CORRELATION_SECOND_FILTER), ConditionalSearchFilterType.COMPLEX_TYPE); filters.add(filter); ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); List<PrismObject<UserType>> matchedUsers = evaluator.findFocusesByCorrelationRule(UserType.class, shadow, filters, resourceType, getSystemConfiguration(), task, result); assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); assertEquals("Found more than one user.", 1, matchedUsers.size()); PrismObject<UserType> jack = matchedUsers.get(0); assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "jack", "Jack Sparrow", "Jack", "Sparrow"); } @Test public void test003CorrelationWithCondition() throws Exception{ String TEST_NAME = "test003CorrelationWithCondition"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); // importObjectFromFile(USER_JACK_FILENAME); PrismObject<UserType> userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); List<ConditionalSearchFilterType> queries = new ArrayList<>(); ConditionalSearchFilterType query = PrismTestUtil.parseAtomicValue(new File(CORRELATION_WITH_CONDITION), ConditionalSearchFilterType.COMPLEX_TYPE); queries.add(query); query = PrismTestUtil.parseAtomicValue(new File(CORRELATION_WITH_CONDITION_EMPL_NUMBER), ConditionalSearchFilterType.COMPLEX_TYPE); queries.add(query); ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); List<PrismObject<UserType>> matchedUsers = evaluator.findFocusesByCorrelationRule(UserType.class, shadow, queries, resourceType, getSystemConfiguration(), task, result); assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); assertEquals("Found more than one user.", 1, matchedUsers.size()); PrismObject<UserType> jack = matchedUsers.get(0); assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "jack", "Jack Sparrow", "Jack", "Sparrow"); } @Test public void test004CorrelationMatchCaseInsensitive() throws Exception{ String TEST_NAME = "test004CorrelationMatchCaseInsensitive"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); // importObjectFromFile(USER_JACK_FILENAME); PrismObject<UserType> userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); ConditionalSearchFilterType query = PrismTestUtil.parseAtomicValue(new File(CORRELATION_CASE_INSENSITIVE), ConditionalSearchFilterType.COMPLEX_TYPE); // List<QueryType> queries = new ArrayList<QueryType>(); // queries.add(query); // ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); resourceType.getSynchronization().getObjectSynchronization().get(0).getCorrelation().clear(); resourceType.getSynchronization().getObjectSynchronization().get(0).getCorrelation().add(query); userType.asObjectable().setName(new PolyStringType("JACK")); ObjectSynchronizationType objectSynchronizationType = resourceType.getSynchronization().getObjectSynchronization().get(0); try{ boolean matchedUsers = evaluator.matchUserCorrelationRule(UserType.class, shadow.asPrismObject(), userType, objectSynchronizationType, resourceType, getSystemConfiguration(), task, result); System.out.println("matched users " + matchedUsers); AssertJUnit.assertTrue(matchedUsers); } catch (Exception ex){ LOGGER.error("exception occured: {}", ex.getMessage(), ex); throw ex; } // assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); // assertEquals("Found more than one user.", 1, matchedUsers.size()); // // PrismObject<UserType> jack = matchedUsers.get(0); // assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "jack", "Jack Sparrow", "Jack", "Sparrow"); } @Test public void test005CorrelationMatchCaseInsensitive() throws Exception{ String TEST_NAME = "test005CorrelationMatchCaseInsensitive"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); // importObjectFromFile(USER_JACK_FILENAME); PrismObject<UserType> userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); ConditionalSearchFilterType query = PrismTestUtil.parseAtomicValue(new File(CORRELATION_CASE_INSENSITIVE_EMPL_NUMBER), ConditionalSearchFilterType.COMPLEX_TYPE); // ObjectQuery query = ObjectQuery.createObjectQuery(EqualsFilter.createEqual(null, userType.getDefinition().findItemDefinition(UserType.F_EMPLOYEE_NUMBER), "stringIgnoreCase", "ps1234")); // List<QueryType> queries = new ArrayList<QueryType>(); // queries.add(query); // ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); resourceType.getSynchronization().getObjectSynchronization().get(0).getCorrelation().clear(); resourceType.getSynchronization().getObjectSynchronization().get(0).getCorrelation().add(query); userType.asObjectable().setEmployeeNumber("JaCk"); ObjectSynchronizationType objectSynchronizationType = resourceType.getSynchronization().getObjectSynchronization().get(0); try{ boolean matchedUsers = evaluator.matchUserCorrelationRule(UserType.class, shadow.asPrismObject(), userType, objectSynchronizationType, resourceType, getSystemConfiguration(), task, result); System.out.println("matched users " + matchedUsers); AssertJUnit.assertTrue(matchedUsers); } catch (Exception ex){ LOGGER.error("exception occured: {}", ex.getMessage(), ex); throw ex; } // assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); // assertEquals("Found more than one user.", 1, matchedUsers.size()); // // PrismObject<UserType> jack = matchedUsers.get(0); // assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "jack", "Jack Sparrow", "Jack", "Sparrow"); } @Test public void test006CorrelationFindCaseInsensitive() throws Exception{ String TEST_NAME = "test006CorrelationFindCaseInsensitive"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); // importObjectFromFile(USER_JACK_FILENAME); PrismObject<UserType> userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); ConditionalSearchFilterType query = PrismTestUtil.parseAtomicValue(new File(CORRELATION_CASE_INSENSITIVE), ConditionalSearchFilterType.COMPLEX_TYPE); List<ConditionalSearchFilterType> queries = new ArrayList<>(); queries.add(query); // ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); // resourceType.getSynchronization().getObjectSynchronization().get(0).getCorrelation().add(query); userType.asObjectable().setName(new PolyStringType("JACK")); Collection<? extends ItemDelta> modifications = PropertyDelta.createModificationReplacePropertyCollection(UserType.F_NAME, userType.getDefinition(), new PolyString("JACK", "jack")); repositoryService.modifyObject(UserType.class, USER_JACK_OID, modifications, result); List<PrismObject<UserType>> matchedUsers = evaluator.findFocusesByCorrelationRule(UserType.class, shadow, queries, resourceType, getSystemConfiguration(), task, result); System.out.println("matched users " + matchedUsers); assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); assertEquals("Found more than one user.", 1, matchedUsers.size()); PrismObject<UserType> jack = matchedUsers.get(0); assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "JACK", "Jack Sparrow", "Jack", "Sparrow"); } }
package im.actor.messenger.app.core; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.SoundPool; import android.support.v4.app.NotificationCompat; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.text.SpannableStringBuilder; import android.text.style.StyleSpan; import org.jetbrains.annotations.NotNull; import java.util.List; import im.actor.core.Messenger; import im.actor.core.NotificationProvider; import im.actor.core.entity.Avatar; import im.actor.core.entity.Notification; import im.actor.core.entity.Peer; import im.actor.core.entity.PeerType; import im.actor.core.viewmodel.FileVMCallback; import im.actor.messenger.R; import im.actor.messenger.app.Intents; import im.actor.messenger.app.activity.MainActivity; import im.actor.messenger.app.util.Screen; import im.actor.messenger.app.view.AvatarPlaceholderDrawable; import im.actor.runtime.files.FileSystemReference; import static im.actor.messenger.app.core.Core.groups; import static im.actor.messenger.app.core.Core.users; /** * Created by ex3ndr on 01.03.15. */ public class AndroidNotifications implements NotificationProvider { private static final int NOTIFICATION_ID = 1; private SoundPool soundPool; private int soundId; private Peer visiblePeer; private Context context; public AndroidNotifications(Context context) { this.context = context; soundPool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 0); soundId = soundPool.load(context, R.raw.notification, 1); } @Override public void onMessageArriveInApp(Messenger messenger) { soundPool.play(soundId, 1.0f, 1.0f, 0, 0, 1.0f); } @Override public void onNotification(Messenger messenger, List<Notification> topNotifications, int messagesCount, int conversationsCount, boolean isInApp) { // Android ignores isInApp argument because it is ok to send normal notification // instead in-app final NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setAutoCancel(true); builder.setSmallIcon(R.drawable.ic_app_notify); if (isInApp) { builder.setPriority(NotificationCompat.PRIORITY_HIGH); } else { builder.setPriority(NotificationCompat.PRIORITY_DEFAULT); } builder.setCategory(NotificationCompat.CATEGORY_MESSAGE); int defaults = NotificationCompat.DEFAULT_LIGHTS; if (messenger.isNotificationSoundEnabled()) { defaults |= NotificationCompat.DEFAULT_SOUND; } if (messenger.isNotificationVibrationEnabled()) { defaults |= NotificationCompat.DEFAULT_VIBRATE; } // if (silentUpdate) { // defaults = 0; // } builder.setDefaults(defaults); // Wearable // builder.extend(new NotificationCompat.WearableExtender() // .setBackground(((BitmapDrawable) AppContext.getContext().getResources().getDrawable(R.drawable.wear_bg)).getBitmap()) // .setHintHideIcon(true)); final Notification topNotification = topNotifications.get(0); // if (!silentUpdate) { // builder.setTicker(getNotificationTextFull(topNotification, messenger)); // } android.app.Notification result; if (messagesCount == 1) { // Single message notification final String sender = getNotificationSender(topNotification); // final CharSequence text = bypass.markdownToSpannable(messenger().getFormatter().formatNotificationText(topNotification), true).toString(); final CharSequence text = messenger.getFormatter().formatNotificationText(topNotification); visiblePeer = topNotification.getPeer(); Avatar avatar = null; int id = 0; String avatarTitle = ""; switch (visiblePeer.getPeerType()) { case PRIVATE: avatar = users().get(visiblePeer.getPeerId()).getAvatar().get(); id = users().get(visiblePeer.getPeerId()).getId(); avatarTitle = users().get(visiblePeer.getPeerId()).getName().get(); break; case GROUP: avatar = groups().get(visiblePeer.getPeerId()).getAvatar().get(); id = groups().get(visiblePeer.getPeerId()).getId(); avatarTitle = groups().get(visiblePeer.getPeerId()).getName().get(); break; } Drawable avatarDrawable = new AvatarPlaceholderDrawable(avatarTitle, id, 18, context); result = buildSingleMessageNotification(avatarDrawable, builder, sender, text, topNotification); final NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, result); if (avatar != null && avatar.getSmallImage() != null && avatar.getSmallImage().getFileReference() != null) { messenger.bindFile(avatar.getSmallImage().getFileReference(), true, new FileVMCallback() { @Override public void onNotDownloaded() { } @Override public void onDownloading(float progress) { } @Override public void onDownloaded(FileSystemReference reference) { RoundedBitmapDrawable d = getRoundedBitmapDrawable(reference); android.app.Notification result = buildSingleMessageNotification(d, builder, sender, text, topNotification); //NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, result); } }); } else { manager.notify(NOTIFICATION_ID, result); } } else if (conversationsCount == 1) { // Single conversation notification String sender = getNotificationSender(topNotification); builder.setContentTitle(sender); builder.setContentText(messagesCount + " messages"); visiblePeer = topNotification.getPeer(); builder.setContentIntent(PendingIntent.getActivity(context, 0, Intents.openDialog(topNotification.getPeer(), false, context), PendingIntent.FLAG_UPDATE_CURRENT)); final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); for (Notification n : topNotifications) { if (topNotification.getPeer().getPeerType() == PeerType.GROUP) { inboxStyle.addLine(getNotificationTextFull(n, messenger)); } else { inboxStyle.addLine(messenger.getFormatter().formatNotificationText(n)); } } inboxStyle.setSummaryText(messagesCount + " messages"); Avatar avatar = null; int id = 0; String avatarTitle = ""; switch (visiblePeer.getPeerType()) { case PRIVATE: avatar = users().get(visiblePeer.getPeerId()).getAvatar().get(); id = users().get(visiblePeer.getPeerId()).getId(); avatarTitle = users().get(visiblePeer.getPeerId()).getName().get(); break; case GROUP: avatar = groups().get(visiblePeer.getPeerId()).getAvatar().get(); id = groups().get(visiblePeer.getPeerId()).getId(); avatarTitle = groups().get(visiblePeer.getPeerId()).getName().get(); break; } Drawable avatarDrawable = new AvatarPlaceholderDrawable(avatarTitle, id, 18, context); result = buildSingleConversationNotification(builder, inboxStyle, avatarDrawable); final NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, result); if (avatar != null && avatar.getSmallImage() != null && avatar.getSmallImage().getFileReference() != null) { messenger.bindFile(avatar.getSmallImage().getFileReference(), true, new FileVMCallback() { @Override public void onNotDownloaded() { } @Override public void onDownloading(float progress) { } @Override public void onDownloaded(FileSystemReference reference) { RoundedBitmapDrawable d = getRoundedBitmapDrawable(reference); android.app.Notification result = buildSingleConversationNotification(builder, inboxStyle, d); manager.notify(NOTIFICATION_ID, result); } }); } else { manager.notify(NOTIFICATION_ID, result); } } else { // Multiple conversations notification builder.setContentTitle(context.getString(R.string.app_name)); builder.setContentText(messagesCount + " messages in " + conversationsCount + " chats"); visiblePeer = null; builder.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT)); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); for (Notification n : topNotifications) { inboxStyle.addLine(getNotificationTextFull(n, messenger)); } inboxStyle.setSummaryText(messagesCount + " messages in " + conversationsCount + " chats"); result = builder .setStyle(inboxStyle) .build(); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, result); } } @Override public void onUpdateNotification(Messenger messenger, List<Notification> topNotifications, int messagesCount, int conversationsCount) { // TODO: Implement } @Override public void hideAllNotifications() { NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.cancel(NOTIFICATION_ID); } @NotNull private RoundedBitmapDrawable getRoundedBitmapDrawable(FileSystemReference reference) { Bitmap b = BitmapFactory.decodeFile(reference.getDescriptor()); RoundedBitmapDrawable d = RoundedBitmapDrawableFactory.create(context.getResources(), Bitmap.createScaledBitmap(b, Screen.dp(55), Screen.dp(55), false)); d.setCornerRadius(d.getIntrinsicHeight() / 2); d.setAntiAlias(true); return d; } private android.app.Notification buildSingleConversationNotification(NotificationCompat.Builder builder, NotificationCompat.InboxStyle inboxStyle, Drawable avatarDrawable) { return builder .setLargeIcon(drawableToBitmap(avatarDrawable)) .setStyle(inboxStyle) .build(); } private android.app.Notification buildSingleMessageNotification(Drawable d, NotificationCompat.Builder builder, String sender, CharSequence text, Notification topNotification) { return builder .setContentTitle(sender) .setContentText(text) .setLargeIcon(drawableToBitmap(d)) .setContentIntent(PendingIntent.getActivity(context, 0, Intents.openDialog(topNotification.getPeer(), false, context), PendingIntent.FLAG_UPDATE_CURRENT)) .setStyle(new NotificationCompat.BigTextStyle().bigText(text)) .build(); } public static Bitmap drawableToBitmap(Drawable drawable) { int height = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(height > 0 ? height : Screen.dp(55), height > 0 ? height : Screen.dp(55), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } private CharSequence getNotificationTextFull(Notification notification, Messenger messenger) { SpannableStringBuilder res = new SpannableStringBuilder(); if (!messenger.getFormatter().isLargeDialogMessage(notification.getContentDescription().getContentType())) { res.append(getNotificationSender(notification)); res.append(": "); res.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, res.length(), 0); } res.append(messenger.getFormatter().formatNotificationText(notification)); return res; } private String getNotificationSender(Notification pendingNotification) { String sender; if (pendingNotification.getPeer().getPeerType() == PeerType.GROUP) { sender = users().get(pendingNotification.getSender()).getName().get(); sender += "@"; sender += groups().get(pendingNotification.getPeer().getPeerId()).getName().get(); } else { sender = users().get(pendingNotification.getSender()).getName().get(); } return sender; } }
/** * */ package io.sinistral.proteus.openapi.jaxrs2; /** * @author jbauer */ import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import com.fasterxml.jackson.databind.introspect.AnnotatedParameter; import com.fasterxml.jackson.databind.type.TypeFactory; import io.sinistral.proteus.annotations.Chain; import io.sinistral.proteus.server.ServerRequest; import io.sinistral.proteus.server.ServerResponse; import io.sinistral.proteus.wrappers.JsonViewWrapper; import io.swagger.v3.core.converter.AnnotatedType; import io.swagger.v3.core.converter.ModelConverters; import io.swagger.v3.core.converter.ResolvedSchema; import io.swagger.v3.core.util.*; import io.swagger.v3.jaxrs2.OperationParser; import io.swagger.v3.jaxrs2.ReaderListener; import io.swagger.v3.jaxrs2.ResolvedParameter; import io.swagger.v3.jaxrs2.SecurityParser; import io.swagger.v3.jaxrs2.ext.OpenAPIExtension; import io.swagger.v3.jaxrs2.ext.OpenAPIExtensions; import io.swagger.v3.jaxrs2.util.ReaderUtils; import io.swagger.v3.oas.annotations.ExternalDocumentation; import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.OpenAPIDefinition; import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.integration.SwaggerConfiguration; import io.swagger.v3.oas.integration.api.OpenAPIConfiguration; import io.swagger.v3.oas.models.*; import io.swagger.v3.oas.models.callbacks.Callback; import io.swagger.v3.oas.models.media.Content; import io.swagger.v3.oas.models.media.MediaType; import io.swagger.v3.oas.models.media.ObjectSchema; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.parameters.RequestBody; import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.oas.models.responses.ApiResponses; import io.swagger.v3.oas.models.security.SecurityRequirement; import io.swagger.v3.oas.models.security.SecurityScheme; import io.swagger.v3.oas.models.tags.Tag; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpServerExchange; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.ApplicationPath; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Application; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; public class Reader extends io.swagger.v3.jaxrs2.Reader { private static final Logger LOGGER = LoggerFactory.getLogger(Reader.class); public static final String DEFAULT_MEDIA_TYPE_VALUE = "*/*"; public static final String DEFAULT_DESCRIPTION = "default response"; protected OpenAPIConfiguration config; private Application application; private OpenAPI openAPI; private Components components; private Paths paths; private Set<Tag> openApiTags; private static final String GET_METHOD = "get"; private static final String POST_METHOD = "post"; private static final String PUT_METHOD = "put"; private static final String DELETE_METHOD = "delete"; private static final String PATCH_METHOD = "patch"; private static final String TRACE_METHOD = "trace"; private static final String HEAD_METHOD = "head"; private static final String OPTIONS_METHOD = "options"; private Schema stringSchema; public Reader() { // Json.mapper().addMixIn(ServerRequest.class, ServerRequestMixIn.class); this.openAPI = new OpenAPI(); paths = new Paths(); openApiTags = new LinkedHashSet<>(); components = new Components(); stringSchema = new Schema(); stringSchema.setType("string"); } public Reader(OpenAPI openAPI) { this(); setConfiguration(new SwaggerConfiguration().openAPI(openAPI)); } public Reader(OpenAPIConfiguration openApiConfiguration) { this(); setConfiguration(openApiConfiguration); } public OpenAPI getOpenAPI() { return openAPI; } /** * Scans a single class for Swagger annotations - does not invoke * ReaderListeners */ public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); } /** * Scans a set of classes for both ReaderListeners and OpenAPI annotations. * All found listeners will * be instantiated before any of the classes are scanned for OpenAPI * annotations - so they can be invoked * accordingly. * @param classes * a set of classes to scan * @return the generated OpenAPI definition */ public OpenAPI read(Set<Class<?>> classes) { Set<Class<?>> sortedClasses = new TreeSet<>(new Comparator<Class<?>>() { @Override public int compare(Class<?> class1, Class<?> class2) { if (class1.equals(class2)) { return 0; } else if (class1.isAssignableFrom(class2)) { return -1; } else if (class2.isAssignableFrom(class1)) { return 1; } return class1.getName().compareTo(class2.getName()); } }); sortedClasses.addAll(classes); Map<Class<?>, ReaderListener> listeners = new HashMap<>(); for (Class<?> cls : sortedClasses) { if (ReaderListener.class.isAssignableFrom(cls) && !listeners.containsKey(cls)) { try { listeners.put(cls, (ReaderListener) cls.newInstance()); } catch (Exception e) { LOGGER.error("Failed to create ReaderListener", e); } } } for (ReaderListener listener : listeners.values()) { try { listener.beforeScan(this, openAPI); } catch (Exception e) { LOGGER.error("Unexpected error invoking beforeScan listener [" + listener.getClass().getName() + "]", e); } } for (Class<?> cls : sortedClasses) { read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); } for (ReaderListener listener : listeners.values()) { try { listener.afterScan(this, openAPI); } catch (Exception e) { LOGGER.error("Unexpected error invoking afterScan listener [" + listener.getClass().getName() + "]", e); } } return openAPI; } public static OpenAPIConfiguration deepCopy(OpenAPIConfiguration config) { if (config == null) { return null; } try { return Json.mapper().readValue(Json.pretty(config), SwaggerConfiguration.class); } catch (Exception e) { LOGGER.error("Exception cloning config: " + e.getMessage(), e); return config; } } @Override public void setConfiguration(OpenAPIConfiguration openApiConfiguration) { if (openApiConfiguration != null) { this.config = deepCopy(openApiConfiguration); if (openApiConfiguration.getOpenAPI() != null) { this.openAPI = this.config.getOpenAPI(); if (this.openAPI.getComponents() != null) { this.components = this.openAPI.getComponents(); } } } } public OpenAPI read(Set<Class<?>> classes, Map<String, Object> resources) { return read(classes); } protected String resolveApplicationPath() { if (application != null) { Class<?> applicationToScan = this.application.getClass(); ApplicationPath applicationPath; // search up in the hierarchy until we find one with the annotation, // this is needed because for example Weld proxies will not have the // annotation and the right class will be the superClass while ((applicationPath = applicationToScan.getAnnotation(ApplicationPath.class)) == null && !applicationToScan.getSuperclass().equals(Application.class)) { applicationToScan = applicationToScan.getSuperclass(); } if (applicationPath != null) { if (StringUtils.isNotBlank(applicationPath.value())) { return applicationPath.value(); } } // look for inner application, e.g. ResourceConfig try { Application innerApp = application; Method m = application.getClass().getMethod("getApplication", null); while (m != null) { Application retrievedApp = (Application) m.invoke(innerApp, null); if (retrievedApp == null) { break; } if (retrievedApp.getClass().equals(innerApp.getClass())) { break; } innerApp = retrievedApp; applicationPath = innerApp.getClass().getAnnotation(ApplicationPath.class); if (applicationPath != null) { if (StringUtils.isNotBlank(applicationPath.value())) { return applicationPath.value(); } } m = innerApp.getClass().getMethod("getApplication", null); } } catch (NoSuchMethodException e) { // no inner application found } catch (Exception e) { // no inner application found } } return ""; } public OpenAPI read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource, RequestBody parentRequestBody, ApiResponses parentResponses, Set<String> parentTags, List<Parameter> parentParameters, Set<Class<?>> scannedResources) { Hidden hidden = cls.getAnnotation(Hidden.class); // class path final javax.ws.rs.Path apiPath = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class); if (hidden != null) { // || (apiPath == null && !isSubresource)) { return openAPI; } io.swagger.v3.oas.annotations.responses.ApiResponse[] classResponses = ReflectionUtils .getRepeatableAnnotationsArray(cls, io.swagger.v3.oas.annotations.responses.ApiResponse.class); List<io.swagger.v3.oas.annotations.security.SecurityScheme> apiSecurityScheme = ReflectionUtils .getRepeatableAnnotations(cls, io.swagger.v3.oas.annotations.security.SecurityScheme.class); List<io.swagger.v3.oas.annotations.security.SecurityRequirement> apiSecurityRequirements = ReflectionUtils .getRepeatableAnnotations(cls, io.swagger.v3.oas.annotations.security.SecurityRequirement.class); ExternalDocumentation apiExternalDocs = ReflectionUtils.getAnnotation(cls, ExternalDocumentation.class); io.swagger.v3.oas.annotations.tags.Tag[] apiTags = ReflectionUtils.getRepeatableAnnotationsArray(cls, io.swagger.v3.oas.annotations.tags.Tag.class); Server[] apiServers = ReflectionUtils.getRepeatableAnnotationsArray(cls, Server.class); Consumes classConsumes = ReflectionUtils.getAnnotation(cls, Consumes.class); Produces classProduces = ReflectionUtils.getAnnotation(cls, Produces.class); // OpenApiDefinition OpenAPIDefinition openAPIDefinition = ReflectionUtils.getAnnotation(cls, OpenAPIDefinition.class); if (openAPIDefinition != null) { // info AnnotationsUtils.getInfo(openAPIDefinition.info()).ifPresent(info -> openAPI.setInfo(info)); // OpenApiDefinition security requirements SecurityParser .getSecurityRequirements(openAPIDefinition.security()) .ifPresent(s -> openAPI.setSecurity(s)); // // OpenApiDefinition external docs AnnotationsUtils .getExternalDocumentation(openAPIDefinition.externalDocs()) .ifPresent(docs -> openAPI.setExternalDocs(docs)); // OpenApiDefinition tags AnnotationsUtils .getTags(openAPIDefinition.tags(), false) .ifPresent(tags -> openApiTags.addAll(tags)); // OpenApiDefinition servers AnnotationsUtils.getServers(openAPIDefinition.servers()).ifPresent(servers -> openAPI.setServers(servers)); // OpenApiDefinition extensions if (openAPIDefinition.extensions().length > 0) { openAPI.setExtensions(AnnotationsUtils .getExtensions(openAPIDefinition.extensions())); } } // class security schemes if (apiSecurityScheme != null) { for (io.swagger.v3.oas.annotations.security.SecurityScheme securitySchemeAnnotation : apiSecurityScheme) { Optional<SecurityParser.SecuritySchemePair> securityScheme = SecurityParser.getSecurityScheme(securitySchemeAnnotation); if (securityScheme.isPresent()) { Map<String, SecurityScheme> securitySchemeMap = new HashMap<>(); if (StringUtils.isNotBlank(securityScheme.get().key)) { securitySchemeMap.put(securityScheme.get().key, securityScheme.get().securityScheme); if (components.getSecuritySchemes() != null && components.getSecuritySchemes().size() != 0) { components.getSecuritySchemes().putAll(securitySchemeMap); } else { components.setSecuritySchemes(securitySchemeMap); } } } } } // class security requirements List<SecurityRequirement> classSecurityRequirements = new ArrayList<>(); if (apiSecurityRequirements != null) { Optional<List<SecurityRequirement>> requirementsObject = SecurityParser.getSecurityRequirements( apiSecurityRequirements.toArray( new io.swagger.v3.oas.annotations.security.SecurityRequirement[apiSecurityRequirements .size()])); if (requirementsObject.isPresent()) { classSecurityRequirements = requirementsObject.get(); } } // class tags, consider only name to add to class operations final Set<String> classTags = new LinkedHashSet<>(); if (apiTags != null) { AnnotationsUtils .getTags(apiTags, false).ifPresent(tags -> tags .stream() .map(t -> t.getName()) .forEach(t -> classTags.add(t))); } // parent tags if (isSubresource) { if (parentTags != null) { classTags.addAll(parentTags); } } // servers final List<io.swagger.v3.oas.models.servers.Server> classServers = new ArrayList<>(); if (apiServers != null) { AnnotationsUtils.getServers(apiServers).ifPresent(servers -> classServers.addAll(servers)); } // class external docs Optional<io.swagger.v3.oas.models.ExternalDocumentation> classExternalDocumentation = AnnotationsUtils.getExternalDocumentation(apiExternalDocs); JavaType classType = TypeFactory.defaultInstance().constructType(cls); BeanDescription bd = Json.mapper().getSerializationConfig().introspect(classType); final List<Parameter> globalParameters = new ArrayList<>(); // look for constructor-level annotated properties globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, components, classConsumes, null)); // look for field-level annotated properties globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, components, classConsumes, null)); // iterate class methods Method[] methods = cls.getMethods(); for (Method method : methods) { if (isOperationHidden(method)) { continue; } Class<?>[] parameterTypes = Arrays.stream(method.getParameterTypes()).filter(p -> !p.isAssignableFrom(ServerRequest.class)).toArray(Class<?>[]::new); AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), parameterTypes); Produces methodProduces = ReflectionUtils.getAnnotation(method, Produces.class); Consumes methodConsumes = ReflectionUtils.getAnnotation(method, Consumes.class); if (ReflectionUtils.isOverriddenMethod(method, cls)) { continue; } javax.ws.rs.Path methodPath = ReflectionUtils.getAnnotation(method, javax.ws.rs.Path.class); String operationPath = ReaderUtils.getPath(apiPath, methodPath, parentPath, isSubresource); // skip if path is the same as parent, e.g. for @ApplicationPath // annotated application // extending resource config. if (ignoreOperationPath(operationPath, parentPath) && !isSubresource) { continue; } Map<String, String> regexMap = new LinkedHashMap<>(); operationPath = PathUtils.parsePath(operationPath, regexMap); if (operationPath != null) { if (config != null && ReaderUtils.isIgnored(operationPath, config)) { continue; } final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(method); String httpMethod = ReaderUtils.extractOperationMethod(method, OpenAPIExtensions.chain()); httpMethod = (httpMethod == null && isSubresource) ? parentMethod : httpMethod; if (StringUtils.isBlank(httpMethod) && subResource == null) { continue; } else if (StringUtils.isBlank(httpMethod) && subResource != null) { Type returnType = method.getGenericReturnType(); if (shouldIgnoreClass(returnType.getTypeName()) && !returnType.equals(subResource)) { continue; } } io.swagger.v3.oas.annotations.Operation apiOperation = ReflectionUtils.getAnnotation(method, io.swagger.v3.oas.annotations.Operation.class); JsonView jsonViewAnnotation = ReflectionUtils.getAnnotation(method, JsonView.class); if (apiOperation != null && apiOperation.ignoreJsonView()) { jsonViewAnnotation = null; } Operation operation = parseMethod( method, globalParameters, methodProduces, classProduces, methodConsumes, classConsumes, classSecurityRequirements, classExternalDocumentation, classTags, classServers, isSubresource, parentRequestBody, parentResponses, jsonViewAnnotation, classResponses); if (operation != null) { // LOGGER.debug("operation is not null"); List<Parameter> operationParameters = new ArrayList<>(); List<Parameter> formParameters = new ArrayList<>(); Annotation[][] paramAnnotations = getParameterAnnotations(method); if (annotatedMethod == null) { // annotatedMethod not null only when method with 0-2 // parameters Type[] genericParameterTypes = method.getGenericParameterTypes(); genericParameterTypes = Arrays.stream(genericParameterTypes).filter(t -> !t.getTypeName().contains("ServerRequest")).toArray(Type[]::new); // // for( Type t : genericParameterTypes ) // { // LOGGER.warn("Generic parameter type: " + t); // } // // LOGGER.warn("paramAnnotations length: " + paramAnnotations.length + " // genericParameterTypes length: " + genericParameterTypes.length); for (int i = 0; i < genericParameterTypes.length; i++) { final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls); io.swagger.v3.oas.annotations.Parameter paramAnnotation = AnnotationsUtils .getAnnotation(io.swagger.v3.oas.annotations.Parameter.class, paramAnnotations[i]); Type paramType = ParameterProcessor.getParameterType(paramAnnotation, true); if (paramType == null) { paramType = type; } else { if (!(paramType instanceof Class)) { paramType = type; } } boolean isOptional = isOptionalType(TypeFactory.defaultInstance().constructType(paramType)); ResolvedParameter resolvedParameter = getParameters( paramType, Arrays.asList(paramAnnotations[i]), operation, classConsumes, methodConsumes, jsonViewAnnotation); operationParameters.addAll(resolvedParameter.parameters); resolvedParameter.formParameters.stream().forEach(fp -> fp.setRequired(!isOptional)); formParameters.addAll(resolvedParameter.formParameters); if (resolvedParameter.requestBody != null) { processRequestBody( resolvedParameter.requestBody, operation, methodConsumes, classConsumes, operationParameters, paramAnnotations[i], type, jsonViewAnnotation); } } } else { for (int i = 0; i < annotatedMethod.getParameterCount(); i++) { AnnotatedParameter param = annotatedMethod.getParameter(i); final Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), cls); io.swagger.v3.oas.annotations.Parameter paramAnnotation = AnnotationsUtils .getAnnotation(io.swagger.v3.oas.annotations.Parameter.class, paramAnnotations[i]); Type paramType = ParameterProcessor.getParameterType(paramAnnotation, true); if (paramType == null) { paramType = type; } else { if (!(paramType instanceof Class)) { paramType = type; } } boolean isOptional = isOptionalType(TypeFactory.defaultInstance().constructType(paramType)); ResolvedParameter resolvedParameter = getParameters( paramType, Arrays.asList(paramAnnotations[i]), operation, classConsumes, methodConsumes, jsonViewAnnotation); operationParameters.addAll(resolvedParameter.parameters); resolvedParameter.formParameters.stream().forEach(fp -> fp.setRequired(!isOptional)); formParameters.addAll(resolvedParameter.formParameters); if (resolvedParameter.requestBody != null) { processRequestBody( resolvedParameter.requestBody, operation, methodConsumes, classConsumes, operationParameters, paramAnnotations[i], type, jsonViewAnnotation); } } } // if we have form parameters, need to merge them into // single schema and use as request body.. if (formParameters.size() > 0) { Schema mergedSchema = new ObjectSchema(); boolean isRequired = false; for (Parameter formParam : formParameters) { if (formParam.getRequired() != null && formParam.getRequired()) { isRequired = true; } mergedSchema.addProperties(formParam.getName(), formParam.getSchema()); } Parameter merged = new Parameter().schema(mergedSchema); merged.setRequired(isRequired); processRequestBody( merged, operation, methodConsumes, classConsumes, operationParameters, new Annotation[0], null, jsonViewAnnotation); } if (operationParameters.size() > 0) { for (Parameter operationParameter : operationParameters) { operation.addParametersItem(operationParameter); } } // if subresource, merge parent parameters if (parentParameters != null) { for (Parameter parentParameter : parentParameters) { operation.addParametersItem(parentParameter); } } boolean hasJsonWrapper = false; if(method.isAnnotationPresent(Chain.class)) { Chain chainAnnotation = method.getAnnotation(Chain.class); Class<? extends HandlerWrapper>[] wrappers = chainAnnotation.value(); for(Class<? extends HandlerWrapper> wrapper : wrappers) { if(wrapper.equals(JsonViewWrapper.class)) { LOGGER.debug("Found json wrapper class on method"); hasJsonWrapper = true; } } } else if(cls.isAnnotationPresent(Chain.class)) { Chain chainAnnotation = cls.getAnnotation(Chain.class); Class<? extends HandlerWrapper>[] wrappers = chainAnnotation.value(); for(Class<? extends HandlerWrapper> wrapper : wrappers) { if(wrapper.equals(JsonViewWrapper.class)) { LOGGER.debug("Found json wrapper class on class"); hasJsonWrapper = true; } } } LOGGER.debug("hasJsonWrapper"); if(hasJsonWrapper && config.getUserDefinedOptions().containsKey("jsonViewQueryParameterName")) { Parameter contextParameter = new Parameter(); contextParameter.description("JsonView class") .allowEmptyValue(true) .required(false) .name(config.getUserDefinedOptions().get("jsonViewQueryParameterName").toString()) .in("query") .schema(stringSchema); operation.addParametersItem(contextParameter); } if (subResource != null && !scannedResources.contains(subResource)) { scannedResources.add(subResource); read( subResource, operationPath, httpMethod, true, operation.getRequestBody(), operation.getResponses(), classTags, operation.getParameters(), scannedResources); // remove the sub resource so that it can visit it later // in another path // but we have a room for optimization in the future to // reuse the scanned result // by caching the scanned resources in the reader // instance to avoid actual scanning // the the resources again scannedResources.remove(subResource); // don't proceed with root resource operation, as it's // handled by subresource continue; } final Iterator<OpenAPIExtension> chain = OpenAPIExtensions.chain(); if (chain.hasNext()) { final OpenAPIExtension extension = chain.next(); extension.decorateOperation(operation, method, chain); } PathItem pathItemObject; if (openAPI.getPaths() != null && openAPI.getPaths().get(operationPath) != null) { pathItemObject = openAPI.getPaths().get(operationPath); } else { pathItemObject = new PathItem(); } if (StringUtils.isBlank(httpMethod)) { continue; } setPathItemOperation(pathItemObject, httpMethod, operation); paths.addPathItem(operationPath, pathItemObject); if (openAPI.getPaths() != null) { this.paths.putAll(openAPI.getPaths()); } openAPI.setPaths(this.paths); LOGGER.debug("Completed paths"); } } } // if no components object is defined in openApi instance passed by // client, set openAPI.components to resolved components (if not empty) if (!isEmptyComponents(components) && openAPI.getComponents() == null) { openAPI.setComponents(components); } // add tags from class to definition tags AnnotationsUtils .getTags(apiTags, true).ifPresent(tags -> openApiTags.addAll(tags)); if (!openApiTags.isEmpty()) { Set<Tag> tagsSet = new LinkedHashSet<>(); if (openAPI.getTags() != null) { for (Tag tag : openAPI.getTags()) { if (tagsSet.stream().noneMatch(t -> t.getName().equals(tag.getName()))) { tagsSet.add(tag); } } } for (Tag tag : openApiTags) { if (tagsSet.stream().noneMatch(t -> t.getName().equals(tag.getName()))) { tagsSet.add(tag); } } openAPI.setTags(new ArrayList<>(tagsSet)); } return openAPI; } public boolean isOptionalType(JavaType propType) { return Arrays.asList("com.google.common.base.Optional", "java.util.Optional") .contains(propType.getRawClass().getCanonicalName()); } public static Annotation[][] getParameterAnnotations(Method method) { Annotation[][] methodAnnotations = method.getParameterAnnotations(); // LOGGER.warn("methodAnnotations length at start: " + // methodAnnotations.length); java.lang.reflect.Parameter[] params = method.getParameters(); List<Integer> filteredParameterIndices = new ArrayList<>(); for (int i = 0; i < params.length; i++) { Annotation[] paramAnnotations = methodAnnotations[i]; if (!params[i].getType().isAssignableFrom(ServerRequest.class) && !params[i].getType().getName().startsWith("io.undertow")) { // String annotationStrings = // Arrays.stream(paramAnnotations).map(a -> // a.annotationType().getName()).collect(Collectors.joining(" // ")); // LOGGER.debug("\nparameter: " + params[i] + " | name: " + params[i].getName() // + " type: " + params[i].getType() + " -> " + annotationStrings); if (paramAnnotations.length == 0) { final String parameterName = params[i].getName(); // LOGGER.debug("creating query parameter for " + // parameterName); QueryParam queryParam = new QueryParam() { @Override public String value() { return parameterName; } @Override public Class<? extends Annotation> annotationType() { return QueryParam.class; } }; methodAnnotations[i] = new Annotation[] { queryParam }; } } else { filteredParameterIndices.add(i); } } ArrayList<Annotation[]> annotations = Arrays.stream(methodAnnotations).collect(Collectors.toCollection(ArrayList::new)); for (int index : filteredParameterIndices) { annotations.remove(index); } methodAnnotations = annotations.stream().toArray(Annotation[][]::new); Method overriddenmethod = ReflectionUtils.getOverriddenMethod(method); if (overriddenmethod != null) { Annotation[][] overriddenAnnotations = overriddenmethod .getParameterAnnotations(); for (int i = 0; i < methodAnnotations.length; i++) { List<Type> types = new ArrayList<>(); for (int j = 0; j < methodAnnotations[i].length; j++) { types.add(methodAnnotations[i][j].annotationType()); } for (int j = 0; j < overriddenAnnotations[i].length; j++) { if (!types.contains(overriddenAnnotations[i][j] .annotationType())) { methodAnnotations[i] = ArrayUtils.add( methodAnnotations[i], overriddenAnnotations[i][j]); } } } } return methodAnnotations; } protected Content processContent(Content content, Schema schema, Consumes methodConsumes, Consumes classConsumes) { if (content == null) { content = new Content(); } if (methodConsumes != null) { for (String value : methodConsumes.value()) { setMediaTypeToContent(schema, content, value); } } else if (classConsumes != null) { for (String value : classConsumes.value()) { setMediaTypeToContent(schema, content, value); } } else { setMediaTypeToContent(schema, content, DEFAULT_MEDIA_TYPE_VALUE); } return content; } protected void processRequestBody( Parameter requestBodyParameter, Operation operation, Consumes methodConsumes, Consumes classConsumes, List<Parameter> operationParameters, Annotation[] paramAnnotations, Type type, JsonView jsonViewAnnotation) { boolean isOptional = !(requestBodyParameter.getRequired() != null ? requestBodyParameter.getRequired() : true); if (type != null && !isOptional) { JavaType classType = TypeFactory.defaultInstance().constructType(type); if (classType != null) { isOptional = isOptionalType(classType); type = classType; } } io.swagger.v3.oas.annotations.parameters.RequestBody requestBodyAnnotation = getRequestBody(Arrays.asList(paramAnnotations)); if (requestBodyAnnotation != null) { Optional<RequestBody> optionalRequestBody = OperationParser.getRequestBody(requestBodyAnnotation, classConsumes, methodConsumes, components, jsonViewAnnotation); if (optionalRequestBody.isPresent()) { RequestBody requestBody = optionalRequestBody.get(); if (StringUtils.isBlank(requestBody.get$ref()) && (requestBody.getContent() == null || requestBody.getContent().isEmpty())) { if (requestBodyParameter.getSchema() != null) { Content content = processContent(requestBody.getContent(), requestBodyParameter.getSchema(), methodConsumes, classConsumes); requestBody.setContent(content); } } else if (StringUtils.isBlank(requestBody.get$ref()) && requestBody.getContent() != null && !requestBody.getContent().isEmpty()) { if (requestBodyParameter.getSchema() != null) { for (MediaType mediaType : requestBody.getContent().values()) { if (mediaType.getSchema() == null) { if (requestBodyParameter.getSchema() == null) { mediaType.setSchema(new Schema()); } else { mediaType.setSchema(requestBodyParameter.getSchema()); } } if (StringUtils.isBlank(mediaType.getSchema().getType())) { mediaType.getSchema().setType(requestBodyParameter.getSchema().getType()); } } } } requestBody.setRequired(!isOptional); operation.setRequestBody(requestBody); } } else { if (operation.getRequestBody() == null) { boolean isRequestBodyEmpty = true; RequestBody requestBody = new RequestBody(); if (StringUtils.isNotBlank(requestBodyParameter.get$ref())) { requestBody.set$ref(requestBodyParameter.get$ref()); isRequestBodyEmpty = false; } if (StringUtils.isNotBlank(requestBodyParameter.getDescription())) { requestBody.setDescription(requestBodyParameter.getDescription()); isRequestBodyEmpty = false; } if (Boolean.TRUE.equals(requestBodyParameter.getRequired())) { requestBody.setRequired(requestBodyParameter.getRequired()); isRequestBodyEmpty = false; } if (requestBodyParameter.getSchema() != null) { Content content = processContent(null, requestBodyParameter.getSchema(), methodConsumes, classConsumes); requestBody.setContent(content); isRequestBodyEmpty = false; } if (!isRequestBodyEmpty) { // requestBody.setExtensions(extensions); requestBody.setRequired(!isOptional); operation.setRequestBody(requestBody); } } } } private io.swagger.v3.oas.annotations.parameters.RequestBody getRequestBody(List<Annotation> annotations) { if (annotations == null) { return null; } for (Annotation a : annotations) { if (a instanceof io.swagger.v3.oas.annotations.parameters.RequestBody) { return (io.swagger.v3.oas.annotations.parameters.RequestBody) a; } } return null; } private void setMediaTypeToContent(Schema schema, Content content, String value) { MediaType mediaTypeObject = new MediaType(); mediaTypeObject.setSchema(schema); content.addMediaType(value, mediaTypeObject); } public Operation parseMethod( Method method, List<Parameter> globalParameters, JsonView jsonViewAnnotation) { JavaType classType = TypeFactory.defaultInstance().constructType(method.getDeclaringClass()); return parseMethod( classType.getClass(), method, globalParameters, null, null, null, null, new ArrayList<>(), Optional.empty(), new HashSet<>(), new ArrayList<>(), false, null, null, jsonViewAnnotation, null); } public Operation parseMethod( Method method, List<Parameter> globalParameters, Produces methodProduces, Produces classProduces, Consumes methodConsumes, Consumes classConsumes, List<SecurityRequirement> classSecurityRequirements, Optional<io.swagger.v3.oas.models.ExternalDocumentation> classExternalDocs, Set<String> classTags, List<io.swagger.v3.oas.models.servers.Server> classServers, boolean isSubresource, RequestBody parentRequestBody, ApiResponses parentResponses, JsonView jsonViewAnnotation, io.swagger.v3.oas.annotations.responses.ApiResponse[] classResponses) { JavaType classType = TypeFactory.defaultInstance().constructType(method.getDeclaringClass()); return parseMethod( classType.getClass(), method, globalParameters, methodProduces, classProduces, methodConsumes, classConsumes, classSecurityRequirements, classExternalDocs, classTags, classServers, isSubresource, parentRequestBody, parentResponses, jsonViewAnnotation, classResponses); } private Operation parseMethod( Class<?> cls, Method method, List<Parameter> globalParameters, Produces methodProduces, Produces classProduces, Consumes methodConsumes, Consumes classConsumes, List<SecurityRequirement> classSecurityRequirements, Optional<io.swagger.v3.oas.models.ExternalDocumentation> classExternalDocs, Set<String> classTags, List<io.swagger.v3.oas.models.servers.Server> classServers, boolean isSubresource, RequestBody parentRequestBody, ApiResponses parentResponses, JsonView jsonViewAnnotation, io.swagger.v3.oas.annotations.responses.ApiResponse[] classResponses) { if (Arrays.stream(method.getParameters()).filter(p -> p.getType().isAssignableFrom(HttpServerExchange.class)).count() > 0L) { return null; } Operation operation = new Operation(); io.swagger.v3.oas.annotations.Operation apiOperation = ReflectionUtils.getAnnotation(method, io.swagger.v3.oas.annotations.Operation.class); List<io.swagger.v3.oas.annotations.security.SecurityRequirement> apiSecurity = ReflectionUtils .getRepeatableAnnotations(method, io.swagger.v3.oas.annotations.security.SecurityRequirement.class); List<io.swagger.v3.oas.annotations.callbacks.Callback> apiCallbacks = ReflectionUtils .getRepeatableAnnotations(method, io.swagger.v3.oas.annotations.callbacks.Callback.class); List<Server> apiServers = ReflectionUtils.getRepeatableAnnotations(method, Server.class); List<io.swagger.v3.oas.annotations.tags.Tag> apiTags = ReflectionUtils.getRepeatableAnnotations(method, io.swagger.v3.oas.annotations.tags.Tag.class); List<io.swagger.v3.oas.annotations.Parameter> apiParameters = ReflectionUtils.getRepeatableAnnotations(method, io.swagger.v3.oas.annotations.Parameter.class); List<io.swagger.v3.oas.annotations.responses.ApiResponse> apiResponses = ReflectionUtils .getRepeatableAnnotations(method, io.swagger.v3.oas.annotations.responses.ApiResponse.class); io.swagger.v3.oas.annotations.parameters.RequestBody apiRequestBody = ReflectionUtils.getAnnotation(method, io.swagger.v3.oas.annotations.parameters.RequestBody.class); ExternalDocumentation apiExternalDocumentation = ReflectionUtils.getAnnotation(method, ExternalDocumentation.class); // callbacks Map<String, Callback> callbacks = new LinkedHashMap<>(); if (apiCallbacks != null) { for (io.swagger.v3.oas.annotations.callbacks.Callback methodCallback : apiCallbacks) { Map<String, Callback> currentCallbacks = getCallbacks(methodCallback, methodProduces, classProduces, methodConsumes, classConsumes, jsonViewAnnotation); callbacks.putAll(currentCallbacks); } } if (callbacks.size() > 0) { operation.setCallbacks(callbacks); } // security classSecurityRequirements.forEach(operation::addSecurityItem); if (apiSecurity != null) { Optional<List<SecurityRequirement>> requirementsObject = SecurityParser.getSecurityRequirements(apiSecurity.toArray( new io.swagger.v3.oas.annotations.security.SecurityRequirement[apiSecurity .size()])); if (requirementsObject.isPresent()) { requirementsObject.get().stream() .filter(r -> operation.getSecurity() == null || !operation.getSecurity().contains(r)) .forEach(operation::addSecurityItem); } } // servers if (classServers != null) { classServers.forEach(operation::addServersItem); } if (apiServers != null) { AnnotationsUtils.getServers(apiServers.toArray(new Server[apiServers.size()])).ifPresent(servers -> servers.forEach(operation::addServersItem)); } // external docs AnnotationsUtils.getExternalDocumentation(apiExternalDocumentation).ifPresent(operation::setExternalDocs); // method tags if (apiTags != null) { apiTags.stream() .filter(t -> operation.getTags() == null || (operation.getTags() != null && !operation.getTags().contains(t.name()))) .map(t -> t.name()) .forEach(operation::addTagsItem); AnnotationsUtils.getTags(apiTags.toArray(new io.swagger.v3.oas.annotations.tags.Tag[apiTags.size()]), true).ifPresent(tags -> openApiTags.addAll(tags)); } // parameters if (globalParameters != null) { for (Parameter globalParameter : globalParameters) { operation.addParametersItem(globalParameter); } } if (apiParameters != null) { getParametersListFromAnnotation( apiParameters.toArray(new io.swagger.v3.oas.annotations.Parameter[apiParameters.size()]), classConsumes, methodConsumes, operation, jsonViewAnnotation).ifPresent(p -> p.forEach(operation::addParametersItem)); } // RequestBody in Method if (apiRequestBody != null && operation.getRequestBody() == null) { OperationParser.getRequestBody(apiRequestBody, classConsumes, methodConsumes, components, jsonViewAnnotation).ifPresent( operation::setRequestBody); LOGGER.debug("request body: " + operation.getRequestBody().toString()); } // operation id if (StringUtils.isBlank(operation.getOperationId())) { operation.setOperationId(getOperationId(method.getName())); } /* if (StringUtils.isBlank(operation.getOperationId())) { String className = toLowerCase(method.getDeclaringClass().getSimpleName().charAt(0)) + method.getDeclaringClass().getSimpleName().substring(1); String operationId = String.format("%s%s",className,toUpperCase(method.getName().charAt(0)) + method.getName().substring(1)); operation.setOperationId(operationId); } */ // classResponses if (classResponses != null && classResponses.length > 0) { OperationParser.getApiResponses( classResponses, classProduces, methodProduces, components, jsonViewAnnotation) .ifPresent(responses -> { if (operation.getResponses() == null) { operation.setResponses(responses); } else { responses.forEach(operation.getResponses()::addApiResponse); } }); } if (apiOperation != null) { setOperationObjectFromApiOperationAnnotation(operation, apiOperation, methodProduces, classProduces, methodConsumes, classConsumes, jsonViewAnnotation); } // apiResponses if (apiResponses != null && apiResponses.size() > 0) { OperationParser.getApiResponses( apiResponses.toArray(new io.swagger.v3.oas.annotations.responses.ApiResponse[apiResponses.size()]), classProduces, methodProduces, components, jsonViewAnnotation) .ifPresent(responses -> { if (operation.getResponses() == null) { operation.setResponses(responses); } else { responses.forEach(operation.getResponses()::addApiResponse); } }); } // class tags after tags defined as field of @Operation if (classTags != null) { classTags.stream() .filter(t -> operation.getTags() == null || (operation.getTags() != null && !operation.getTags().contains(t))) .forEach(operation::addTagsItem); } // external docs of class if not defined in annotation of method or as // field of Operation annotation if (operation.getExternalDocs() == null) { classExternalDocs.ifPresent(operation::setExternalDocs); } // if subresource, merge parent requestBody if (isSubresource && parentRequestBody != null) { if (operation.getRequestBody() == null) { operation.requestBody(parentRequestBody); } else { Content content = operation.getRequestBody().getContent(); if (content == null) { content = parentRequestBody.getContent(); operation.getRequestBody().setContent(content); } else if (parentRequestBody.getContent() != null) { for (String parentMediaType : parentRequestBody.getContent().keySet()) { if (content.get(parentMediaType) == null) { content.addMediaType(parentMediaType, parentRequestBody.getContent().get(parentMediaType)); } } } } } // handle return type, add as response in case. Type returnType = method.getGenericReturnType(); final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(method); if (!shouldIgnoreClass(returnType.getTypeName()) && !returnType.equals(subResource)) { LOGGER.debug("processing class " + returnType + " " + returnType.getTypeName()); JavaType classType = TypeFactory.defaultInstance().constructType(returnType); if (classType != null && classType.getRawClass() != null) { if (classType.getRawClass().isAssignableFrom(ServerResponse.class)) { if (classType.containedType(0) != null) { returnType = classType.containedType(0); } } else if (classType.getRawClass().isAssignableFrom(CompletableFuture.class)) { Class<?> futureCls = classType.containedType(0).getRawClass(); if (futureCls.isAssignableFrom(ServerResponse.class)) { final JavaType futureType = TypeFactory.defaultInstance().constructType(classType.containedType(0)); returnType = futureType.containedType(0); } else { returnType = classType.containedType(0); } } } ResolvedSchema resolvedSchema = ModelConverters.getInstance() .resolveAsResolvedSchema(new AnnotatedType(returnType).resolveAsRef(true).jsonViewAnnotation(jsonViewAnnotation)); if (resolvedSchema.schema != null) { Schema returnTypeSchema = resolvedSchema.schema; Content content = new Content(); MediaType mediaType = new MediaType().schema(returnTypeSchema); AnnotationsUtils.applyTypes(classProduces == null ? new String[0] : classProduces.value(), methodProduces == null ? new String[0] : methodProduces.value(), content, mediaType); if (operation.getResponses() == null) { operation.responses( new ApiResponses()._default( new ApiResponse().description(DEFAULT_DESCRIPTION) .content(content))); } if (operation.getResponses().getDefault() != null && StringUtils.isBlank(operation.getResponses().getDefault().get$ref())) { if (operation.getResponses().getDefault().getContent() == null) { operation.getResponses().getDefault().content(content); } else { for (String key : operation.getResponses().getDefault().getContent().keySet()) { if (operation.getResponses().getDefault().getContent().get(key).getSchema() == null) { operation.getResponses().getDefault().getContent().get(key).setSchema(returnTypeSchema); } } } } Map<String, Schema> schemaMap = resolvedSchema.referencedSchemas; if (schemaMap != null) { schemaMap.forEach((key, schema) -> components.addSchemas(key, schema)); } } } if (operation.getResponses() == null || operation.getResponses().isEmpty()) { LOGGER.debug("responses are null or empty"); // Content content = new Content(); // MediaType mediaType = new MediaType(); // AnnotationsUtils.applyTypes(classProduces == null ? new String[0] // : classProduces.value(), // methodProduces == null ? new String[0] : methodProduces.value(), // content, mediaType); ApiResponse apiResponseObject = new ApiResponse().description(DEFAULT_DESCRIPTION);// .content(content); operation.setResponses(new ApiResponses()._default(apiResponseObject)); } return operation; } private boolean shouldIgnoreClass(String className) { if (StringUtils.isBlank(className)) { return true; } boolean ignore = false; ignore = ignore || className.startsWith("javax.ws.rs."); ignore = ignore || className.equalsIgnoreCase("void"); ignore = ignore || className.startsWith("io.undertow"); ignore = ignore || className.startsWith("java.lang.Void"); return ignore; } private Map<String, Callback> getCallbacks( io.swagger.v3.oas.annotations.callbacks.Callback apiCallback, Produces methodProduces, Produces classProduces, Consumes methodConsumes, Consumes classConsumes, JsonView jsonViewAnnotation) { Map<String, Callback> callbackMap = new HashMap<>(); if (apiCallback == null) { return callbackMap; } Callback callbackObject = new Callback(); if (StringUtils.isNotBlank(apiCallback.ref())) { callbackObject.set$ref(apiCallback.ref()); callbackMap.put(apiCallback.name(), callbackObject); return callbackMap; } PathItem pathItemObject = new PathItem(); for (io.swagger.v3.oas.annotations.Operation callbackOperation : apiCallback.operation()) { Operation callbackNewOperation = new Operation(); setOperationObjectFromApiOperationAnnotation( callbackNewOperation, callbackOperation, methodProduces, classProduces, methodConsumes, classConsumes, jsonViewAnnotation); setPathItemOperation(pathItemObject, callbackOperation.method(), callbackNewOperation); } callbackObject.addPathItem(apiCallback.callbackUrlExpression(), pathItemObject); callbackMap.put(apiCallback.name(), callbackObject); return callbackMap; } private void setPathItemOperation(PathItem pathItemObject, String method, Operation operation) { switch (method) { case POST_METHOD: pathItemObject.post(operation); break; case GET_METHOD: pathItemObject.get(operation); break; case DELETE_METHOD: pathItemObject.delete(operation); break; case PUT_METHOD: pathItemObject.put(operation); break; case PATCH_METHOD: pathItemObject.patch(operation); break; case TRACE_METHOD: pathItemObject.trace(operation); break; case HEAD_METHOD: pathItemObject.head(operation); break; case OPTIONS_METHOD: pathItemObject.options(operation); break; default: // Do nothing here break; } } private void setOperationObjectFromApiOperationAnnotation( Operation operation, io.swagger.v3.oas.annotations.Operation apiOperation, Produces methodProduces, Produces classProduces, Consumes methodConsumes, Consumes classConsumes, JsonView jsonViewAnnotation) { if (StringUtils.isNotBlank(apiOperation.summary())) { operation.setSummary(apiOperation.summary()); } if (StringUtils.isNotBlank(apiOperation.description())) { operation.setDescription(apiOperation.description()); } if (StringUtils.isNotBlank(apiOperation.operationId())) { operation.setOperationId(getOperationId(apiOperation.operationId())); } if (apiOperation.deprecated()) { operation.setDeprecated(apiOperation.deprecated()); } ReaderUtils.getStringListFromStringArray(apiOperation.tags()).ifPresent(tags -> { tags.stream() .filter(t -> operation.getTags() == null || (operation.getTags() != null && !operation.getTags().contains(t))) .forEach(operation::addTagsItem); }); if (operation.getExternalDocs() == null) { // if not set in root annotation AnnotationsUtils.getExternalDocumentation(apiOperation.externalDocs()).ifPresent(operation::setExternalDocs); } OperationParser.getApiResponses(apiOperation.responses(), classProduces, methodProduces, components, jsonViewAnnotation).ifPresent(responses -> { if (operation.getResponses() == null) { operation.setResponses(responses); } else { responses.forEach(operation.getResponses()::addApiResponse); } }); AnnotationsUtils.getServers(apiOperation.servers()).ifPresent(servers -> servers.forEach(operation::addServersItem)); getParametersListFromAnnotation( apiOperation.parameters(), classConsumes, methodConsumes, operation, jsonViewAnnotation).ifPresent(p -> p.forEach(operation::addParametersItem)); // security Optional<List<SecurityRequirement>> requirementsObject = SecurityParser.getSecurityRequirements(apiOperation.security()); if (requirementsObject.isPresent()) { requirementsObject.get().stream() .filter(r -> operation.getSecurity() == null || !operation.getSecurity().contains(r)) .forEach(operation::addSecurityItem); } // RequestBody in Operation if (apiOperation != null && apiOperation.requestBody() != null && operation.getRequestBody() == null) { OperationParser.getRequestBody(apiOperation.requestBody(), classConsumes, methodConsumes, components, jsonViewAnnotation).ifPresent( requestBodyObject -> operation .setRequestBody( requestBodyObject)); } // Extensions in Operation if (apiOperation.extensions().length > 0) { Map<String, Object> extensions = AnnotationsUtils.getExtensions(apiOperation.extensions()); if (extensions != null) { for (String ext : extensions.keySet()) { operation.addExtension(ext, extensions.get(ext)); } } } } protected String getOperationId(String operationId) { boolean operationIdUsed = existOperationId(operationId); String operationIdToFind = null; int counter = 0; while (operationIdUsed) { operationIdToFind = String.format("%s_%d", operationId, ++counter); operationIdUsed = existOperationId(operationIdToFind); } if (operationIdToFind != null) { operationId = operationIdToFind; } return operationId; } private boolean existOperationId(String operationId) { if (openAPI == null) { return false; } if (openAPI.getPaths() == null || openAPI.getPaths().isEmpty()) { return false; } for (PathItem path : openAPI.getPaths().values()) { String pathOperationId = extractOperationIdFromPathItem(path); if (operationId.equalsIgnoreCase(pathOperationId)) { return true; } } return false; } protected Optional<List<Parameter>> getParametersListFromAnnotation(io.swagger.v3.oas.annotations.Parameter[] parameters, Consumes classConsumes, Consumes methodConsumes, Operation operation, JsonView jsonViewAnnotation) { if (parameters == null) { return Optional.empty(); } List<Parameter> parametersObject = new ArrayList<>(); for (io.swagger.v3.oas.annotations.Parameter parameter : parameters) { ResolvedParameter resolvedParameter = getParameters( ParameterProcessor.getParameterType(parameter), Collections.singletonList(parameter), operation, classConsumes, methodConsumes, jsonViewAnnotation); parametersObject.addAll(resolvedParameter.parameters); } if (parametersObject.size() == 0) { return Optional.empty(); } return Optional.of(parametersObject); } protected ResolvedParameter getParameters( Type type, List<Annotation> annotations, Operation operation, Consumes classConsumes, Consumes methodConsumes, JsonView jsonViewAnnotation) { final Iterator<OpenAPIExtension> chain = OpenAPIExtensions.chain(); if (!chain.hasNext()) { return new ResolvedParameter(); } LOGGER.debug("getParameters for {}", type); if(type.toString().equalsIgnoreCase("[map type; class java.util.Map, [simple type, class java.lang.String] -> [simple type, class java.nio.file.Path]]")) { type = TypeFactory.defaultInstance().constructCollectionType(java.util.List.class,java.nio.file.Path.class); } else if(type.toString().equalsIgnoreCase("[map type; class java.util.Map, [simple type, class java.lang.String] -> [simple type, class java.io.File]]")) { type = TypeFactory.defaultInstance().constructCollectionType(java.util.List.class,java.io.File.class); } Set<Type> typesToSkip = new HashSet<>(); final OpenAPIExtension extension = chain.next(); LOGGER.debug("trying extension {}", extension); final ResolvedParameter extractParametersResult = extension .extractParameters(annotations, type, typesToSkip, components, classConsumes, methodConsumes, true, jsonViewAnnotation, chain); return extractParametersResult; } private String extractOperationIdFromPathItem(PathItem path) { if (path.getGet() != null) { return path.getGet().getOperationId(); } else if (path.getPost() != null) { return path.getPost().getOperationId(); } else if (path.getPut() != null) { return path.getPut().getOperationId(); } else if (path.getDelete() != null) { return path.getDelete().getOperationId(); } else if (path.getOptions() != null) { return path.getOptions().getOperationId(); } else if (path.getHead() != null) { return path.getHead().getOperationId(); } else if (path.getPatch() != null) { return path.getPatch().getOperationId(); } return ""; } private boolean isEmptyComponents(Components components) { if (components == null) { return true; } if (components.getSchemas() != null && components.getSchemas().size() > 0) { return false; } if (components.getSecuritySchemes() != null && components.getSecuritySchemes().size() > 0) { return false; } if (components.getCallbacks() != null && components.getCallbacks().size() > 0) { return false; } if (components.getExamples() != null && components.getExamples().size() > 0) { return false; } if (components.getExtensions() != null && components.getExtensions().size() > 0) { return false; } if (components.getHeaders() != null && components.getHeaders().size() > 0) { return false; } if (components.getLinks() != null && components.getLinks().size() > 0) { return false; } if (components.getParameters() != null && components.getParameters().size() > 0) { return false; } if (components.getRequestBodies() != null && components.getRequestBodies().size() > 0) { return false; } if (components.getResponses() != null && components.getResponses().size() > 0) { return false; } return true; } protected boolean isOperationHidden(Method method) { io.swagger.v3.oas.annotations.Operation apiOperation = ReflectionUtils.getAnnotation(method, io.swagger.v3.oas.annotations.Operation.class); if (apiOperation != null && apiOperation.hidden()) { return true; } Hidden hidden = method.getAnnotation(Hidden.class); if (hidden != null) { return true; } if (config != null && !Boolean.TRUE.equals(config.isReadAllResources()) && apiOperation == null) { return true; } return false; } public void setApplication(Application application) { this.application = application; } protected boolean ignoreOperationPath(String path, String parentPath) { if (StringUtils.isBlank(path) && StringUtils.isBlank(parentPath)) { return true; } else if (StringUtils.isNotBlank(path) && StringUtils.isBlank(parentPath)) { return false; } else if (StringUtils.isBlank(path) && StringUtils.isNotBlank(parentPath)) { return false; } if (parentPath != null && !"".equals(parentPath) && !"/".equals(parentPath)) { if (!parentPath.startsWith("/")) { parentPath = "/" + parentPath; } if (parentPath.endsWith("/")) { parentPath = parentPath.substring(0, parentPath.length() - 1); } } if (path != null && !"".equals(path) && !"/".equals(path)) { if (!path.startsWith("/")) { path = "/" + path; } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } } if (path.equals(parentPath)) { return true; } return false; } protected Class<?> getSubResourceWithJaxRsSubresourceLocatorSpecs(Method method) { final Class<?> rawType = method.getReturnType(); final Class<?> type; if (Class.class.equals(rawType)) { type = getClassArgument(method.getGenericReturnType()); if (type == null) { return null; } } else { type = rawType; } if (method.getAnnotation(javax.ws.rs.Path.class) != null) { if (ReaderUtils.extractOperationMethod(method, null) == null) { return type; } } return null; } private static Class<?> getClassArgument(Type cls) { if (cls instanceof ParameterizedType) { final ParameterizedType parameterized = (ParameterizedType) cls; final Type[] args = parameterized.getActualTypeArguments(); if (args.length != 1) { LOGGER.error("Unexpected class definition: {}", cls); return null; } final Type first = args[0]; if (first instanceof Class) { return (Class<?>) first; } else { return null; } } else { LOGGER.error("Unknown class definition: {}", cls); return null; } } }