answer
stringlengths
17
10.2M
package org.tndata.android.compass.activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.RelativeLayout; import com.github.clans.fab.FloatingActionButton; import org.tndata.android.compass.R; import org.tndata.android.compass.adapter.MaterialAdapter; import org.tndata.android.compass.util.CompassUtil; import org.tndata.android.compass.util.ParallaxEffect; /** * Generic activity for library screens. * * @author Ismael Alonso * @version 1.0.0 */ public abstract class MaterialActivity extends AppCompatActivity{ private FrameLayout mHeaderContainer; private RecyclerView mRecyclerView; private FloatingActionButton mFAB; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_material); //Set up the toolbar Toolbar toolbar = (Toolbar)findViewById(R.id.material_toolbar); toolbar.setNavigationIcon(R.drawable.ic_back_white_24dp); setSupportActionBar(toolbar); if (getSupportActionBar() != null){ getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); } //Fetch UI components mHeaderContainer = (FrameLayout)findViewById(R.id.material_header_container); mRecyclerView = (RecyclerView)findViewById(R.id.material_list); mFAB = (FloatingActionButton)findViewById(R.id.material_fab); //Make the header the right size RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)mHeaderContainer.getLayoutParams(); params.height = CompassUtil.getScreenWidth(this)/3*2; mHeaderContainer.setLayoutParams(params); //Add the parallax effect to the header mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.addOnScrollListener(new ParallaxEffect(mHeaderContainer, 0.5f)); //Add the toolbar effect ParallaxEffect toolbarEffect = new ParallaxEffect(toolbar, 1); toolbarEffect.setParallaxCondition(new ParallaxEffect.ParallaxCondition(){ @Override protected boolean doParallax(){ int height = (int)((CompassUtil.getScreenWidth(MaterialActivity.this) * 2 / 3) * 0.6); return -getRecyclerViewOffset() > height; } @Override protected int getParallaxViewOffset(){ int height = (int)((CompassUtil.getScreenWidth(MaterialActivity.this) * 2 / 3) * 0.6); return height + getFixedState() + getRecyclerViewOffset(); } }); mRecyclerView.addOnScrollListener(toolbarEffect); } @Override public void setContentView(@LayoutRes int layoutResID){ /* no-op */ //This and the two following methods are overriden and empty to prevent // the programmer from changing the default layout of this activity } @Override public void setContentView(View view){ /* no-op */ } @Override public void setContentView(View view, ViewGroup.LayoutParams params){ /* no-op */ } @Override public boolean onCreateOptionsMenu(Menu menu){ return super.onCreateOptionsMenu(menu); } @Override public final boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()){ case android.R.id.home: onHomeTapped(); finish(); return true; case R.id.search: startActivity(new Intent(this, SearchActivity.class)); return true; default: return menuItemSelected(item) || super.onOptionsItemSelected(item); } } protected void onHomeTapped(){} protected boolean menuItemSelected(MenuItem item){ return false; } protected final void setColor(int color){ mHeaderContainer.setBackgroundColor(color); mFAB.setColorNormal(color); mFAB.setColorPressed(color); } protected final void setAdapter(MaterialAdapter adapter){ mRecyclerView.setAdapter(adapter); } protected final View inflateHeader(@LayoutRes int layoutResId){ return LayoutInflater.from(this).inflate(layoutResId, mHeaderContainer); } protected final void setFAB(@IdRes int id, View.OnClickListener listener){ mFAB.setId(id); mFAB.setOnClickListener(listener); mFAB.setVisibility(View.VISIBLE); } }
package soot.dexpler; import lanchon.multidexlib2.BasicDexFileNamer; import lanchon.multidexlib2.BasicMultiDexFile; import lanchon.multidexlib2.DexIO; import lanchon.multidexlib2.MultiDexIO; import org.jf.dexlib2.Opcodes; import org.jf.dexlib2.dexbacked.DexBackedDexFile; import org.jf.dexlib2.iface.ClassDef; import org.jf.dexlib2.iface.DexFile; import org.jf.dexlib2.iface.MultiDexContainer; import soot.*; import soot.javaToJimple.IInitialResolver.Dependencies; import soot.options.Options; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.*; /** * DexlibWrapper provides an entry point to the dexlib library from the smali * project. Given a dex file, it will use dexlib to retrieve all classes for * further processing A call to getClass retrieves the specific class to analyze * further. */ public class DexlibWrapper { private final static Set<String> systemAnnotationNames; static { Set<String> systemAnnotationNamesModifiable = new HashSet<String>(); // names as defined in the ".dex - Dalvik Executable Format" document systemAnnotationNamesModifiable.add("dalvik.annotation.AnnotationDefault"); systemAnnotationNamesModifiable.add("dalvik.annotation.EnclosingClass"); systemAnnotationNamesModifiable.add("dalvik.annotation.EnclosingMethod"); systemAnnotationNamesModifiable.add("dalvik.annotation.InnerClass"); systemAnnotationNamesModifiable.add("dalvik.annotation.MemberClasses"); systemAnnotationNamesModifiable.add("dalvik.annotation.Signature"); systemAnnotationNamesModifiable.add("dalvik.annotation.Throws"); systemAnnotationNames = Collections.unmodifiableSet(systemAnnotationNamesModifiable); } private final DexClassLoader dexLoader = new DexClassLoader(); private final Map<String, ClassDef> classesToDefItems = new HashMap<String, ClassDef>(); private final File inputDexFile; private MultiDexContainer<? extends DexFile> dexContainer; /** * Construct a DexlibWrapper from a dex file and stores its classes * referenced by their name. No further process is done here. * * @param inputDexFile the dex file or an apk/zip/jar with multiple dex files. */ public DexlibWrapper(File inputDexFile) { this.inputDexFile = inputDexFile; } public void initialize() { try { int api = Scene.v().getAndroidAPIVersion(); boolean multiDex = Options.v().process_multiple_dex(); DexIO.Logger logger = new DexIO.Logger() { @Override public void log(File file, String entryName, int typeCount) { G.v().out.println(String.format("Found dex file '%s' with %d classes in '%s'", entryName, typeCount, file.getName())); } }; dexContainer = MultiDexIO.readMultiDexContainer(inputDexFile, new BasicDexFileNamer(), Opcodes.forApi(api), logger); List<String> dexEntries = dexContainer.getDexEntryNames(); int num_dex_files = dexEntries.size(); if (!multiDex && num_dex_files > 1) { G.v().out.println("WARNING: Multiple dex files detected, only processing first dex file (" + dexEntries.get(0) + "). Use '-process-multiple-dex' option to process them all."); // restrict processed dex files to the first num_dex_files = 1; } for (int dexIndex = 0; dexIndex < num_dex_files; dexIndex++) { DexFile dexFile = dexContainer.getEntry(dexEntries.get(dexIndex)); for (ClassDef defItem : dexFile.getClasses()) { String forClassName = Util.dottedClassName(defItem.getType()); classesToDefItems.put(forClassName, defItem); } } // It is important to first resolve the classes, otherwise we will produce an error during type resolution. for (int dexIndex = 0; dexIndex < num_dex_files; dexIndex++) { // FIXME reflection hack to get the DexBackedDexFile out of the BasicMultiDexFileImplementation DexFile dexFile = dexBackedDexFileHack(dexContainer.getEntry(dexEntries.get(dexIndex))); if (dexFile instanceof DexBackedDexFile) { DexBackedDexFile dbdf = (DexBackedDexFile) dexFile; for (int i = 0; i < dbdf.getTypeCount(); i++) { String t = dbdf.getType(i); Type st = DexType.toSoot(t); if (st instanceof ArrayType) { st = ((ArrayType) st).baseType; } Debug.printDbg("Type: ", t, " soot type:", st); String sootTypeName = st.toString(); if (!Scene.v().containsClass(sootTypeName)) { if (st instanceof PrimType || st instanceof VoidType || systemAnnotationNames.contains(sootTypeName)) { // dex files contain references to the Type IDs of // void // / primitive types - we obviously do not want them // be resolved /* * dex files contain references to the Type IDs of * the system annotations. They are only visible to * the Dalvik VM (for reflection, see * vm/reflect/Annotations.cpp), and not to the user * - so we do not want them to be resolved. */ continue; } SootResolver.v().makeClassRef(sootTypeName); } SootResolver.v().resolveClass(sootTypeName, SootClass.SIGNATURES); } } else { System.out.println("Warning: DexFile not instance of DexBackedDexFile! Not resolving types!"); System.out.println("type: " + dexFile.getClass()); } } } catch (IOException e) { throw new RuntimeException(e); } } private DexFile dexBackedDexFileHack(DexFile dexFile) { if (!(dexFile instanceof BasicMultiDexFile)) return dexFile; try { Field internalDexFile = BasicMultiDexFile.class.getDeclaredField("dexFile"); internalDexFile.setAccessible(true); dexFile = (DexFile) internalDexFile.get(dexFile); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return dexFile; } public Dependencies makeSootClass(SootClass sc, String className) { if (Util.isByteCodeClassName(className)) { className = Util.dottedClassName(className); } try { for (String dexEntry : dexContainer.getDexEntryNames()) { DexFile dexFile = dexContainer.getEntry(dexEntry); ClassDef defItem = classesToDefItems.get(className); return dexLoader.makeSootClass(sc, defItem, dexFile); } } catch (IOException e) { // happens when dex file is not available throw new RuntimeException(e); } throw new RuntimeException("Error: class not found in DEX files: " + className); } }
package com.oncore.calorders.rest.service.extension; import com.oncore.calorders.core.enums.ErrorCode; import com.oncore.calorders.core.exceptions.DataAccessException; import com.oncore.calorders.core.utils.FormatHelper; import static com.oncore.calorders.core.utils.FormatHelper.LOG; import com.oncore.calorders.core.utils.Logger; import com.oncore.calorders.rest.GroupPartyAssoc; import com.oncore.calorders.rest.OrdStatusCd; import com.oncore.calorders.rest.OrderHistory; import com.oncore.calorders.rest.OrderProductAssoc; import com.oncore.calorders.rest.Party; import com.oncore.calorders.rest.Product; import com.oncore.calorders.rest.data.OrderHistoryData; import com.oncore.calorders.rest.data.OrderItemData; import com.oncore.calorders.rest.data.OrderStatusData; import com.oncore.calorders.rest.data.OrderStatusSummaryData; import com.oncore.calorders.rest.data.OrdersByQuarterData; import com.oncore.calorders.rest.data.OrdersByQuarterSeriesData; import com.oncore.calorders.rest.service.OrdStatusCdFacadeREST; import com.oncore.calorders.rest.service.OrderHistoryFacadeREST; import java.io.StringReader; import java.math.BigDecimal; import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.List; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.persistence.TypedQuery; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.commons.collections4.CollectionUtils; /** * * @author oncore */ @Stateless @Path("com.oncore.calorders.rest.orderHistory") public class OrderHistoryFacadeRESTExtension extends OrderHistoryFacadeREST { @EJB OrdStatusCdFacadeREST ordStatusCdFacadeREST; @EJB PartyFacadeRESTExtension partyFacadeRESTExtension; @EJB ProductFacadeRESTExtension productFacadeRESTExtension; public OrderHistoryFacadeRESTExtension() { super(); } /** * Creates an order, containing the ordered products and related services. * * @param orderjson The order, represented as a JSON string * @throws DataAccessException */ @POST @Path("createOrder") @Consumes({MediaType.APPLICATION_JSON}) public void createOrder(String orderjson) throws DataAccessException { try { JsonReader reader = Json.createReader(new StringReader(orderjson)); JsonObject orderObject = reader.readObject(); reader.close(); OrderHistory order = new OrderHistory(); order.setUpdateTs(new Date()); order.setUpdateUserId(orderObject.getString("updateUserId", null)); order.setCreateTs(new Date()); order.setCreateUserId(orderObject.getString("createUserId", null)); OrdStatusCd ordStatusCd = this.ordStatusCdFacadeREST.find(orderObject.getString("orderStatusCd", null)); if (ordStatusCd == null) { throw new DataAccessException(ErrorCode.DATAACCESSERROR.toString()); } else { order.setOrdStatusCd(ordStatusCd); } Party party = this.partyFacadeRESTExtension.find(Integer.valueOf(orderObject.getString("partyUid"))); if (party == null) { throw new DataAccessException(ErrorCode.DATAACCESSERROR.toString()); } else { order.setPtyUidFk(party); } order.setOrderProductAssocCollection(new ArrayList<OrderProductAssoc>()); JsonArray productList = orderObject.getJsonArray("products"); for (int i = 0; i < productList.size(); i++) { JsonObject productObject = productList.getJsonObject(i); OrderProductAssoc orderProductAssoc = new OrderProductAssoc(); Product product = this.productFacadeRESTExtension.find(productObject.getInt("prdUid")); orderProductAssoc.setPrdUidFk(product); orderProductAssoc.setOrdUidFk(order); orderProductAssoc.setUpdateTs(new Date()); orderProductAssoc.setUpdateUserId(productObject.getString("updateUserId", null)); orderProductAssoc.setCreateTs(new Date()); orderProductAssoc.setCreateUserId(productObject.getString("createUserId", null)); orderProductAssoc.setOpaQuantity(productObject.getInt("quantity")); orderProductAssoc.setOpaPrice(product.getPrdPrice().multiply(BigDecimal.valueOf(productObject.getInt("quantity")))); order.getOrderProductAssocCollection().add(orderProductAssoc); } super.create(order); } catch (Exception ex) { Logger.error(LOG, FormatHelper.getStackTrace(ex)); throw new DataAccessException(ex, ErrorCode.DATAACCESSERROR); } } /** * Fetch all orders grouped by quarter for the last 4 years. For this * iteration the orders are pulled for the last four years (including the * current year), which are 2017,16,15,14 * * @return a structure of order totals grouped by quarter * * @throws com.oncore.calorders.core.exceptions.DataAccessException */ @GET @Path("fetchOrdersByQuarter") @Produces({MediaType.APPLICATION_JSON}) public OrdersByQuarterSeriesData fetchOrdersByQuarter() throws DataAccessException { List<OrderHistory> orderHistoryList = null; OrdersByQuarterSeriesData ordersByQuarterSeriesData = new OrdersByQuarterSeriesData(); OrdersByQuarterData ordersByQuarterData = null; OrderItemData orderItemData = null; Calendar cal = Calendar.getInstance(); ordersByQuarterData = new OrdersByQuarterData(); ordersByQuarterData.setName("Jan"); ordersByQuarterSeriesData.getOrdersByQuarterDataList().add(ordersByQuarterData); ordersByQuarterData = new OrdersByQuarterData(); ordersByQuarterData.setName("Apr"); ordersByQuarterSeriesData.getOrdersByQuarterDataList().add(ordersByQuarterData); ordersByQuarterData = new OrdersByQuarterData(); ordersByQuarterData.setName("Jul"); ordersByQuarterSeriesData.getOrdersByQuarterDataList().add(ordersByQuarterData); ordersByQuarterData = new OrdersByQuarterData(); ordersByQuarterData.setName("Oct"); ordersByQuarterSeriesData.getOrdersByQuarterDataList().add(ordersByQuarterData); try { Logger.debug(LOG, "Hey testing logging, the fetchOrdersByQuarter is being called!"); orderHistoryList = getEntityManager().createQuery("SELECT o FROM OrderHistory o WHERE o.createTs > '2014:01:01 15:06:39.673' ORDER BY o.createTs ASC", OrderHistory.class).getResultList(); String month = null; Integer year = null; if (CollectionUtils.isNotEmpty(orderHistoryList)) { for (OrderHistory order : orderHistoryList) { cal.setTime(order.getCreateTs()); month = this.getQuarterMonth(cal.get(Calendar.MONTH)); year = cal.get(Calendar.YEAR); if (year.equals(2015)) { year = 2015; } boolean found = false; for (OrdersByQuarterData quarter : ordersByQuarterSeriesData.getOrdersByQuarterDataList()) { if (month.equalsIgnoreCase(quarter.getName())) { found = false; if (CollectionUtils.isEmpty(quarter.getItems())) { OrderItemData item = new OrderItemData(); item.setYear(year); item.setY(1); item.setLabel(1); quarter.getItems().add(item); } else { for (OrderItemData item : quarter.getItems()) { if (year.equals(item.getYear())) { item.setY(item.getY() + 1); item.setLabel(item.getY()); found = true; break; } } if (!found) { OrderItemData item = new OrderItemData(); item.setYear(year); item.setY(1); item.setLabel(1); quarter.getItems().add(item); break; } } } } } } } catch (Exception ex) { Logger.error(LOG, FormatHelper.getStackTrace(ex)); throw new DataAccessException(ex, ErrorCode.DATAACCESSERROR); } return ordersByQuarterSeriesData; } /** * Fetch all orders grouped by status * * @return a structure of order totals grouped by status * * @throws com.oncore.calorders.core.exceptions.DataAccessException */ @GET @Path("fetchOrderStatusSummary") @Produces({MediaType.APPLICATION_JSON}) public OrderStatusSummaryData fetchOrderStatusSummary() throws DataAccessException { OrderStatusSummaryData orderStatusSummaryData = new OrderStatusSummaryData(); OrderStatusData orderStatusData = null; OrdStatusCd ordStatusCd = null; try { Logger.debug(LOG, "Hey testing logging, the fetchOrderStatusSummary is being called!"); ordStatusCd = getEntityManager().createNamedQuery("OrdStatusCd.findByCode", OrdStatusCd.class).setParameter("code", "CANC").getSingleResult(); TypedQuery<Long> query = getEntityManager().createQuery( "SELECT COUNT(o) FROM OrderHistory o WHERE o.ordStatusCd = :code", Long.class).setParameter("code", ordStatusCd); Long count = query.getSingleResult(); List<Integer> items = new ArrayList<>(1); orderStatusData = new OrderStatusData(); orderStatusData.setName("Cancelled"); items.add(count.intValue()); orderStatusData.setItems(items); orderStatusSummaryData.getItems().add(orderStatusData); ordStatusCd = getEntityManager().createNamedQuery("OrdStatusCd.findByCode", OrdStatusCd.class).setParameter("code", "PRCS").getSingleResult(); query = getEntityManager().createQuery( "SELECT COUNT(o) FROM OrderHistory o WHERE o.ordStatusCd = :code", Long.class).setParameter("code", ordStatusCd); count = query.getSingleResult(); items = new ArrayList<>(1); orderStatusData = new OrderStatusData(); orderStatusData.setName("Processing"); items.add(count.intValue()); orderStatusData.setItems(items); orderStatusSummaryData.getItems().add(orderStatusData); ordStatusCd = getEntityManager().createNamedQuery("OrdStatusCd.findByCode", OrdStatusCd.class).setParameter("code", "SHIP").getSingleResult(); query = getEntityManager().createQuery( "SELECT COUNT(o) FROM OrderHistory o WHERE o.ordStatusCd = :code", Long.class).setParameter("code", ordStatusCd); count = query.getSingleResult(); items = new ArrayList<>(1); orderStatusData = new OrderStatusData(); orderStatusData.setName("Shipped"); items.add(count.intValue()); orderStatusData.setItems(items); orderStatusSummaryData.getItems().add(orderStatusData); ordStatusCd = getEntityManager().createNamedQuery("OrdStatusCd.findByCode", OrdStatusCd.class).setParameter("code", "SUBT").getSingleResult(); query = getEntityManager().createQuery( "SELECT COUNT(o) FROM OrderHistory o WHERE o.ordStatusCd = :code", Long.class).setParameter("code", ordStatusCd); count = query.getSingleResult(); items = new ArrayList<>(1); orderStatusData = new OrderStatusData(); orderStatusData.setName("Submitted"); items.add(count.intValue()); orderStatusData.setItems(items); orderStatusSummaryData.getItems().add(orderStatusData); } catch (Exception ex) { Logger.error(LOG, FormatHelper.getStackTrace(ex)); throw new DataAccessException(ex, ErrorCode.DATAACCESSERROR); } return orderStatusSummaryData; } /** * Fetch all orders by PartyUid and ordered by Date ascending * * @return a structure of orders history ordered by Date * * @throws com.oncore.calorders.core.exceptions.DataAccessException */ @GET @Path("findAllOrderHistoryByPartyUid/{partyUid}") @Produces({MediaType.APPLICATION_JSON}) public List<OrderHistoryData> findAllOrderHistoryByPartyUid(@PathParam("partyUid") Integer partyUid) throws DataAccessException { List<OrderHistoryData> orderHistoryDatas = new ArrayList<OrderHistoryData>(); List<OrderHistory> orderHistorys = new ArrayList<OrderHistory>(); orderHistorys = getEntityManager().createQuery("SELECT oh FROM OrderHistory oh join oh.ordStatusCd os join oh.ptyUidFk pt join pt.groupPartyAssocCollection gpa join gpa.grpUidFk g join g.depUidFk d WHERE pt.ptyUid = :partyUid ORDER BY oh.createTs DESC", OrderHistory.class).setParameter("partyUid", partyUid).getResultList(); if (orderHistorys != null && orderHistorys.size() > 0) { for (OrderHistory orderHistory : orderHistorys) { OrderHistoryData data = new OrderHistoryData(); data.setOrderHistoryId(orderHistory.getOrdUid()); if (orderHistory.getPtyUidFk() != null && orderHistory.getPtyUidFk().getGroupPartyAssocCollection() != null && orderHistory.getPtyUidFk().getGroupPartyAssocCollection().size() > 0) { for (GroupPartyAssoc assoc : orderHistory.getPtyUidFk().getGroupPartyAssocCollection()) { if (assoc.getGrpUidFk() != null && assoc.getGrpUidFk().getDepUidFk() != null) { data.setOrderAgency(assoc.getGrpUidFk().getDepUidFk().getDepName()); break; } } } data.setOrderDate(orderHistory.getCreateTs()); if (orderHistory.getOrderProductAssocCollection() != null && orderHistory.getOrderProductAssocCollection().size() > 0) { String skuConcat = new String(); List<OrderProductAssoc> productAssocs = new ArrayList<OrderProductAssoc>(); orderHistory.getOrderProductAssocCollection().forEach((assoc) -> { productAssocs.add(assoc); }); for (int i = 0; i < productAssocs.size(); i++) { if (skuConcat.length() > 25) { skuConcat = skuConcat + "..."; break; } if (productAssocs.get(i).getPrdUidFk() != null && productAssocs.get(i).getPrdUidFk().getPrdSku() != null) { if (i == 0) { skuConcat = productAssocs.get(i).getPrdUidFk().getPrdSku(); } else { skuConcat = skuConcat + ", " + productAssocs.get(i).getPrdUidFk().getPrdSku(); } } } data.setOrderDescription(skuConcat.trim()); } data.setOrderPoNumber(null); if (orderHistory.getOrderProductAssocCollection() != null && orderHistory.getOrderProductAssocCollection().size() > 0) { BigDecimal totalPrice = new BigDecimal(BigInteger.ZERO); for (OrderProductAssoc assoc : orderHistory.getOrderProductAssocCollection()) { totalPrice = totalPrice.add(assoc.getOpaPrice()); } data.setOrderPrice(NumberFormat.getCurrencyInstance().format(totalPrice)); } if (orderHistory.getOrdStatusCd() != null) { data.setOrderStatus(orderHistory.getOrdStatusCd().getShortDesc()); } orderHistoryDatas.add(data); } } return orderHistoryDatas; } private String getQuarterMonth(int month) { String result = "Jan"; switch (month) { case 1: result = "Jan"; break; case 2: result = "Jan"; break; case 3: result = "Jan"; break; case 4: result = "Apr"; break; case 5: result = "Apr"; break; case 6: result = "Apr"; break; case 7: result = "Jul"; break; case 8: result = "Jul"; break; case 9: result = "Jul"; break; case 10: result = "Oct"; break; case 11: result = "Oct"; break; case 12: result = "Oct"; break; default: result = "Jan"; } return result; } }
package com.navigation.reactnative; import android.app.Activity; import android.app.ActivityOptions; import android.app.SharedElementCallback; import android.content.Context; import android.content.Intent; import android.content.res.TypedArray; import android.os.Build; import android.os.Bundle; import android.util.Pair; import android.view.View; import android.view.ViewGroup; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.views.image.ReactImageView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; public class NavigationStackView extends ViewGroup { private ArrayList<String> sceneKeys = new ArrayList<>(); public static HashMap<String, SceneView> scenes = new HashMap<>(); protected ReadableArray keys; private Activity mainActivity; private int oldCrumb = -1; private String oldKey; protected String enterAnim; protected String exitAnim; protected ReadableArray sharedElementNames; protected ReadableArray oldSharedElementNames; protected boolean finish = false; private int activityOpenEnterAnimationId; private int activityOpenExitAnimationId; private int activityCloseEnterAnimationId; private int activityCloseExitAnimationId; public NavigationStackView(Context context) { super(context); TypedArray activityStyle = context.getTheme().obtainStyledAttributes(new int[] {android.R.attr.windowAnimationStyle}); int windowAnimationStyleResId = activityStyle.getResourceId(0, 0); activityStyle.recycle(); activityStyle = context.getTheme().obtainStyledAttributes(windowAnimationStyleResId, new int[] { android.R.attr.activityOpenEnterAnimation, android.R.attr.activityOpenExitAnimation, android.R.attr.activityCloseEnterAnimation, android.R.attr.activityCloseExitAnimation }); activityOpenEnterAnimationId = activityStyle.getResourceId(0, 0); activityOpenExitAnimationId = activityStyle.getResourceId(1, 0); activityCloseEnterAnimationId = activityStyle.getResourceId(2, 0); activityCloseExitAnimationId = activityStyle.getResourceId(3, 0); activityStyle.recycle(); } @Override public void addView(View child, int index) { SceneView scene = (SceneView) child; sceneKeys.add(index, scene.sceneKey); scenes.put(scene.sceneKey, scene); } @Override public void removeViewAt(int index) { String sceneKey = sceneKeys.remove(index); scenes.remove(sceneKey); } protected void onAfterUpdateTransaction() { Activity currentActivity = ((ThemedReactContext) getContext()).getCurrentActivity(); if (currentActivity == null) return; if (mainActivity == null) mainActivity = currentActivity; if (finish) { mainActivity.finish(); return; } if (scenes.size() == 0) return; int crumb = keys.size() - 1; int currentCrumb = oldCrumb; if (crumb < currentCrumb) { Intent intent = new Intent(getContext(), SceneActivity.getActivity(crumb)); String key = keys.getString(crumb); intent.putExtra(SceneActivity.KEY, key); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); int enter = getAnimationResourceId(enterAnim, activityCloseEnterAnimationId); int exit = getAnimationResourceId(exitAnim, activityCloseExitAnimationId); final HashMap<String, View> oldSharedElementsMap = getSharedElementMap(); boolean orientationChanged = currentActivity.getIntent().getIntExtra(SceneActivity.ORIENTATION, 0) != currentActivity.getResources().getConfiguration().orientation; Pair[] oldSharedElements = (!orientationChanged && crumb < 20 && currentCrumb - crumb == 1) ? getSharedElements(oldSharedElementsMap, oldSharedElementNames) : null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && oldSharedElements != null && oldSharedElements.length != 0) { final SharedElementTransitioner transitioner = new SharedElementTransitioner(currentActivity, getSharedElementSet(oldSharedElementNames)); currentActivity.setEnterSharedElementCallback(new SharedElementCallback() { @Override public void onMapSharedElements(List<String> names, Map<String, View> elements) { names.clear(); elements.clear(); for(int i = 0; i < oldSharedElementNames.size(); i++) { String name = oldSharedElementNames.getString(i); names.add(name); if (oldSharedElementsMap.containsKey(name)) { View oldSharedElement = oldSharedElementsMap.get(name); elements.put(name, oldSharedElement); SharedElementView oldSharedElementView = (SharedElementView) oldSharedElement.getParent(); transitioner.load(name, oldSharedElementView.exitTransition); } } } }); currentActivity.finishAfterTransition(); } else { currentActivity.navigateUpTo(intent); } currentActivity.overridePendingTransition(enter, exit); } if (crumb > currentCrumb) { Intent[] intents = new Intent[crumb - currentCrumb]; for(int i = 0; i < crumb - currentCrumb; i++) { int nextCrumb = currentCrumb + i + 1; Intent intent = new Intent(getContext(), SceneActivity.getActivity(nextCrumb)); String key = keys.getString(nextCrumb); intent.putExtra(SceneActivity.KEY, key); intent.putExtra(SceneActivity.ORIENTATION, currentActivity.getResources().getConfiguration().orientation); intents[i] = intent; } int enter = getAnimationResourceId(enterAnim, activityOpenEnterAnimationId); int exit = getAnimationResourceId(exitAnim, activityOpenExitAnimationId); final HashMap<String, View> sharedElementsMap = getSharedElementMap(); final Pair[] sharedElements = crumb - currentCrumb == 1 ? getSharedElements(sharedElementsMap, sharedElementNames) : null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && sharedElements != null && sharedElements.length != 0) { intents[0].putExtra(SceneActivity.SHARED_ELEMENTS, getSharedElementSet(sharedElementNames)); currentActivity.setExitSharedElementCallback(new SharedElementCallback() { @Override public void onSharedElementEnd(List<String> names, List<View> elements, List<View> snapshots) { for (View view : elements) { if (view instanceof ReactImageView) ((ReactImageView) view).getDrawable().setVisible(true, true); } } @Override public void onMapSharedElements(List<String> names, Map<String, View> elements) { elements.clear(); for(String name : names) { if (sharedElementsMap.containsKey(name)) elements.put(name, sharedElementsMap.get(name)); } } }); @SuppressWarnings("unchecked") Bundle bundle = ActivityOptions.makeSceneTransitionAnimation(currentActivity, sharedElements).toBundle(); currentActivity.startActivity(intents[0], bundle); } else { currentActivity.startActivities(intents); } currentActivity.overridePendingTransition(enter, exit); } if (crumb == currentCrumb && !oldKey.equals(keys.getString(crumb))) { Intent intent = new Intent(getContext(), SceneActivity.getActivity(crumb)); String key = keys.getString(crumb); intent.putExtra(SceneActivity.KEY, key); int enter = getAnimationResourceId(enterAnim, activityOpenEnterAnimationId); int exit = getAnimationResourceId(exitAnim, activityOpenExitAnimationId); currentActivity.finish(); currentActivity.startActivity(intent); currentActivity.overridePendingTransition(enter, exit); } oldCrumb = keys.size() - 1; oldKey = keys.getString(oldCrumb); } @Override public int getChildCount() { return scenes.size(); } @Override public View getChildAt(int index) { return scenes.get(sceneKeys.get(index)); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); onAfterUpdateTransaction(); } @Override public void onDetachedFromWindow() { Activity currentActivity = ((ThemedReactContext) getContext()).getCurrentActivity(); if (keys.size() > 0 && currentActivity != null) { Intent mainIntent = mainActivity.getIntent(); mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); currentActivity.navigateUpTo(mainIntent); } scenes.clear(); super.onDetachedFromWindow(); } private int getAnimationResourceId(String animationName, int defaultId) { if(((ThemedReactContext) getContext()).getCurrentActivity() == mainActivity) return -1; if (animationName == null) return defaultId; String packageName = getContext().getPackageName(); return getContext().getResources().getIdentifier(animationName, "anim", packageName); } private HashSet<String> getSharedElementSet(ReadableArray sharedElementNames) { HashSet<String> sharedElementSet = new HashSet<>(); for(int i = 0; i < sharedElementNames.size(); i++) { sharedElementSet.add(sharedElementNames.getString(i)); } return sharedElementSet; } private HashMap<String, View> getSharedElementMap() { Activity currentActivity = ((ThemedReactContext) getContext()).getCurrentActivity(); if (!(currentActivity instanceof SceneActivity)) return null; SceneView scene = ((SceneActivity) currentActivity).scene; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return null; HashMap<String, View> sharedElementMap = new HashMap<>(); for(View sharedElement : scene.sharedElements) { sharedElementMap.put(sharedElement.getTransitionName(), sharedElement); } return sharedElementMap; } private Pair[] getSharedElements(HashMap<String, View> sharedElementMap, ReadableArray sharedElementNames) { if (sharedElementMap == null || sharedElementNames == null) return null; ArrayList<Pair> sharedElementPairs = new ArrayList<>(); for(int i = 0; i < sharedElementNames.size(); i++) { String name = sharedElementNames.getString(i); if (sharedElementMap.containsKey(name)) sharedElementPairs.add(Pair.create(sharedElementMap.get(name), name)); } return sharedElementPairs.toArray(new Pair[0]); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { } }
package ucar.nc2.util; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Test TableParser.readTable * * @author caron * @since 4/19/12 */ public class TestTableParser { static final String testName3 = "/resources/nj22/tables/nexrad.tbl"; static final String testRepeat = "C:\\data\\ghcnm\\ghcnm.v3.0.0-beta1.20101207.qae.dat"; // LOOK put this into cdmUnitTest @Test public void testReadNexradTable() throws IOException { Class c = TableParser.class; InputStream is = c.getResourceAsStream(testName3); List<TableParser.Record> recs = TableParser.readTable(is, "3,15,54,60d,67d,73d", 50000); TableParser.Record rec = recs.get(0); Assert.assertEquals("TLX", rec.get(0)); Assert.assertEquals(" 000001", rec.get(1)); Assert.assertEquals(" OKLAHOMA_CITY/Norman OK US", rec.get(2)); Assert.assertEquals(3532.0, (Double)rec.get(3), 0.1); Assert.assertEquals(-9727.0, (Double)rec.get(4), 0.1); Assert.assertEquals(370.0, (Double)rec.get(5), 0.1); rec = recs.get(20); Assert.assertEquals("TWX", rec.get(0)); Assert.assertEquals(" 000554", rec.get(1)); Assert.assertEquals(" TOPEKA/Alma KS US", rec.get(2)); Assert.assertEquals(3898.0, (Double)rec.get(3), 0.1); Assert.assertEquals(-9622.0, (Double)rec.get(4), 0.1); Assert.assertEquals(417.0, (Double)rec.get(5), 0.1); } @Test @Ignore("ghcnm.v3.0.0-beta1.20101207.qae.dat isn't in repo") public void testReadgGghcnmTable() throws IOException { List<TableParser.Record> recs = TableParser.readTable(testRepeat, "11L,15i,19,(24i,25,26,27)*10", 5); for (TableParser.Record record : recs) { for (int j = 0; j < record.values.size(); j++) { Object s = record.values.get(j); System.out.print(" " + s.toString()); } System.out.println(); } } }
package com.quickblox.q_municate.ui.activities.authorization; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TextInputLayout; import android.text.TextUtils; import android.util.Log; import android.widget.EditText; import com.afollestad.materialdialogs.MaterialDialog; import com.digits.sdk.android.AuthCallback; import com.digits.sdk.android.DigitsException; import com.digits.sdk.android.DigitsOAuthSigning; import com.digits.sdk.android.DigitsSession; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.login.LoginResult; import com.quickblox.auth.QBAuth; import com.quickblox.auth.model.QBProvider; import com.quickblox.auth.session.QBSessionManager; import com.quickblox.core.exception.QBResponseException; import com.quickblox.q_municate.App; import com.quickblox.q_municate.R; import com.quickblox.q_municate.ui.activities.base.BaseActivity; import com.quickblox.q_municate.ui.activities.main.MainActivity; import com.quickblox.q_municate.ui.fragments.dialogs.UserAgreementDialogFragment; import com.quickblox.q_municate.utils.helpers.FlurryAnalyticsHelper; import com.quickblox.q_municate.utils.helpers.GoogleAnalyticsHelper; import com.quickblox.q_municate.utils.helpers.FacebookHelper; import com.quickblox.q_municate.utils.helpers.TwitterDigitsHelper; import com.quickblox.q_municate_auth_service.QMAuthService; import com.quickblox.q_municate_core.core.command.Command; import com.quickblox.q_municate_core.models.AppSession; import com.quickblox.q_municate_core.models.LoginType; import com.quickblox.q_municate_core.models.UserCustomData; import com.quickblox.q_municate_core.qb.commands.QBUpdateUserCommand; import com.quickblox.q_municate_core.qb.commands.rest.QBLoginCompositeCommand; import com.quickblox.q_municate_core.qb.commands.rest.QBSocialLoginCommand; import com.quickblox.q_municate_core.service.QBServiceConsts; import com.quickblox.q_municate_core.utils.ConstsCore; import com.quickblox.q_municate_core.utils.UserFriendUtils; import com.quickblox.q_municate_core.utils.Utils; import com.quickblox.q_municate_core.utils.helpers.CoreSharedHelper; import com.quickblox.q_municate_db.managers.DataManager; import com.quickblox.q_municate_db.utils.ErrorUtils; import com.quickblox.q_municate_user_service.QMUserService; import com.quickblox.q_municate_user_service.model.QMUser; import com.quickblox.users.QBUsers; import com.quickblox.users.model.QBUser; import com.twitter.sdk.android.core.TwitterAuthConfig; import com.twitter.sdk.android.core.TwitterAuthToken; import com.twitter.sdk.android.core.TwitterCore; import java.util.Map; import java.util.concurrent.Callable; import butterknife.Bind; import butterknife.OnTextChanged; import rx.Observable; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; public abstract class BaseAuthActivity extends BaseActivity { private static String TAG = BaseAuthActivity.class.getSimpleName(); protected static final String STARTED_LOGIN_TYPE = "started_login_type"; @Nullable @Bind(R.id.email_textinputlayout) protected TextInputLayout emailTextInputLayout; @Nullable @Bind(R.id.email_edittext) protected EditText emailEditText; @Nullable @Bind(R.id.password_textinputlayout) protected TextInputLayout passwordTextInputLayout; @Nullable @Bind(R.id.password_edittext) protected EditText passwordEditText; protected FacebookHelper facebookHelper; protected TwitterDigitsHelper twitterDigitsHelper; protected LoginType loginType = LoginType.EMAIL; protected Resources resources; protected LoginSuccessAction loginSuccessAction; protected SocialLoginSuccessAction socialLoginSuccessAction; protected FailAction failAction; private TwitterDigitsAuthCallback twitterDigitsAuthCallback; private QMAuthService authService; private QMUserService userService; public static void start(Context context) { Intent intent = new Intent(context, BaseAuthActivity.class); context.startActivity(intent); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initFields(savedInstanceState); } @Override public void onStart() { super.onStart(); facebookHelper.onActivityStart(); } @Override protected void onResume() { super.onResume(); addActions(); } @Override protected void onPause() { super.onPause(); removeActions(); } @Override public void onStop() { super.onStop(); facebookHelper.onActivityStop(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STARTED_LOGIN_TYPE, loginType); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); facebookHelper.onActivityResult(requestCode, resultCode, data); } @Nullable @OnTextChanged(R.id.email_edittext) void onTextChangedEmail(CharSequence text) { emailTextInputLayout.setError(null); } @Nullable @OnTextChanged(R.id.password_edittext) void onTextChangedPassword(CharSequence text) { passwordTextInputLayout.setError(null); } private void initFields(Bundle savedInstanceState) { resources = getResources(); if (savedInstanceState != null && savedInstanceState.containsKey(STARTED_LOGIN_TYPE)) { loginType = (LoginType) savedInstanceState.getSerializable(STARTED_LOGIN_TYPE); } facebookHelper = new FacebookHelper(this); twitterDigitsHelper = new TwitterDigitsHelper(); twitterDigitsAuthCallback = new TwitterDigitsAuthCallback(); loginSuccessAction = new LoginSuccessAction(); socialLoginSuccessAction = new SocialLoginSuccessAction(); failAction = new FailAction(); authService = QMAuthService.getInstance(); userService = QMUserService.getInstance(); } protected void startSocialLogin() { if (!appSharedHelper.isShownUserAgreement()) { UserAgreementDialogFragment .show(getSupportFragmentManager(), new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { super.onPositive(dialog); appSharedHelper.saveShownUserAgreement(true); loginWithSocial(); } }); } else { loginWithSocial(); } } private void loginWithSocial() { appSharedHelper.saveFirstAuth(true); appSharedHelper.saveSavedRememberMe(true); if (loginType.equals(LoginType.FACEBOOK)) { facebookHelper.login(new FacebookLoginCallback()); } else if (loginType.equals(LoginType.TWITTER_DIGITS)) { twitterDigitsHelper.login(twitterDigitsAuthCallback); } } protected void startMainActivity(QBUser user) { AppSession.getSession().updateUser(user); startMainActivity(); } protected void startMainActivity(boolean importInitialized) { appSharedHelper.saveUsersImportInitialized(importInitialized); startMainActivity(); } protected void startMainActivity() { MainActivity.start(BaseAuthActivity.this); finish(); } protected void parseExceptionMessage(Throwable exception) { hideProgress(); String errorMessage = exception.getMessage(); if (errorMessage != null) { if (errorMessage.equals(getString(R.string.error_bad_timestamp))) { errorMessage = getString(R.string.error_bad_timestamp_from_app); } else if (errorMessage.equals(getString(R.string.error_login_or_email_required))) { errorMessage = getString(R.string.error_login_or_email_required_from_app); } else if (errorMessage.equals(getString(R.string.error_email_already_taken)) && loginType.equals(LoginType.FACEBOOK)) { errorMessage = getString(R.string.error_email_already_taken_from_app); } else if (errorMessage.equals(getString(R.string.error_unauthorized))) { errorMessage = getString(R.string.error_unauthorized_from_app); } ErrorUtils.showError(this, errorMessage); } } protected void parseFailException(Bundle bundle) { Exception exception = (Exception) bundle.getSerializable(QBServiceConsts.EXTRA_ERROR); int errorCode = bundle.getInt(QBServiceConsts.EXTRA_ERROR_CODE); parseExceptionMessage(exception); } protected void login(String userEmail, final String userPassword) { appSharedHelper.saveFirstAuth(true); appSharedHelper.saveSavedRememberMe(true); appSharedHelper.saveUsersImportInitialized(true); QBUser user = new QBUser(null, userPassword, userEmail); ServiceManager serviceManager = new ServiceManager(this); serviceManager.login(user); } protected void performLoginSuccessAction(Bundle bundle) { QBUser user = (QBUser) bundle.getSerializable(QBServiceConsts.EXTRA_USER); performLoginSuccessAction(user); } protected void performLoginSuccessAction(QBUser user) { startMainActivity(user); // send analytics data GoogleAnalyticsHelper.pushAnalyticsData(BaseAuthActivity.this, user, "User Sign In"); FlurryAnalyticsHelper.pushAnalyticsData(BaseAuthActivity.this); } protected boolean isLoggedInToServer() { return AppSession.getSession().isLoggedIn(); } private void addActions() { addAction(QBServiceConsts.LOGIN_SUCCESS_ACTION, loginSuccessAction); addAction(QBServiceConsts.LOGIN_FAIL_ACTION, failAction); addAction(QBServiceConsts.SOCIAL_LOGIN_SUCCESS_ACTION, socialLoginSuccessAction); addAction(QBServiceConsts.SOCIAL_LOGIN_FAIL_ACTION, failAction); addAction(QBServiceConsts.SIGNUP_FAIL_ACTION, failAction); updateBroadcastActionList(); } private void removeActions() { removeAction(QBServiceConsts.LOGIN_SUCCESS_ACTION); removeAction(QBServiceConsts.LOGIN_FAIL_ACTION); removeAction(QBServiceConsts.SOCIAL_LOGIN_SUCCESS_ACTION); removeAction(QBServiceConsts.SOCIAL_LOGIN_FAIL_ACTION); removeAction(QBServiceConsts.SIGNUP_FAIL_ACTION); updateBroadcastActionList(); } protected void startLandingScreen() { LandingActivity.start(this); finish(); } private boolean hasUserCustomData(QBUser user) { if (TextUtils.isEmpty(user.getCustomData())) { return false; } UserCustomData userCustomData = Utils.customDataToObject(user.getCustomData()); return userCustomData != null; } private Observable<QBUser> updateUserObservable(final QBUser user) { return Observable.fromCallable(new Callable<QBUser>() { @Override public QBUser call() throws Exception { return updateUser(user); } }); } private QBUser updateUser(QBUser inputUser) throws QBResponseException { QBUser user; String password = inputUser.getPassword(); UserCustomData userCustomDataNew = getUserCustomData(inputUser); inputUser.setCustomData(Utils.customDataToString(userCustomDataNew)); inputUser.setPassword(null); inputUser.setOldPassword(null); user = QBUsers.updateUser(inputUser).perform(); if (LoginType.EMAIL.equals(AppSession.getSession().getLoginType())) { user.setPassword(password); } else { user.setPassword(QBAuth.getSession().perform().getToken()); } return user; } private void saveOwnerUser(QBUser qbUser) { QMUser user = QMUser.convert(qbUser); QMUserService.getInstance().getUserCache().createOrUpdate(user); } private UserCustomData getUserCustomData(QBUser user) { if (TextUtils.isEmpty(user.getCustomData())) { return new UserCustomData(); } UserCustomData userCustomData = Utils.customDataToObject(user.getCustomData()); if (userCustomData != null) { return userCustomData; } else { return new UserCustomData(); } } private QBUser getFBUserWithAvatar(QBUser user) { String avatarUrl = getString(com.quickblox.q_municate_core.R.string.url_to_facebook_avatar, user.getFacebookId()); user.setCustomData(Utils.customDataToString(getUserCustomData(avatarUrl))); return user; } private QBUser getTDUserWithFullName(QBUser user) { user.setFullName(user.getPhone()); user.setCustomData(Utils.customDataToString(getUserCustomData(ConstsCore.EMPTY_STRING))); return user; } private UserCustomData getUserCustomData(String avatarUrl) { String isImport = "1"; // TODO: temp, first FB or TD login (for correct work need use crossplatform) return new UserCustomData(avatarUrl, ConstsCore.EMPTY_STRING, isImport); } private class LoginSuccessAction implements Command { @Override public void execute(Bundle bundle) throws Exception { performLoginSuccessAction(bundle); } } private class SocialLoginSuccessAction implements Command { @Override public void execute(Bundle bundle) throws Exception { QBUser user = (QBUser) bundle.getSerializable(QBServiceConsts.EXTRA_USER); QBUpdateUserCommand.start(BaseAuthActivity.this, user, null); performLoginSuccessAction(bundle); } } private class FailAction implements Command { @Override public void execute(Bundle bundle) throws Exception { parseFailException(bundle); } } private class FacebookLoginCallback implements FacebookCallback<LoginResult> { @Override public void onSuccess(LoginResult loginResult) { Log.d(TAG, "+++ FacebookCallback call onSuccess from BaseAuthActivity +++"); showProgress(); authService.login(QBProvider.FACEBOOK, loginResult.getAccessToken().getToken(), null) .flatMap(new Func1<QBUser, Observable<QBUser>>() { @Override public Observable<QBUser> call(final QBUser user) { CoreSharedHelper.getInstance().saveUsersImportInitialized(false); getFBUserWithAvatar(user); return updateUserObservable(user); } }) .subscribeOn(Schedulers.io()) .subscribe(new Observer<QBUser>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Log.d(TAG, "onError " + e.getMessage()); parseExceptionMessage(e); } @Override public void onNext(QBUser qbUser) { performLoginSuccessAction(qbUser); } }); } @Override public void onCancel() { Log.d(TAG, "+++ FacebookCallback call onCancel from BaseAuthActivity +++"); hideProgress(); } @Override public void onError(FacebookException error) { Log.d(TAG, "+++ FacebookCallback call onCancel BaseAuthActivity +++"); hideProgress(); } } private class TwitterDigitsAuthCallback implements AuthCallback { @Override public void success(DigitsSession session, String phoneNumber) { Log.d(TAG, "Success login by number: " + phoneNumber); showProgress(); TwitterAuthConfig authConfig = TwitterCore.getInstance().getAuthConfig(); TwitterAuthToken authToken = session.getAuthToken(); DigitsOAuthSigning authSigning = new DigitsOAuthSigning(authConfig, authToken); Map<String, String> authHeaders = authSigning.getOAuthEchoHeadersForVerifyCredentials(); authService.login(QBProvider.TWITTER_DIGITS, authHeaders.get(TwitterDigitsHelper.PROVIDER), authHeaders.get(TwitterDigitsHelper.CREDENTIALS)) .flatMap(new Func1<QBUser, Observable<QBUser>>() { @Override public Observable<QBUser> call(final QBUser user) { UserCustomData userCustomData = Utils.customDataToObject(user.getCustomData()); CoreSharedHelper.getInstance().saveUsersImportInitialized(false); getTDUserWithFullName(user); return updateUserObservable(user); } }) .subscribeOn(Schedulers.io()) .subscribe(new Observer<QBUser>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Log.d(TAG, "onError" + e.getMessage()); parseExceptionMessage(e); } @Override public void onNext(QBUser qbUser) { performLoginSuccessAction(qbUser); } }); } @Override public void failure(DigitsException error) { Log.d(TAG, "Failure!!!! error: " + error.getLocalizedMessage()); hideProgress(); } } }
package ti.modules.titanium.android.notificationmanager; import java.util.Date; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.util.TiColorHelper; import ti.modules.titanium.android.AndroidModule; import ti.modules.titanium.android.PendingIntentProxy; import ti.modules.titanium.android.RemoteViewsProxy; import android.app.Notification; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat.Builder; import android.os.Build; import java.util.HashMap; @SuppressWarnings("deprecation") @Kroll.proxy(creatableInModule = AndroidModule.class, propertyAccessors = { TiC.PROPERTY_CONTENT_TEXT, TiC.PROPERTY_CONTENT_TITLE }) public class NotificationProxy extends KrollProxy { private static final String TAG = "TiNotification"; protected Builder notificationBuilder; private int flags, ledARGB, ledOnMS, ledOffMS; private Uri sound; private int audioStreamType; private HashMap wakeParams; public NotificationProxy() { super(); notificationBuilder = new NotificationCompat.Builder(TiApplication.getInstance().getApplicationContext()) .setSmallIcon(android.R.drawable.stat_sys_warning) .setWhen(System.currentTimeMillis()) .setChannelId("miscellaneous"); // NotificationChannel.DEFAULT_CHANNEL_ID //set up default values flags = Notification.FLAG_AUTO_CANCEL; audioStreamType = Notification.STREAM_DEFAULT; wakeParams = new HashMap(); } @Override public void handleCreationDict(KrollDict d) { super.handleCreationDict(d); if (d == null) { return; } if (d.containsKey(TiC.PROPERTY_ICON)) { setIcon(d.get(TiC.PROPERTY_ICON)); } if (d.containsKey(TiC.PROPERTY_LARGE_ICON)) { setLargeIcon(d.get(TiC.PROPERTY_LARGE_ICON)); } if (d.containsKey(TiC.PROPERTY_COLOR)) { setColor(TiConvert.toString(d, TiC.PROPERTY_COLOR)); } if (d.containsKey(TiC.PROPERTY_TICKER_TEXT)) { setTickerText(TiConvert.toString(d, TiC.PROPERTY_TICKER_TEXT)); } if (d.containsKey(TiC.PROPERTY_WHEN)) { setWhen(d.get(TiC.PROPERTY_WHEN)); } if (d.containsKey(TiC.PROPERTY_AUDIO_STREAM_TYPE)) { setAudioStreamType(TiConvert.toInt(d, TiC.PROPERTY_AUDIO_STREAM_TYPE)); } if (d.containsKey(TiC.PROPERTY_CHANNEL_ID)) { setChannelId(d.getString(TiC.PROPERTY_CHANNEL_ID)); } if (d.containsKey(TiC.PROPERTY_CONTENT_VIEW)) { setContentView((RemoteViewsProxy) d.get(TiC.PROPERTY_CONTENT_VIEW)); } if (d.containsKey(TiC.PROPERTY_CONTENT_INTENT)) { setContentIntent((PendingIntentProxy) d.get(TiC.PROPERTY_CONTENT_INTENT)); } if (d.containsKey(TiC.PROPERTY_DEFAULTS)) { setDefaults(TiConvert.toInt(d, TiC.PROPERTY_DEFAULTS)); } if (d.containsKey(TiC.PROPERTY_DELETE_INTENT)) { setDeleteIntent((PendingIntentProxy) d.get(TiC.PROPERTY_DELETE_INTENT)); } if (d.containsKey(TiC.PROPERTY_FLAGS)) { setFlags(TiConvert.toInt(d, TiC.PROPERTY_FLAGS)); } if (d.containsKey(TiC.PROPERTY_LED_ARGB)) { setLedARGB(TiConvert.toInt(d, TiC.PROPERTY_LED_ARGB)); } if (d.containsKey(TiC.PROPERTY_LED_OFF_MS)) { setLedOffMS(TiConvert.toInt(d, TiC.PROPERTY_LED_OFF_MS)); } if (d.containsKey(TiC.PROPERTY_LED_ON_MS)) { setLedOnMS(TiConvert.toInt(d, TiC.PROPERTY_LED_ON_MS)); } if (d.containsKey(TiC.PROPERTY_NUMBER)) { setNumber(TiConvert.toInt(d, TiC.PROPERTY_NUMBER)); } if (d.containsKey(TiC.PROPERTY_SOUND)) { setSound(TiConvert.toString(d, TiC.PROPERTY_SOUND)); } if (d.containsKey(TiC.PROPERTY_STYLE)) { setStyle((StyleProxy) d.get(TiC.PROPERTY_STYLE)); } if (d.containsKey(TiC.PROPERTY_VIBRATE_PATTERN)) { setVibratePattern((Object[]) d.get(TiC.PROPERTY_VIBRATE_PATTERN)); } if (d.containsKey(TiC.PROPERTY_VISIBILITY)) { setVisibility(TiConvert.toInt(d, TiC.PROPERTY_VISIBILITY)); } if (d.containsKey(TiC.PROPERTY_CATEGORY)) { setCategory(TiConvert.toString(d, TiC.PROPERTY_CATEGORY)); } if (d.containsKey(TiC.PROPERTY_PRIORITY)) { setPriority(TiConvert.toInt(d, TiC.PROPERTY_PRIORITY)); } if (d.containsKey(TiC.PROPERTY_GROUP_KEY)) { setGroupKey(TiConvert.toString(d, TiC.PROPERTY_GROUP_KEY)); } if (d.containsKey(TiC.PROPERTY_GROUP_ALERT_BEHAVIOR)) { setGroupAlertBehavior(TiConvert.toInt(d, TiC.PROPERTY_GROUP_ALERT_BEHAVIOR)); } if (d.containsKey(TiC.PROPERTY_GROUP_SUMMARY)) { setGroupSummary(TiConvert.toBoolean(d, TiC.PROPERTY_GROUP_SUMMARY)); } if (d.containsKey(TiC.PROPERTY_WAKE_LOCK)) { setWakeLock((HashMap) d.get(TiC.PROPERTY_WAKE_LOCK)); } checkLatestEventInfoProperties(d); } // clang-format off @Kroll.method @Kroll.setProperty public void setCategory(String category) // clang-format on { notificationBuilder.setCategory(category); setProperty(TiC.PROPERTY_CATEGORY, category); } // clang-format off @Kroll.method @Kroll.setProperty public void setIcon(Object icon) // clang-format on { if (icon instanceof Number) { notificationBuilder.setSmallIcon(((Number) icon).intValue()); } else { String iconUrl = TiConvert.toString(icon); if (iconUrl == null) { Log.e(TAG, "Url is null"); return; } String iconFullUrl = resolveUrl(null, iconUrl); notificationBuilder.setSmallIcon(TiUIHelper.getResourceId(iconFullUrl)); } setProperty(TiC.PROPERTY_ICON, icon); } // clang-format off @Kroll.method @Kroll.setProperty public void setLargeIcon(Object icon) // clang-format on { if (icon instanceof Number) { Bitmap largeIcon = BitmapFactory.decodeResource(TiApplication.getInstance().getResources(), ((Number) icon).intValue()); notificationBuilder.setLargeIcon(largeIcon); } else { String iconUrl = TiConvert.toString(icon); if (iconUrl == null) { Log.e(TAG, "Url is null"); return; } String iconFullUrl = resolveUrl(null, iconUrl); Bitmap largeIcon = BitmapFactory.decodeResource(TiApplication.getInstance().getResources(), TiUIHelper.getResourceId(iconFullUrl)); notificationBuilder.setLargeIcon(largeIcon); } setProperty(TiC.PROPERTY_LARGE_ICON, icon); } // clang-format off @Kroll.method @Kroll.setProperty public void setColor(String color) // clang-format on { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { notificationBuilder.setColor(TiColorHelper.parseColor(color)); } setProperty(TiC.PROPERTY_COLOR, color); } // clang-format off @Kroll.method @Kroll.setProperty public void setVisibility(int visibility) // clang-format on { notificationBuilder.setVisibility(visibility); setProperty(TiC.PROPERTY_VISIBILITY, visibility); } // clang-format off @Kroll.method @Kroll.setProperty public void setPriority(int priority) // clang-format on { notificationBuilder.setPriority(priority); setProperty(TiC.PROPERTY_PRIORITY, priority); } // clang-format off @Kroll.method @Kroll.setProperty public void setWakeLock(HashMap d) // clang-format on { if (d == null) { return; } wakeParams = d; } // clang-format off @Kroll.method @Kroll.setProperty public void setTickerText(String tickerText) // clang-format on { notificationBuilder.setTicker(tickerText); //set the javascript object setProperty(TiC.PROPERTY_TICKER_TEXT, tickerText); } // clang-format off @Kroll.method @Kroll.setProperty public void setWhen(Object when) // clang-format on { if (when instanceof Date) { notificationBuilder.setWhen(((Date) when).getTime()); } else { notificationBuilder.setWhen(((Double) TiConvert.toDouble(when)).longValue()); } setProperty(TiC.PROPERTY_WHEN, when); } // clang-format off @Kroll.method @Kroll.setProperty public void setAudioStreamType(int type) // clang-format on { audioStreamType = type; if (sound != null) { notificationBuilder.setSound(this.sound, audioStreamType); } setProperty(TiC.PROPERTY_AUDIO_STREAM_TYPE, type); } // clang-format off @Kroll.method @Kroll.setProperty public void setContentView(RemoteViewsProxy contentView) // clang-format on { notificationBuilder.setContent(contentView.getRemoteViews()); setProperty(TiC.PROPERTY_CONTENT_VIEW, contentView); } // clang-format off @Kroll.method @Kroll.setProperty public void setContentIntent(PendingIntentProxy contentIntent) // clang-format on { notificationBuilder.setContentIntent(contentIntent.getPendingIntent()); setProperty(TiC.PROPERTY_CONTENT_INTENT, contentIntent); } // clang-format off @Kroll.method @Kroll.setProperty public void setDefaults(int defaults) // clang-format on { notificationBuilder.setDefaults(defaults); setProperty(TiC.PROPERTY_DEFAULTS, defaults); } // clang-format off @Kroll.method @Kroll.setProperty public void setDeleteIntent(PendingIntentProxy deleteIntent) // clang-format on { notificationBuilder.setDeleteIntent(deleteIntent.getPendingIntent()); setProperty(TiC.PROPERTY_DELETE_INTENT, deleteIntent); } // clang-format off @Kroll.method @Kroll.setProperty public void setFlags(int flags) // clang-format on { this.flags = flags; setProperty(TiC.PROPERTY_FLAGS, flags); } // clang-format off @Kroll.method @Kroll.setProperty public void setLedARGB(int ledARGB) // clang-format on { this.ledARGB = ledARGB; notificationBuilder.setLights(this.ledARGB, ledOnMS, ledOffMS); setProperty(TiC.PROPERTY_LED_ARGB, ledARGB); } // clang-format off @Kroll.method @Kroll.setProperty public void setLedOffMS(int ledOffMS) // clang-format on { this.ledOffMS = ledOffMS; notificationBuilder.setLights(ledARGB, ledOnMS, this.ledOffMS); setProperty(TiC.PROPERTY_LED_OFF_MS, ledOffMS); } // clang-format off @Kroll.method @Kroll.setProperty public void setLedOnMS(int ledOnMS) // clang-format on { this.ledOnMS = ledOnMS; notificationBuilder.setLights(ledARGB, this.ledOnMS, ledOffMS); setProperty(TiC.PROPERTY_LED_ON_MS, ledOnMS); } // clang-format off @Kroll.method @Kroll.setProperty public void setNumber(int number) // clang-format on { notificationBuilder.setNumber(number); setProperty(TiC.PROPERTY_NUMBER, number); } // clang-format off @Kroll.method @Kroll.setProperty public void setSound(String url) // clang-format on { if (url == null) { Log.e(TAG, "Url is null"); return; } sound = Uri.parse(resolveUrl(null, url)); notificationBuilder.setSound(sound, audioStreamType); setProperty(TiC.PROPERTY_SOUND, url); } // clang-format off @Kroll.method @Kroll.setProperty public void setStyle(StyleProxy style) // clang-format on { notificationBuilder.setStyle(style.getStyle()); setProperty(TiC.PROPERTY_STYLE, style); } // clang-format off @Kroll.method @Kroll.setProperty public void setVibratePattern(Object[] pattern) // clang-format on { if (pattern != null) { long[] vibrate = new long[pattern.length]; for (int i = 0; i < pattern.length; i++) { vibrate[i] = ((Double) TiConvert.toDouble(pattern[i])).longValue(); } notificationBuilder.setVibrate(vibrate); } setProperty(TiC.PROPERTY_VIBRATE_PATTERN, pattern); } // clang-format off @Kroll.method @Kroll.setProperty public void setGroupKey(String groupKey) // clang-format on { notificationBuilder.setGroup(groupKey); setProperty(TiC.PROPERTY_GROUP_KEY, groupKey); } // clang-format off @Kroll.method @Kroll.setProperty public void setGroupAlertBehavior(int groupAlertBehavior) // clang-format on { notificationBuilder.setGroupAlertBehavior(groupAlertBehavior); setProperty(TiC.PROPERTY_GROUP_ALERT_BEHAVIOR, groupAlertBehavior); } // clang-format off @Kroll.method @Kroll.setProperty public void setGroupSummary(boolean isGroupSummary) // clang-format on { notificationBuilder.setGroupSummary(isGroupSummary); setProperty(TiC.PROPERTY_GROUP_SUMMARY, isGroupSummary); } protected void checkLatestEventInfoProperties(KrollDict d) { if (d.containsKeyAndNotNull(TiC.PROPERTY_CONTENT_TITLE) || d.containsKeyAndNotNull(TiC.PROPERTY_CONTENT_TEXT)) { String contentTitle = ""; String contentText = ""; if (d.containsKeyAndNotNull(TiC.PROPERTY_CONTENT_TITLE)) { contentTitle = TiConvert.toString(d, TiC.PROPERTY_CONTENT_TITLE); notificationBuilder.setContentTitle(contentTitle); } if (d.containsKeyAndNotNull(TiC.PROPERTY_CONTENT_TEXT)) { contentText = TiConvert.toString(d, TiC.PROPERTY_CONTENT_TEXT); notificationBuilder.setContentText(contentText); } } } @Kroll.method public void setLatestEventInfo(String contentTitle, String contentText, PendingIntentProxy contentIntent) { notificationBuilder.setContentIntent(contentIntent.getPendingIntent()) .setContentText(contentText) .setContentTitle(contentTitle); } // clang-format off @Kroll.method @Kroll.setProperty public void setChannelId(String channelId) // clang-format on { notificationBuilder.setChannelId(channelId); setProperty(TiC.PROPERTY_CHANNEL_ID, channelId); } @Kroll.method public void setProgress(int max, int progress, boolean indeterminate) { notificationBuilder.setProgress(max, progress, indeterminate); } @Kroll.method public void addAction(Object icon, String title, PendingIntentProxy pendingIntent) { int iconId = -1; if (icon instanceof Number) { iconId = ((Number) icon).intValue(); } else { String iconUrl = TiConvert.toString(icon); if (iconUrl == null) { Log.e(TAG, "Url is null"); return; } String iconFullUrl = resolveUrl(null, iconUrl); iconId = TiUIHelper.getResourceId(iconFullUrl); } if (pendingIntent == null) { Log.e(TAG, "a pending intent for the action button must be provided"); return; } notificationBuilder.addAction(iconId, title, pendingIntent.getPendingIntent()); } public Notification buildNotification() { Notification notification = notificationBuilder.build(); if (hasProperty(TiC.PROPERTY_GROUP_KEY)) { // remove FLAG_AUTO_CANCEL as this will prevent group notifications this.flags &= ~Notification.FLAG_AUTO_CANCEL; } notification.flags |= this.flags; return notification; } public HashMap getWakeParams() { return wakeParams; } @Override public String getApiName() { return "Ti.Android.Notification"; } }
package com.alexstyl.specialdates.upcoming.widget.today; import android.graphics.Color; import android.support.annotation.ColorInt; import com.alexstyl.specialdates.date.Date; class WidgetColorCalculator { private static final int MODIFIER = 15; private static final double MAX = 100.00; @ColorInt private static final int HIGHLIGHT_COLOR = Color.RED; private static final int DAYS_THRESHOLD = 3; private static final int ONE_DAY = 1; @ColorInt private final int baseColor; WidgetColorCalculator(int baseColor) { this.baseColor = baseColor; } public int getColor(Date today, Date nextEvent) { int dayDiff = today.daysDifferenceTo(nextEvent); if (dayDiff <= DAYS_THRESHOLD) { return getColorForDaysDifference(dayDiff); } return baseColor; } private int getColorForDaysDifference(int dayDiff) { float modifier = getModifier(dayDiff); return blend(baseColor, HIGHLIGHT_COLOR, modifier); } private float getModifier(int dif) { return (float) ((MAX - (dif + ONE_DAY) * MODIFIER) / MAX); } //Check:OFF // disable checkstyle checks due to the loaded of magic stuff happening private static int blend(@ColorInt int background, @ColorInt int foreground, float ratio) { if (ratio > 1f) { ratio = 1f; } else if (ratio < 0f) { ratio = 0f; } float iRatio = 1.0f - ratio; int aA = (background >> 24 & 0xff); int aR = ((background & 0xff0000) >> 16); int aG = ((background & 0xff00) >> 8); int aB = (background & 0xff); int bA = (foreground >> 24 & 0xff); int bR = ((foreground & 0xff0000) >> 16); int bG = ((foreground & 0xff00) >> 8); int bB = (foreground & 0xff); int A = (int) ((aA * iRatio) + (bA * ratio)); int R = (int) ((aR * iRatio) + (bR * ratio)); int G = (int) ((aG * iRatio) + (bG * ratio)); int B = (int) ((aB * iRatio) + (bB * ratio)); return A << 24 | R << 16 | G << 8 | B; } //Check:ON }
package uk.ac.ebi.quickgo.annotation.service.search; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument; import uk.ac.ebi.quickgo.annotation.model.Annotation; import uk.ac.ebi.quickgo.annotation.service.converter.AnnotationDocConverter; import uk.ac.ebi.quickgo.rest.search.solr.AbstractSolrQueryResultConverter; import uk.ac.ebi.quickgo.rest.search.solr.SolrQueryResultHighlightingConverter; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.solr.client.solrj.beans.DocumentObjectBinder; import org.apache.solr.common.SolrDocumentList; class SolrQueryResultConverter extends AbstractSolrQueryResultConverter<Annotation> { private final DocumentObjectBinder documentObjectBinder; private final AnnotationDocConverter annotationDocConverter; private static final Map<String,String> emptyMap = new HashMap<>(); public SolrQueryResultConverter(DocumentObjectBinder documentObjectBinder, AnnotationDocConverter annotationDocConverter){ super(); Preconditions.checkArgument(documentObjectBinder != null, "Document Object Binder cannot be null"); Preconditions.checkArgument(annotationDocConverter != null, "Gene product document converter cannot be null"); this.documentObjectBinder = documentObjectBinder; this.annotationDocConverter = annotationDocConverter; } /** * Turns SolrDocuments into instances of the Annotation DTO. * @param results * @return */ @Override protected List<Annotation> convertResults(SolrDocumentList results) { assert results != null : "Results list cannot be null"; List<AnnotationDocument> solrTermDocs = documentObjectBinder.getBeans(AnnotationDocument.class, results); List<Annotation> domainObjs = new ArrayList<>(solrTermDocs.size()); solrTermDocs.stream() .map(annotationDocConverter::convert) .forEach(domainObjs::add); assert domainObjs.size() == results.size(); return domainObjs; } }
package com.itachi1706.cheesecakeutilities.Modules.LyricFinder; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.media.MediaMetadata; import android.media.session.MediaController; import android.media.session.MediaSessionManager; import android.media.session.PlaybackState; import android.net.Uri; import android.os.Build; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v4.content.FileProvider; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; @SuppressLint("OverrideAbstract") @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public class LyricNotificationListener extends NotificationListenerService { private static MediaSessionManager mm; private static final String TAG = "LyricService"; private static boolean processing = false; public LyricNotificationListener() { // Constructor that is needed just for show } @Override public void onCreate() { super.onCreate(); mm = (MediaSessionManager) this.getSystemService(Context.MEDIA_SESSION_SERVICE); scanForControllers(); if (receiver == null) receiver = new UpdateReceiver(); IntentFilter filter = new IntentFilter(NowPlaying.Companion.getLYRIC_UPDATE()); this.registerReceiver(receiver, filter); } private void scanForControllers() { List<MediaController> controllers = mm.getActiveSessions( new ComponentName(this, LyricNotificationListener.class)); Log.d(TAG, "Found " + controllers.size() + " controllers"); if (controllers.size() >= 1) processController(controllers.get(0)); else processing = false; //noinspection UnusedAssignment controllers = null; } @Override public void onDestroy() { super.onDestroy(); if (receiver != null) this.unregisterReceiver(receiver); } private void processController(MediaController controller) { // Retrieve data if (nowPlaying == null) nowPlaying = new NowPlaying(); processMetadata(controller.getMetadata()); if (controller.getPlaybackState() != null) { processPlaybackState(controller.getPlaybackState()); } else nowPlaying.setState(NowPlaying.Companion.getSTOP()); updateData(); processing = false; Log.d(TAG, "Data Retrival Complete"); } private static NowPlaying nowPlaying = null; private void updateData() { Log.i(TAG, nowPlaying.getArtist() + " | " + nowPlaying.getTitle() + " | " + nowPlaying.getAlbum() + " | " + nowPlaying.getStateString()); sendBroadcastData(); } private void processPlaybackState(@NonNull PlaybackState state) { switch (state.getState()) { case PlaybackState.STATE_PAUSED: nowPlaying.setState(NowPlaying.Companion.getPAUSE()); break; case PlaybackState.STATE_PLAYING: nowPlaying.setState(NowPlaying.Companion.getPLAY()); break; case PlaybackState.STATE_NONE: case PlaybackState.STATE_STOPPED: default: nowPlaying.setState(NowPlaying.Companion.getSTOP()); break; } } private void processMetadata(@Nullable MediaMetadata metadata) { nowPlaying.setAlbum(metadata.getString(MediaMetadata.METADATA_KEY_ALBUM)); nowPlaying.setTitle(metadata.getString(MediaMetadata.METADATA_KEY_TITLE)); nowPlaying.setArtist(metadata.getString(MediaMetadata.METADATA_KEY_ARTIST)); nowPlaying.setAlbumart(metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART)); } // Unused @Override public void onNotificationPosted(StatusBarNotification sbn) { processNotification(sbn, "Posted"); } @Override public void onNotificationRemoved(StatusBarNotification sbn) { processNotification(sbn, "Removed"); } private void processNotification(StatusBarNotification sbn, String state) { Log.i(TAG,"Notification " + state + " ID: " + sbn.getId() + " | Time: " + sbn.getPostTime() + " | " + sbn.getPackageName()); if (sbn.getPackageName().equals(getPackageName())) return; // Don't process own notifications if (!processing) { processing = true; scanForControllers(); } } private class UpdateReceiver extends BroadcastReceiver { UpdateReceiver(){} @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Receieved broadcast, updating metadata"); sendBroadcastData(); } } private void sendBroadcastData() { if (nowPlaying == null) nowPlaying = new NowPlaying(); Intent intent = nowPlaying.generateIntent(); if (nowPlaying.getAlbumart() != null) { intent.putExtra(NowPlaying.Companion.getLYRIC_ALBUMART(), saveImageTmpAndGetUri() != null); } sendBroadcast(intent); Log.i(TAG, "Metadata Update Broadcast Sent"); } private Uri saveImageTmpAndGetUri() { //noinspection ConstantConditions File cache = new File(getExternalCacheDir(), "images_cache"); //noinspection ResultOfMethodCallIgnored cache.mkdirs(); try { FileOutputStream s = new FileOutputStream(cache + "/albumart.png"); nowPlaying.getAlbumart().compress(Bitmap.CompressFormat.PNG, 100, s); s.close(); } catch (IOException e) { Log.e(TAG, "Failed to create temp barcode file"); e.printStackTrace(); return null; } File shareFile = new File(cache, "albumart.png"); Uri contentUri = FileProvider.getUriForFile(this, this.getPackageName() + ".appupdater.provider", shareFile); if (contentUri == null) { Log.e(TAG, "Failed to share file, invalid contentUri"); return null; } return contentUri; } UpdateReceiver receiver = null; }
package org.gridsphere.portlets.core.admin.layout; import org.gridsphere.layout.*; import org.gridsphere.portlet.impl.SportletProperties; import org.gridsphere.portletcontainer.ApplicationPortlet; import org.gridsphere.portletcontainer.DefaultPortletAction; import org.gridsphere.portletcontainer.GridSphereEvent; import org.gridsphere.portletcontainer.impl.GridSphereEventImpl; import org.gridsphere.provider.event.jsr.ActionFormEvent; import org.gridsphere.provider.event.jsr.FormEvent; import org.gridsphere.provider.event.jsr.RenderFormEvent; import org.gridsphere.provider.portlet.jsr.ActionPortlet; import org.gridsphere.provider.portletui.beans.*; import org.gridsphere.services.core.content.ContentFile; import org.gridsphere.services.core.content.ContentManagerService; import org.gridsphere.services.core.registry.PortletRegistryService; import org.gridsphere.services.core.security.role.PortletRole; import org.gridsphere.services.core.security.role.RoleManagerService; import javax.portlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.*; public class LayoutManagerPortlet extends ActionPortlet { public static final String VIEW_JSP = "admin/layout/view.jsp"; private static Map<String, PortletPage> pages = new HashMap<String, PortletPage>(); private static RoleManagerService roleManagerService; private static ContentManagerService contentManagerService; private PortletRegistryService portletRegistryService = null; private PortletPageFactory pageFactory = null; private static final String SELECTED_LAYOUT = LayoutManagerPortlet.class.getName() + ".SELECTED_LAYOUT"; public void init(PortletConfig config) throws PortletException { super.init(config); roleManagerService = (RoleManagerService) createPortletService(RoleManagerService.class); contentManagerService = (ContentManagerService) createPortletService(ContentManagerService.class); portletRegistryService = (PortletRegistryService) createPortletService(PortletRegistryService.class); pageFactory = PortletPageFactory.getInstance(); DEFAULT_VIEW_PAGE = "doShowLayout"; } public void savePageDetails(ActionFormEvent event) { PortletRequest req = event.getActionRequest(); String sessionId = req.getPortletSession().getId(); PortletPage page = (PortletPage) pages.get(sessionId); String title = event.getTextFieldBean("titleTF").getValue(); page.setTitle(title); String keywords = event.getTextFieldBean("keywordsTF").getValue(); page.setKeywords(keywords); pageFactory.savePortletPageMaster(page); } public void editComponent(RenderFormEvent event) throws PortletException, IOException { PortletRequest req = event.getRenderRequest(); PortletResponse res = event.getRenderResponse(); PortletContext context = getPortletConfig().getPortletContext(); GridSphereEvent gsevent = new GridSphereEventImpl(context, (HttpServletRequest) req, (HttpServletResponse) res); String sessionId = req.getPortletSession().getId(); PortletPage page = (PortletPage) pages.get(sessionId); page.actionPerformed(gsevent); pages.put(sessionId, page); setNextState(req, DEFAULT_VIEW_PAGE); } public PortletPage createLayout(FormEvent event, PortletRequest req) throws PortletException, IOException { PortletSession session = req.getPortletSession(); String layoutId = (String) session.getAttribute(SELECTED_LAYOUT); PortletPage page = pageFactory.createPortletPageCopy(layoutId); pageFactory.setPageTheme(page, req); page.init(req, new ArrayList<ComponentIdentifier>()); return page; } /* public void doFinish(FormEvent event) throws PortletException, IOException { PortletSession session = event.getPortletRequest().getPortletSession(); session.setAttribute(SportletProperties.LAYOUT_PAGE, PortletPageFactory.USER_PAGE); session.removeAttribute(SELECTED_LAYOUT); pages.remove(session.getId()); } */ public void doSaveFrame(ActionFormEvent event) throws PortletException, IOException { PortletRequest req = event.getActionRequest(); String sessionId = req.getPortletSession().getId(); PortletPage page = (PortletPage) pages.get(sessionId); HiddenFieldBean compHF = event.getHiddenFieldBean("compHF"); String activeComp = compHF.getValue(); String reqRole = event.getListBoxBean("rolesLB").getSelectedName(); String portletClass = event.getListBoxBean("portletsLB").getSelectedName(); String label = event.getTextFieldBean("labelTF").getValue(); PortletComponent comp = page.getActiveComponent(activeComp); if (comp instanceof PortletFrame) { PortletFrame frame = (PortletFrame) comp; if (reqRole.toUpperCase().equals("NONE")) reqRole = ""; frame.setRequiredRole(reqRole); frame.setLabel(label); frame.setPortletClass(portletClass); log.debug("setting frame class to " + portletClass); RadioButtonBean istitleRB = event.getRadioButtonBean("istitleRB"); if (!istitleRB.getSelectedValue().equalsIgnoreCase("yes")) { frame.setTransparent(true); } page.init(req, new ArrayList<ComponentIdentifier>()); } pageFactory.savePortletPageMaster(page); } public void doSaveBar(ActionFormEvent event) throws PortletException, IOException { PortletRequest req = event.getActionRequest(); String sessionId = req.getPortletSession().getId(); PortletPage page = (PortletPage) pages.get(sessionId); HiddenFieldBean compHF = event.getHiddenFieldBean("compHF"); String activeComp = compHF.getValue(); PortletComponent comp = page.getActiveComponent(activeComp); if (comp instanceof PortletBar) { PortletBar bar = (PortletBar) comp; ListBoxBean colsLB = event.getListBoxBean("colsLB"); String colTemplateNum = colsLB.getSelectedName(); if (colTemplateNum != null) { PortletComponent c = createLayoutStrategy(colTemplateNum, bar.getPortletComponent()); bar.setPortletComponent(c); } } pageFactory.savePortletPageMaster(page); } public void doSaveTab(ActionFormEvent event) throws PortletException, IOException { PortletRequest req = event.getActionRequest(); String sessionId = req.getPortletSession().getId(); PortletPage page = (PortletPage) pages.get(sessionId); HiddenFieldBean compHF = event.getHiddenFieldBean("compHF"); String activeComp = compHF.getValue(); String reqRole = event.getListBoxBean("rolesLB").getSelectedName(); String name = event.getTextFieldBean("nameTF").getValue(); String label = event.getTextFieldBean("labelTF").getValue(); PortletComponent comp = page.getActiveComponent(activeComp); if (comp instanceof PortletTab) { PortletTab tab = (PortletTab) comp; if (reqRole.equalsIgnoreCase("NONE")) reqRole = ""; tab.setRequiredRole(reqRole); tab.setLabel(label); tab.setTitle(req.getLocale().getLanguage(), name); ListBoxBean colsLB = event.getListBoxBean("colsLB"); String colTemplateNum = colsLB.getSelectedName(); if (colTemplateNum != null) { PortletComponent table = createLayoutStrategy(colTemplateNum, tab.getPortletComponent()); tab.setPortletComponent(table); PortletNavMenu parent = (PortletNavMenu) tab.getParentComponent(); parent.setSelectedPortletTab(tab); } } pageFactory.savePortletPageMaster(page); } public void doSaveNewTab(ActionFormEvent event) throws PortletException, IOException { PortletRequest req = event.getActionRequest(); String sessionId = req.getPortletSession().getId(); PortletPage page = (PortletPage) pages.get(sessionId); HiddenFieldBean compHF = event.getHiddenFieldBean("compHF"); String activeComp = compHF.getValue(); String reqRole = event.getListBoxBean("rolesLB").getSelectedName(); String name = event.getTextFieldBean("nameTF").getValue(); String label = event.getTextFieldBean("labelTF").getValue(); PortletComponent comp = page.getActiveComponent(activeComp); //PortletComponent comp = active.getParentComponent(); log.debug("compHF=" + activeComp); log.debug("comp class= " + comp.getClass()); log.debug("active comp = " + comp.getComponentID()); if (comp instanceof PortletTabbedPane) { PortletTabbedPane pane = (PortletTabbedPane) comp; //System.err.println("tab name " + thistab.getTitle("en")); //PortletTabbedPane pane = (PortletTabbedPane)thistab.getParentComponent(); PortletTab tab = new PortletTab(); tab.setTitle(req.getLocale().getLanguage(), name); if (reqRole.equalsIgnoreCase("NONE")) reqRole = ""; tab.setRequiredRole(reqRole); tab.setLabel(label); if (pane.getStyle().equals("menu")) { //RadioButtonBean addSubTab = event.getRadioButtonBean("subcompRB"); //if (addSubTab.getSelectedValue().equals("double")) { PortletTabbedPane newpane = new PortletTabbedPane(); newpane.setStyle("sub-menu"); tab.setPortletComponent(newpane); /*} else { PortletRowLayout row = new PortletRowLayout(); PortletColumnLayout col = new PortletColumnLayout(); col.setWidth("100%"); row.addPortletComponent(col); PortletTableLayout table = new PortletTableLayout(); table.addPortletComponent(row); tab.setPortletComponent(table); }*/ } else if (pane.getStyle().equals("sub-menu")) { ListBoxBean colsLB = event.getListBoxBean("colsLB"); String colTemplateNum = colsLB.getSelectedName(); PortletComponent c = createLayoutStrategy(colTemplateNum, tab.getPortletComponent()); tab.setPortletComponent(c); } pane.addTab(tab); pane.setSelectedPortletTab(tab); pageFactory.savePortletPageMaster(page); page.init(req, new ArrayList<ComponentIdentifier>()); pages.put(sessionId, page); } else if (comp instanceof PortletMenu) { PortletMenu menu = (PortletMenu) comp; //System.err.println("tab name " + thistab.getTitle("en")); //PortletTabbedPane pane = (PortletTabbedPane)thistab.getParentComponent(); log.debug("creating new menu tab!"); PortletTab tab = new PortletTab(); tab.setTitle(req.getLocale().getLanguage(), name); if (reqRole.equalsIgnoreCase("NONE")) reqRole = ""; tab.setRequiredRole(reqRole); tab.setLabel(label); ListBoxBean colsLB = event.getListBoxBean("colsLB"); String colTemplateNum = colsLB.getSelectedName(); PortletComponent c = createLayoutStrategy(colTemplateNum, tab.getPortletComponent()); tab.setPortletComponent(c); menu.addTab(tab); menu.setSelectedPortletTab(tab); pageFactory.savePortletPageMaster(page); page.init(req, new ArrayList<ComponentIdentifier>()); pages.put(sessionId, page); } } public void doDeleteTab(ActionFormEvent event) throws PortletException, IOException { PortletRequest req = event.getActionRequest(); String sessionId = req.getPortletSession().getId(); PortletPage page = (PortletPage) pages.get(sessionId); HiddenFieldBean compHF = event.getHiddenFieldBean("compHF"); String activeComp = compHF.getValue(); PortletComponent comp = page.getActiveComponent(activeComp); if (comp instanceof PortletTab) { PortletTab tab = (PortletTab) comp; PortletNavMenu menu = (PortletNavMenu) tab.getParentComponent(); int index = menu.getIndexOfTab(tab); if (index < (menu.getTabCount() - 1)) { menu.setSelectedPortletTabIndex(index + 1); } else if (index > 0) { menu.setSelectedPortletTabIndex(index - 1); } menu.removeTab(tab); } pageFactory.savePortletPageMaster(page); } public void doMoveTabLeft(ActionFormEvent event) throws PortletException, IOException { PortletRequest req = event.getActionRequest(); String sessionId = req.getPortletSession().getId(); PortletPage page = (PortletPage) pages.get(sessionId); HiddenFieldBean compHF = event.getHiddenFieldBean("compHF"); String activeComp = compHF.getValue(); PortletComponent comp = page.getActiveComponent(activeComp); if (comp instanceof PortletTab) { PortletTab tab = (PortletTab) comp; PortletNavMenu pane = (PortletNavMenu) tab.getParentComponent(); int index = pane.getIndexOfTab(tab); pane.removeTab(tab); pane.insertTab(tab, index - 1); pane.setSelectedPortletTabIndex(index - 1); } pageFactory.savePortletPageMaster(page); } public void doMoveTabRight(ActionFormEvent event) throws PortletException, IOException { PortletRequest req = event.getActionRequest(); String sessionId = req.getPortletSession().getId(); PortletPage page = (PortletPage) pages.get(sessionId); HiddenFieldBean compHF = event.getHiddenFieldBean("compHF"); String activeComp = compHF.getValue(); PortletComponent comp = page.getActiveComponent(activeComp); if (comp instanceof PortletTab) { PortletTab tab = (PortletTab) comp; PortletNavMenu pane = (PortletNavMenu) tab.getParentComponent(); int index = pane.getIndexOfTab(tab); pane.removeTab(tab); pane.insertTab(tab, index + 1); pane.setSelectedPortletTabIndex(index + 1); } pageFactory.savePortletPageMaster(page); } public void doCancel(ActionFormEvent event) throws PortletException, IOException { // do nothing } public void doShowLayout(ActionFormEvent event) throws PortletException, IOException { doShowLayout(event.getActionRequest(), event.getActionResponse(), event); } public void doShowLayout(RenderFormEvent event) throws PortletException, IOException { RenderRequest req = event.getRenderRequest(); RenderResponse res = event.getRenderResponse(); doShowLayout(req, res, event); setNextState(event.getRenderRequest(), VIEW_JSP); } public void doShowLayout(PortletRequest req, PortletResponse res, FormEvent event) throws PortletException, IOException { PortletSession session = req.getPortletSession(); Set<String> layoutIds = pageFactory.getEditableLayoutIds(); // set guest page as the selected page if (session.getAttribute(SELECTED_LAYOUT) == null) { session.setAttribute(SELECTED_LAYOUT, PortletPageFactory.GUEST_PAGE); } String selectedLayout = (String) session.getAttribute(SELECTED_LAYOUT); req.setAttribute("pageName", selectedLayout); ListBoxBean layoutsLB = event.getListBoxBean("layoutsLB"); layoutsLB.clear(); for (String layoutId : layoutIds) { ListBoxItemBean item = new ListBoxItemBean(); item.setName(layoutId); item.setValue(layoutId); if (layoutId.equalsIgnoreCase(selectedLayout)) item.setSelected(true); layoutsLB.addBean(item); } String theme = (String) req.getPortletSession().getAttribute(SportletProperties.LAYOUT_THEME, PortletSession.APPLICATION_SCOPE); String renderkit = (String) req.getPortletSession().getAttribute(SportletProperties.LAYOUT_RENDERKIT, PortletSession.APPLICATION_SCOPE); ListBoxBean themesLB = event.getListBoxBean("themesLB"); themesLB.clear(); String themesPath = getPortletConfig().getPortletContext().getRealPath("/themes"); /// retrieve the current renderkit themesPath += "/" + renderkit; String[] themes = null; File f = new File(themesPath); if (f.isDirectory()) { themes = f.list(); } for (int i = 0; i < themes.length; i++) { ListBoxItemBean lb = new ListBoxItemBean(); lb.setValue(themes[i].trim()); if (themes[i].trim().equalsIgnoreCase(theme)) lb.setSelected(true); themesLB.addBean(lb); } PortletContext context = getPortletConfig().getPortletContext(); // theme has to be set before it is inited req.setAttribute(SportletProperties.LAYOUT_EDIT_MODE, "true"); String cid = (String) req.getAttribute(SportletProperties.COMPONENT_ID); String sessionId = session.getId(); String extraURI = "&" + SportletProperties.COMPONENT_ID + "=" + cid + "&" + SportletProperties.DEFAULT_PORTLET_ACTION + "=doShowLayout"; log.debug("extraURI= " + extraURI); req.setAttribute(SportletProperties.EXTRA_QUERY_INFO, extraURI); PortletPage page = (PortletPage) pages.get(sessionId); if (page == null) page = createLayout(event, req); // set page details event.getTextFieldBean("titleTF").setValue(page.getTitle()); event.getTextFieldBean("keywordsTF").setValue(page.getKeywords()); GridSphereEventImpl gsevent = new GridSphereEventImpl(context, (HttpServletRequest) req, (HttpServletResponse) res); req.setAttribute(SportletProperties.IGNORE_PARSING, "true"); String controlUI = ""; String compid = req.getParameter(SportletProperties.COMPONENT_ID_2); // put new cid in before render is called if (compid != null) { gsevent.setComponentID(compid); System.err.println("\n\n\nfound compid2 = " + compid); } String action = req.getParameter(SportletProperties.DEFAULT_PORTLET_ACTION_2); if (action != null) { gsevent.setAction(new DefaultPortletAction(action)); System.err.println("found action2 = " + action); } if (req.getParameter("usertable") != null) { page.init(req, new ArrayList<ComponentIdentifier>()); page.actionPerformed(gsevent); pageFactory.savePortletPageMaster(page); page.init(req, new ArrayList<ComponentIdentifier>()); } if (compid != null) { PortletComponent comp = page.getActiveComponent(compid); if (comp instanceof PortletFrame) { log.debug("it's a frame!"); PortletFrame frame = (PortletFrame) comp; // don't perform action on portlet frame if (action.equals(PortletFrame.DELETE_PORTLET)) { PortletComponent parent = frame.getParentComponent(); parent.remove(frame); pageFactory.savePortletPageMaster(page); } else { controlUI = "frame"; } if (!frame.getTransparent()) { req.setAttribute("isTitle", "true"); } ListBoxBean portletsLB = event.getListBoxBean("portletsLB"); Collection<ApplicationPortlet> appColl = portletRegistryService.getAllApplicationPortlets(); Locale loc = req.getLocale(); for (ApplicationPortlet app : appColl) { String concID = app.getConcretePortletID(); // we don't want to list PortletServlet loader! // if (concID.startsWith(PortletServlet.class.getName())) continue; String dispName = app.getDisplayName(loc); String descName = app.getDescription(loc); ListBoxItemBean item = new ListBoxItemBean(); item.setValue(dispName + " - " + descName); item.setName(concID); if (concID.equalsIgnoreCase(frame.getPortletClass())) item.setSelected(true); portletsLB.addBean(item); } } else if (comp instanceof PortletContent) { if (!action.equals("")) { PortletContent content = (PortletContent) comp; PortletComponent parent = content.getParentComponent(); parent.remove(content); pageFactory.savePortletPageMaster(page); } else { controlUI = "content"; ListBoxBean contentLB = event.getListBoxBean("contentLB"); List contentFiles = contentManagerService.getAllContent(); for (int i = 0; i < contentFiles.size(); i++) { ContentFile contentFile = (ContentFile) contentFiles.get(i); ListBoxItemBean item = new ListBoxItemBean(); item.setName(contentFile.getFile().getName()); item.setValue(contentFile.getFile().getName()); contentLB.addBean(item); } } } else if (comp instanceof PortletTab) { PortletTab tab = (PortletTab) comp; PortletNavMenu pane = (PortletNavMenu) tab.getParentComponent(); if (pane.getStyle().equals("menu")) { log.debug("it's a tab!"); controlUI = "tab"; createColsListBox(event, req, tab.getPortletComponent()); } else { log.debug("it's a subtab"); controlUI = "subtab"; createColsListBox(event, req, tab.getPortletComponent()); } log.debug("tab name=" + tab.getTitle(req.getLocale().getLanguage())); // if selected tab is first tab disable 'move left' button if ((pane.getIndexOfTab(tab) == 0)) { ActionSubmitBean moveLeftButton = event.getActionSubmitBean("moveLeftButton"); moveLeftButton.setDisabled(true); } // if selected tab is last tab disable 'move right' buttom if ((pane.getIndexOfTab(tab) == (pane.getTabCount() - 1))) { ActionSubmitBean moveRightButton = event.getActionSubmitBean("moveRightButton"); moveRightButton.setDisabled(true); } log.debug("invoking action on tab/subtab"); page.actionPerformed(gsevent); } else if (comp instanceof PortletBar) { PortletBar bar = (PortletBar) comp; controlUI = "bar"; createColsListBox(event, req, bar.getPortletComponent()); } boolean itsanewtab = false; if (req.getParameter("newtab") != null) { controlUI = "tab"; TextFieldBean nameTF = event.getTextFieldBean("nameTF"); nameTF.setValue(this.getLocalizedText(req, "LAYOUT_NEW_TAB2")); itsanewtab = true; comp = new PortletTab(); } else if (req.getParameter("newsubtab") != null) { controlUI = "subtab"; TextFieldBean nameTF = event.getTextFieldBean("nameTF"); nameTF.setValue(this.getLocalizedText(req, "LAYOUT_NEW_SUBTAB2")); itsanewtab = true; PortletTab tab = new PortletTab(); createColsListBox(event, req, tab.getPortletComponent()); comp = tab; } else if (req.getParameter("newmenutab") != null) { controlUI = "menu"; TextFieldBean nameTF = event.getTextFieldBean("nameTF"); nameTF.setValue(this.getLocalizedText(req, "LAYOUT_NEW_MENUTAB")); itsanewtab = true; PortletTab tab = new PortletTab(); createColsListBox(event, req, tab.getPortletComponent()); comp = tab; } if (itsanewtab) { TextFieldBean labelTF = event.getTextFieldBean("labelTF"); labelTF.setValue(""); ActionSubmitBean moveLeftButton = event.getActionSubmitBean("moveLeftButton"); moveLeftButton.setDisabled(true); ActionSubmitBean moveRightButton = event.getActionSubmitBean("moveRightButton"); moveRightButton.setDisabled(true); req.setAttribute("isnewtab", "true"); } ListBoxBean rolesLB = event.getListBoxBean("rolesLB"); rolesLB.clear(); ListBoxItemBean item = new ListBoxItemBean(); item.setValue(this.getLocalizedText(req, "LAYOUT_ROLE_NONE_REQUIRED")); item.setName("NONE"); rolesLB.addBean(item); List<PortletRole> roles = roleManagerService.getRoles(); for (PortletRole role : roles) { item = new ListBoxItemBean(); item.setValue(role.getName()); item.setName(role.getName()); if ((comp != null) && (comp.getRequiredRole() != null) && (comp.getRequiredRole().equalsIgnoreCase(role.getName()))) item.setSelected(true); rolesLB.addBean(item); } HiddenFieldBean compHF = event.getHiddenFieldBean("compHF"); compHF.setName("compid"); compHF.setValue(compid); req.setAttribute("portletComp", comp); req.setAttribute("controlUI", controlUI); } StringBuffer pageBuffer = new StringBuffer(); PortletComponent comp = page.getPortletComponent(); log.debug("rendering the component"); comp.doRender(gsevent); pageBuffer = comp.getBufferedOutput(req); //System.err.println(pageBuffer); ListBoxBean navigationLB = event.getListBoxBean("navigationLB"); navigationLB.clear(); ListBoxItemBean item = new ListBoxItemBean(); item.setName("bar"); item.setValue(this.getLocalizedText(req, "LAYOUT_SINGLE_DIVIDER")); if (comp instanceof PortletBar) { item.setSelected(true); } navigationLB.addBean(item); item = new ListBoxItemBean(); item.setName("menu"); item.setValue(this.getLocalizedText(req, "LAYOUT_MENUBAR")); if (comp instanceof PortletMenu) { item.setSelected(true); } navigationLB.addBean(item); item = new ListBoxItemBean(); item.setName("pane"); item.setValue(this.getLocalizedText(req, "LAYOUT_TABBEDPANE")); if (comp instanceof PortletTabbedPane) { item.setSelected(true); } navigationLB.addBean(item); req.setAttribute("pane", pageBuffer.toString()); pages.put(sessionId, page); // put old cid back so beans/tags work!! req.setAttribute(SportletProperties.COMPONENT_ID, cid); // remove special layout attributes so the rest of "real" layout after this portlet renders properly req.removeAttribute(SportletProperties.EXTRA_QUERY_INFO); req.removeAttribute(SportletProperties.LAYOUT_EDIT_MODE); //setNextState(req, VIEW_JSP); } public void selectLayout(ActionFormEvent event) throws PortletException, IOException { ListBoxBean layoutsLB = event.getListBoxBean("layoutsLB"); PortletSession session = event.getActionRequest().getPortletSession(); session.setAttribute(SELECTED_LAYOUT, layoutsLB.getSelectedValue()); pages.remove(session.getId()); } public void doSaveNav(ActionFormEvent event) { PortletRequest req = event.getActionRequest(); String sessionId = req.getPortletSession().getId(); PortletPage page = (PortletPage) pages.get(sessionId); PortletComponent navComp = page.getPortletComponent(); ListBoxBean navLB = event.getListBoxBean("navigationLB"); String name = navLB.getSelectedName(); if (name.equals("bar")) { // the actual component matches the selected one, do nothing if (navComp instanceof PortletBar) { return; } PortletBar bar = new PortletBar(); // set the first menu tab component to be the bar component if (navComp instanceof PortletMenu) { PortletMenu menu = (PortletMenu) navComp; List<PortletTab> tabs = menu.getPortletTabs(); PortletTab tab = tabs.get(0); bar.setPortletComponent(tab.getPortletComponent()); } // set the component of the first subtab to be the bar component if (navComp instanceof PortletTabbedPane) { PortletTabbedPane pane = (PortletTabbedPane) navComp; List<PortletTab> tabs = pane.getPortletTabs(); PortletTab tab = tabs.get(0); PortletTabbedPane subpane = (PortletTabbedPane) tab.getPortletComponent(); PortletTab subtab = subpane.getPortletTabAt(0); bar.setPortletComponent(subtab.getPortletComponent()); } page.setPortletComponent(bar); } else if (name.equals("menu")) { if (navComp instanceof PortletMenu) { return; } PortletMenu menu = new PortletMenu(); if (navComp instanceof PortletBar) { PortletBar bar = (PortletBar) navComp; PortletTab tab = new PortletTab(); tab.setTitle(req.getLocale().getLanguage(), this.getLocalizedText(req, "LAYOUT_DEFAULT_TAB_NAME")); tab.setPortletComponent(bar.getPortletComponent()); menu.addTab(tab); } if (navComp instanceof PortletTabbedPane) { PortletTabbedPane pane = (PortletTabbedPane) navComp; List<PortletTab> tabs = pane.getPortletTabs(); for (PortletTab atab : tabs) { PortletTabbedPane subpane = (PortletTabbedPane) atab.getPortletComponent(); List<PortletTab> subtabs = subpane.getPortletTabs(); menu.addTab(subtabs.get(0)); } } page.setPortletComponent(menu); } else if (name.equals("pane")) { if (navComp instanceof PortletTabbedPane) { return; } PortletTabbedPane pane = new PortletTabbedPane(); pane.setStyle("menu"); if (navComp instanceof PortletBar) { PortletTab newtab = new PortletTab(); newtab.setTitle(req.getLocale().getLanguage(), this.getLocalizedText(req, "LAYOUT_DEFAULT_TAB_NAME")); pane.addTab(newtab); PortletTabbedPane subpane = new PortletTabbedPane(); subpane.setStyle("sub-menu"); newtab.setPortletComponent(subpane); PortletTab subtab = new PortletTab(); subtab.setTitle(req.getLocale().getLanguage(), this.getLocalizedText(req, "LAYOUT_DEFAULT_TAB_NAME")); PortletTableLayout table = new PortletTableLayout(); PortletRowLayout row = new PortletRowLayout(); PortletColumnLayout col = new PortletColumnLayout(); col.setWidth("100%"); row.addPortletComponent(col); table.addPortletComponent(row); subtab.setPortletComponent(table); } else if (navComp instanceof PortletMenu) { PortletMenu menu = (PortletMenu) navComp; List<PortletTab> tabs = menu.getPortletTabs(); for (PortletTab atab : tabs) { PortletTab newtab = new PortletTab(); newtab.setTitle(req.getLocale().getLanguage(), atab.getTitle(req.getLocale().getLanguage())); pane.addTab(newtab); PortletTabbedPane subpane = new PortletTabbedPane(); subpane.setStyle("sub-menu"); newtab.setPortletComponent(subpane); subpane.addTab(atab); } } page.setPortletComponent(pane); } pageFactory.savePortletPageMaster(page); page.init(req, new ArrayList<ComponentIdentifier>()); pages.put(sessionId, page); } /** * Modifies a portlet tab to provide the desired column layout strategy given a tab * The numbering is as follows: * "one" - 1 column * "two" - 2 col, 33%, 66% * "three" - 2 col, 50%, 50% * "four" - 2 col, 66%, 33% * "five" - 3 col, 33%, 33%, 33% * "six" - 3 col 25%, 50%, 25% * * @param strategyNum the string as one of the above * @param comp a portlet component * @return the updated table layout */ private PortletComponent createLayoutStrategy(String strategyNum, PortletComponent comp) { log.debug("col strategy: " + strategyNum); if ((comp != null) && (comp instanceof PortletTableLayout)) { PortletTableLayout table = (PortletTableLayout) comp; List rows = table.getPortletComponents(); if ((rows != null) && (!rows.isEmpty())) { PortletComponent c = (PortletComponent) rows.get(0); if (c instanceof PortletRowLayout) { PortletRowLayout row = (PortletRowLayout) c; List cols = row.getPortletComponents(); System.err.println("cols size= " + cols.size()); if (cols.size() == 1) { if (strategyNum.equals("one")) { return table; } if (strategyNum.equals("two")) { // deal with case where column layout needs to be extended PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(0); PortletColumnLayout col = new PortletColumnLayout(); oldcol.setWidth("33%"); col.setWidth("66%"); row.addPortletComponent(col); } if (strategyNum.equals("three")) { PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(0); PortletColumnLayout col = new PortletColumnLayout(); oldcol.setWidth("50%"); col.setWidth("50%"); row.addPortletComponent(col); } if (strategyNum.equals("four")) { PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(0); PortletColumnLayout col = new PortletColumnLayout(); oldcol.setWidth("66%"); col.setWidth("33%"); row.addPortletComponent(col); } if (strategyNum.equals("five")) { PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(0); PortletColumnLayout col = new PortletColumnLayout(); PortletColumnLayout newcol = new PortletColumnLayout(); oldcol.setWidth("33%"); col.setWidth("33%"); newcol.setWidth("33%"); row.addPortletComponent(col); row.addPortletComponent(newcol); } if (strategyNum.equals("six")) { PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(0); PortletColumnLayout col = new PortletColumnLayout(); PortletColumnLayout newcol = new PortletColumnLayout(); oldcol.setWidth("25%"); col.setWidth("50%"); newcol.setWidth("25%"); row.addPortletComponent(col); row.addPortletComponent(newcol); } } if (cols.size() == 2) { if (strategyNum.equals("one")) { // deal with case where column layout needs to be reduced PortletColumnLayout col = (PortletColumnLayout) cols.get(0); PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(1); col.setWidth("100%"); row.removePortletComponent(oldcol); } if (strategyNum.equals("two")) { PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(0); PortletColumnLayout col = (PortletColumnLayout) cols.get(1); oldcol.setWidth("33%"); col.setWidth("66%"); } if (strategyNum.equals("three")) { PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(0); PortletColumnLayout col = (PortletColumnLayout) cols.get(1); oldcol.setWidth("50%"); col.setWidth("50%"); } if (strategyNum.equals("four")) { PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(0); PortletColumnLayout col = (PortletColumnLayout) cols.get(1); oldcol.setWidth("66%"); col.setWidth("33%"); } if (strategyNum.equals("five")) { PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(0); PortletColumnLayout col = (PortletColumnLayout) cols.get(1); PortletColumnLayout newcol = new PortletColumnLayout(); oldcol.setWidth("33%"); col.setWidth("33%"); newcol.setWidth("33%"); row.addPortletComponent(newcol); } if (strategyNum.equals("six")) { PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(0); PortletColumnLayout col = (PortletColumnLayout) cols.get(1); PortletColumnLayout newcol = new PortletColumnLayout(); oldcol.setWidth("25%"); col.setWidth("50%"); newcol.setWidth("25%"); row.addPortletComponent(newcol); } } if (cols.size() == 3) { if (strategyNum.equals("one")) { // deal with case where column layout needs to be reduced PortletColumnLayout col = (PortletColumnLayout) cols.get(0); PortletColumnLayout newcol = (PortletColumnLayout) cols.get(2); PortletColumnLayout oldcol = (PortletColumnLayout) cols.get(1); col.setWidth("100%"); row.removePortletComponent(oldcol); row.removePortletComponent(newcol); } if (strategyNum.equals("two")) { PortletColumnLayout col1 = (PortletColumnLayout) cols.get(0); PortletColumnLayout col2 = (PortletColumnLayout) cols.get(1); PortletColumnLayout col3 = (PortletColumnLayout) cols.get(2); col1.setWidth("33%"); col2.setWidth("66%"); row.removePortletComponent(col3); } if (strategyNum.equals("three")) { PortletColumnLayout col1 = (PortletColumnLayout) cols.get(0); PortletColumnLayout col2 = (PortletColumnLayout) cols.get(1); PortletColumnLayout col3 = (PortletColumnLayout) cols.get(2); col1.setWidth("50%"); col2.setWidth("50%"); row.removePortletComponent(col3); } if (strategyNum.equals("four")) { PortletColumnLayout col1 = (PortletColumnLayout) cols.get(0); PortletColumnLayout col2 = (PortletColumnLayout) cols.get(1); PortletColumnLayout col3 = (PortletColumnLayout) cols.get(2); col1.setWidth("66%"); col2.setWidth("33%"); row.removePortletComponent(col3); } if (strategyNum.equals("five")) { PortletColumnLayout col1 = (PortletColumnLayout) cols.get(0); PortletColumnLayout col2 = (PortletColumnLayout) cols.get(1); PortletColumnLayout col3 = (PortletColumnLayout) cols.get(2); col1.setWidth("33%"); col2.setWidth("33%"); col3.setWidth("33%"); } if (strategyNum.equals("six")) { PortletColumnLayout col1 = (PortletColumnLayout) cols.get(0); PortletColumnLayout col2 = (PortletColumnLayout) cols.get(1); PortletColumnLayout col3 = (PortletColumnLayout) cols.get(2); col1.setWidth("25%"); col2.setWidth("50%"); col3.setWidth("25%"); } } } } System.err.println("return comp " + comp.getClass().getName()); return table; } else { System.err.println("creating a new table"); PortletTableLayout table = new PortletTableLayout(); PortletRowLayout row = new PortletRowLayout(); if (strategyNum.equals("one")) { PortletColumnLayout col = new PortletColumnLayout(); col.setWidth("100%"); row.addPortletComponent(col); } if (strategyNum.equals("two")) { PortletColumnLayout col = new PortletColumnLayout(); PortletColumnLayout newcol = new PortletColumnLayout(); col.setWidth("33%"); row.addPortletComponent(col); col.setWidth("66%"); row.addPortletComponent(newcol); } if (strategyNum.equals("three")) { PortletColumnLayout col = new PortletColumnLayout(); PortletColumnLayout newcol = new PortletColumnLayout(); col.setWidth("50%"); row.addPortletComponent(col); col.setWidth("50%"); row.addPortletComponent(newcol); } if (strategyNum.equals("four")) { PortletColumnLayout col = new PortletColumnLayout(); PortletColumnLayout newcol = new PortletColumnLayout(); col.setWidth("66%"); row.addPortletComponent(col); col.setWidth("33%"); row.addPortletComponent(newcol); } if (strategyNum.equals("five")) { PortletColumnLayout col1 = new PortletColumnLayout(); PortletColumnLayout col2 = new PortletColumnLayout(); PortletColumnLayout col3 = new PortletColumnLayout(); col1.setWidth("33%"); row.addPortletComponent(col1); col2.setWidth("33%"); row.addPortletComponent(col2); col2.setWidth("33%"); row.addPortletComponent(col3); } if (strategyNum.equals("six")) { PortletColumnLayout col1 = new PortletColumnLayout(); PortletColumnLayout col2 = new PortletColumnLayout(); PortletColumnLayout col3 = new PortletColumnLayout(); col1.setWidth("25%"); row.addPortletComponent(col1); col2.setWidth("50%"); row.addPortletComponent(col2); col2.setWidth("25%"); row.addPortletComponent(col3); } table.addPortletComponent(row); System.err.println("return table"); return table; } } private void createColsListBox(FormEvent event, PortletRequest req, PortletComponent comp) { // TODO deal with column layouts String colType = "one"; if ((comp != null) && (comp instanceof PortletTableLayout)) { PortletTableLayout tableLayout = (PortletTableLayout) comp; List rows = tableLayout.getPortletComponents(); if ((rows != null) && (!rows.isEmpty())) { PortletComponent row = (PortletComponent) rows.get(0); if (row instanceof PortletRowLayout) { PortletRowLayout r = (PortletRowLayout) row; List cols = r.getPortletComponents(); if (cols.size() == 2) { PortletColumnLayout col = (PortletColumnLayout) cols.get(0); if (col.getWidth().equals("33%")) { colType = "two"; } if (col.getWidth().equals("50%")) { colType = "three"; } if (col.getWidth().equals("66%")) { colType = "four"; } } if (cols.size() == 3) { PortletColumnLayout col = (PortletColumnLayout) cols.get(0); if (col.getWidth().equals("33%")) { colType = "five"; } if (col.getWidth().equals("25%")) { colType = "six"; } } } } } ListBoxBean colsLB = event.getListBoxBean("colsLB"); colsLB.clear(); ListBoxItemBean one = new ListBoxItemBean(); ListBoxItemBean two = new ListBoxItemBean(); ListBoxItemBean three = new ListBoxItemBean(); ListBoxItemBean four = new ListBoxItemBean(); ListBoxItemBean five = new ListBoxItemBean(); ListBoxItemBean six = new ListBoxItemBean(); one.setValue(this.getLocalizedText(req, "LAYOUT_ONECOL")); one.setName("one"); if (colType.equals("one")) one.setSelected(true); two.setValue(this.getLocalizedText(req, "LAYOUT_TWOCOL1")); two.setName("two"); if (colType.equals("two")) two.setSelected(true); three.setValue(this.getLocalizedText(req, "LAYOUT_TWOCOL2")); three.setName("three"); if (colType.equals("three")) three.setSelected(true); four.setValue(this.getLocalizedText(req, "LAYOUT_TWOCOL3")); four.setName("four"); if (colType.equals("four")) four.setSelected(true); five.setValue(this.getLocalizedText(req, "LAYOUT_THREECOL1")); five.setName("five"); if (colType.equals("five")) five.setSelected(true); six.setValue(this.getLocalizedText(req, "LAYOUT_THREECOL2")); six.setName("six"); if (colType.equals("six")) six.setSelected(true); colsLB.addBean(one); colsLB.addBean(two); colsLB.addBean(three); colsLB.addBean(four); colsLB.addBean(five); colsLB.addBean(six); } }
package de.ptb.epics.eve.editor.gef; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.EventObject; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.draw2d.FigureCanvas; import org.eclipse.gef.DefaultEditDomain; import org.eclipse.gef.EditDomain; import org.eclipse.gef.EditPart; import org.eclipse.gef.GraphicalViewer; import org.eclipse.gef.MouseWheelHandler; import org.eclipse.gef.MouseWheelZoomHandler; import org.eclipse.gef.commands.CommandStack; import org.eclipse.gef.dnd.TemplateTransferDragSourceListener; import org.eclipse.gef.dnd.TemplateTransferDropTargetListener; import org.eclipse.gef.editparts.ScalableFreeformRootEditPart; import org.eclipse.gef.editparts.ZoomManager; import org.eclipse.gef.palette.PaletteRoot; import org.eclipse.gef.ui.actions.ActionRegistry; import org.eclipse.gef.ui.actions.DeleteAction; import org.eclipse.gef.ui.actions.ZoomInAction; import org.eclipse.gef.ui.actions.ZoomOutAction; import org.eclipse.gef.ui.palette.PaletteViewer; import org.eclipse.gef.ui.palette.PaletteViewerProvider; import org.eclipse.gef.ui.parts.ContentOutlinePage; import org.eclipse.gef.ui.parts.GraphicalEditorWithFlyoutPalette; import org.eclipse.gef.ui.parts.GraphicalViewerKeyHandler; import org.eclipse.gef.ui.parts.TreeViewer; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.MenuDetectEvent; import org.eclipse.swt.events.MenuDetectListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.ide.FileStoreEditorInput; import org.eclipse.ui.part.IPageSite; import org.eclipse.ui.progress.IProgressService; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.xml.sax.SAXException; import de.ptb.epics.eve.data.scandescription.Chain; import de.ptb.epics.eve.data.scandescription.ScanDescription; import de.ptb.epics.eve.data.scandescription.processors.ScanDescriptionLoader; import de.ptb.epics.eve.data.scandescription.updatenotification.IModelUpdateListener; import de.ptb.epics.eve.data.scandescription.updatenotification.ModelUpdateEvent; import de.ptb.epics.eve.data.scandescription.updater.VersionTooOldException; import de.ptb.epics.eve.editor.Activator; import de.ptb.epics.eve.editor.dialogs.lostdevices.LostDevicesDialog; import de.ptb.epics.eve.editor.dialogs.updater.ChangeLogDialog; import de.ptb.epics.eve.editor.gef.actions.Copy; import de.ptb.epics.eve.editor.gef.actions.Cut; import de.ptb.epics.eve.editor.gef.actions.Paste; import de.ptb.epics.eve.editor.jobs.file.Save; /** * @author Marcus Michalsky * @since 1.6 */ public class ScanDescriptionEditor extends GraphicalEditorWithFlyoutPalette implements IModelUpdateListener { private static Logger logger = Logger.getLogger(ScanDescriptionEditor.class .getName()); // editor save state private boolean dirty; private ScanDescription scanDescription; private Point contextMenuLocation; /** * Constructor. */ public ScanDescriptionEditor() { this.setEditDomain(new DefaultEditDomain(this)); } /** * {@inheritDoc} */ @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { logger.trace("init"); this.setSite(site); this.setInput(input); this.setPartName(input.getName()); this.contextMenuLocation = null; final FileStoreEditorInput fileStoreEditorInput = (FileStoreEditorInput)input; final File scanDescriptionFile = new File(fileStoreEditorInput.getURI()); if (scanDescriptionFile.isFile()) { if (scanDescriptionFile.length() == 0) { // file exists but is empty -> do not read throw new PartInitException("File is empty!"); } } else { // file does not exist -> do not read throw new PartInitException("File does not exist!"); } ScanDescriptionEditorFileLoader scmlUpdater = new ScanDescriptionEditorFileLoader(); File currentVersionScml; try { currentVersionScml = scmlUpdater.loadFile(scanDescriptionFile); } catch (VersionTooOldException e) { throw new PartInitException("File version is too old (< 2.3)!"); } if (scmlUpdater.getChanges() != null && !scmlUpdater.getChanges().isEmpty()) { ChangeLogDialog changeLogDialog = new ChangeLogDialog(PlatformUI .getWorkbench().getModalDialogShellProvider() .getShell(), scmlUpdater.getChanges()); changeLogDialog.open(); this.dirty = true; } else { this.dirty = false; } final ScanDescriptionLoader scanDescriptionLoader = new ScanDescriptionLoader(Activator.getDefault(). getMeasuringStation(), Activator.getDefault(). getSchemaFile()); try { scanDescriptionLoader.load(currentVersionScml); scanDescriptionLoader.getScanDescription().setFileName( scanDescriptionFile.getName()); this.scanDescription = scanDescriptionLoader.getScanDescription(); if (scanDescriptionLoader.getLostDevices() != null) { LostDevicesDialog dialog = new LostDevicesDialog(PlatformUI .getWorkbench().getModalDialogShellProvider() .getShell(), scanDescriptionLoader); dialog.open(); this.dirty = true; } this.scanDescription.addModelUpdateListener(this); } catch(final ParserConfigurationException e) { logger.error(e.getMessage(), e); } catch(final SAXException e) { logger.error(e.getMessage(), e); } catch(final IOException e) { logger.error(e.getMessage(), e); } this.firePropertyChange(PROP_DIRTY); // TODO add CommandStackListener super.init(site, fileStoreEditorInput); } /** * {@inheritDoc} */ @Override public void doSave(IProgressMonitor monitor) { if(!isSaveAllowed()) { return; } try { monitor.beginTask("Saving Scan Description", 3); monitor.subTask("determine file name"); String saveFileName = ((FileStoreEditorInput)this.getEditorInput()). getURI().getPath().toString(); monitor.worked(1); monitor.subTask("creating save routine"); Job saveJob = new Save("Save", saveFileName, this.scanDescription, this); monitor.worked(1); monitor.subTask("running save routine"); saveJob.setUser(true); saveJob.schedule(); monitor.worked(1); } finally { monitor.done(); } Activator.getDefault().saveDefaults(this.scanDescription); this.updatePositionCounts(); } /** * {@inheritDoc} */ @Override public void doSaveAs() { if(!isSaveAllowed()) { return; } // show dialog preconfigured with path of "last" file name final FileDialog fileDialog = new FileDialog(this.getEditorSite().getShell(), SWT.SAVE); File currentFile = new File(((FileStoreEditorInput) this.getEditorInput()).getURI()); fileDialog.setFilterPath(currentFile.getParent()); fileDialog.setFileName(currentFile.getName()); final String dialogName = fileDialog.open(); // file path where the file will be saved String saveFileName; // check dialog result if(dialogName != null) { // adjust filename to ".scml" final int lastPoint = dialogName.lastIndexOf('.'); final int lastSep = dialogName.lastIndexOf('/'); if ((lastPoint > 0) && (lastPoint > lastSep)) { saveFileName = dialogName.substring(0, lastPoint) + ".scml"; } else { saveFileName = dialogName + ".scml"; } } else { // user pressed "cancel" -> do nothing return; } File newFile = new File(saveFileName); if (newFile.isFile() && newFile.exists()) { boolean ok = MessageDialog.openConfirm( this.getSite().getShell(), "File already exists!", "File already exists! Overwrite?"); if (!ok) { return; } } // create the save job Job saveJob = new Save( "Save As", saveFileName, this.scanDescription, this); // run the save job with a progress dialog IProgressService service = (IProgressService) getSite().getService( IProgressService.class); service.showInDialog(getSite().getShell(), saveJob); saveJob.setUser(true); saveJob.schedule(); Activator.getDefault().saveDefaults(this.scanDescription); this.updatePositionCounts(); this.firePropertyChange(PROP_TITLE); this.scanDescription.setFileName(new File(saveFileName).getName()); } private void updatePositionCounts() { for (Chain chain : this.scanDescription.getChains()) { chain.calculatePositionCount(); } } /** * Called by the save as job to update the input. * * @param filename the new file name */ public void resetEditorState(String filename) { logger.debug("reset editor state"); final IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(filename)); final FileStoreEditorInput fileStoreEditorInput = new FileStoreEditorInput(fileStore); this.setInput(fileStoreEditorInput); this.firePropertyChange(PROP_INPUT); this.setPartName(fileStoreEditorInput.getName()); this.firePropertyChange(PROP_TITLE); this.dirty = false; this.firePropertyChange(PROP_DIRTY); } /* * helper for save and save as to determine whether saving is allowed. * returns true if saving is allowed, false otherwise */ private boolean isSaveAllowed() { // check for errors in the model // if present -> inform the user if(scanDescription.getModelErrors().size() > 0) { MessageDialog.openError( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Save Error", "Scandescription could not be saved! " + "Consult the Error View for more Information."); return false; } return true; } /** * {@inheritDoc} */ @Override public boolean isDirty() { return this.dirty; } /** * {@inheritDoc} */ @Override public boolean isSaveAsAllowed() { return true; } /** * {@inheritDoc} */ @Override public boolean isSaveOnCloseNeeded() { return true; } /** * {@inheritDoc} */ @Override public void commandStackChanged(EventObject event) { logger.debug("Command Stack changed"); firePropertyChange(IEditorPart.PROP_DIRTY); super.commandStackChanged(event); } /** * {@inheritDoc} */ public CommandStack getCommandStack() { return this.getEditDomain().getCommandStack(); } /** * {@inheritDoc} */ @Override public void dispose() { getSite().setSelectionProvider(null); this.scanDescription.removeModelUpdateListener(this); // TODO remove CommandStackListener super.dispose(); } /** * Returns the editor content. * * @return the editor content */ public ScanDescription getContent() { return this.scanDescription; } /** * {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public Object getAdapter(Class type) { if (type == ZoomManager.class) { return ((ScalableFreeformRootEditPart) getGraphicalViewer() .getRootEditPart()).getZoomManager(); } else if (type == IContentOutlinePage.class) { return new OutlinePage(); } else if (type == CommandStack.class) { return this.getEditDomain().getCommandStack(); } else if (type == EditDomain.class) { return this.getEditDomain(); } else if (type == GraphicalViewer.class) { return this.getGraphicalViewer(); } else if (type == EditPart.class) { return this.getGraphicalViewer().getRootEditPart(); } return super.getAdapter(type); } public GraphicalViewer getViewer() { return this.getGraphicalViewer(); } /** * {@inheritDoc} */ @Override public void updateEvent(ModelUpdateEvent modelUpdateEvent) { logger.debug("update event"); this.dirty = true; this.firePropertyChange(PROP_DIRTY); } /** * {@inheritDoc} */ @Override protected void configureGraphicalViewer() { logger.trace("configureGraphicalViewer"); final GraphicalViewer viewer = this.getGraphicalViewer(); viewer.setEditPartFactory(new ScanDescriptionEditorEditPartFactory()); // construct layered view for displaying FreeformFigures (zoomable) ScalableFreeformRootEditPart root = new ScalableFreeformRootEditPart(); viewer.setRootEditPart(root); viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer)); // zoom with MouseWheel viewer.setProperty(MouseWheelHandler.KeyGenerator.getKey(SWT.MOD1), MouseWheelZoomHandler.SINGLETON); List<String> zoomContributions = Arrays.asList(new String[] { ZoomManager.FIT_ALL, ZoomManager.FIT_HEIGHT, ZoomManager.FIT_WIDTH }); root.getZoomManager().setZoomLevelContributions(zoomContributions); IAction zoomIn = new ZoomInAction(root.getZoomManager()); IAction zoomOut = new ZoomOutAction(root.getZoomManager()); getActionRegistry().registerAction(zoomIn); getActionRegistry().registerAction(zoomOut); viewer.getControl().addMenuDetectListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent e) { contextMenuLocation = viewer.getControl().toControl(e.x, e.y); } }); super.configureGraphicalViewer(); } /** * {@inheritDoc} */ @Override protected void initializeGraphicalViewer() { logger.trace("initializeGraphicalViewer"); super.initializeGraphicalViewer(); this.getGraphicalViewer().setContents(this.scanDescription); this.getGraphicalViewer().addDropTargetListener( new TemplateTransferDropTargetListener(this .getGraphicalViewer())); MenuManager menuManager = new MenuManager(); menuManager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); this.getGraphicalViewer().setContextMenu(menuManager); getSite().registerContextMenu(menuManager, this.getGraphicalViewer()); this.getSite().setSelectionProvider(this.getGraphicalViewer()); } /** * {@inheritDoc} */ @Override protected PaletteRoot getPaletteRoot() { return ScanDescriptionEditorPaletteFactory.createPalette(); } /** * {@inheritDoc} */ @Override protected PaletteViewerProvider createPaletteViewerProvider() { return new PaletteViewerProvider(getEditDomain()) { @Override protected void configurePaletteViewer(PaletteViewer viewer) { super.configurePaletteViewer(viewer); viewer.addDragSourceListener(new TemplateTransferDragSourceListener( viewer)); } }; } /** * Returns the current cursor position. * * @return the current cursor position * @since 1.19 */ public Point getCursorPosition() { Display display = Display.getDefault(); Point point = getGraphicalViewer().getControl().toControl( display.getCursorLocation()); FigureCanvas figureCanvas = (FigureCanvas) getGraphicalViewer() .getControl(); org.eclipse.draw2d.geometry.Point location = figureCanvas.getViewport() .getViewLocation(); point = new Point(point.x + location.x, point.y + location.y); return point; } /** * Returns the context menu position if any or <code>null</code>. * * @return the context menu position or <code>null</code> * @since 1.19 */ public Point getContextMenuPosition() { Point menuPosition = this.contextMenuLocation; this.contextMenuLocation = null; return menuPosition; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void createActions() { super.createActions(); ActionRegistry registry = getActionRegistry(); IAction action; action = new Copy(this); registry.registerAction(action); getSelectionActions().add(action.getId()); action = new Paste(this); registry.registerAction(action); action = new Cut(this, (DeleteAction) registry.getAction( ActionFactory.DELETE.getId())); registry.registerAction(action); getSelectionActions().add(action.getId()); } protected class OutlinePage extends ContentOutlinePage { private SashForm sash; // private ScrollableThumbnail thumbnail; // private DisposeListener disposeListener; public OutlinePage() { super(new TreeViewer()); } public void createControl(Composite parent) { sash = new SashForm(parent, SWT.VERTICAL); getViewer().createControl(sash); getViewer().setEditDomain(getEditDomain()); getViewer().setEditPartFactory( new ScanDescriptionEditorTreeEditPartFactory()); if (scanDescription != null) { getViewer().setContents(scanDescription); } getSelectionSynchronizer().addViewer(getViewer()); // miniature view /* Canvas canvas = new Canvas(sash, SWT.BORDER); LightweightSystem lws = new LightweightSystem(canvas); thumbnail = new ScrollableThumbnail( (FreeformViewport)((ScalableFreeformRootEditPart)getGraphicalViewer() .getRootEditPart()).getFigure()); lws.setContents(thumbnail); disposeListener = new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { if (thumbnail != null) { thumbnail.deactivate(); thumbnail = null; } } }; getGraphicalViewer().getControl().addDisposeListener( disposeListener);*/ } /** * {@inheritDoc} */ @Override public void init(IPageSite pageSite) { super.init(pageSite); } /** * {@inheritDoc} */ @Override public Control getControl() { return sash; } /** * {@inheritDoc} */ @Override public void dispose() { getSelectionSynchronizer().removeViewer(getViewer()); /*if (getGraphicalViewer().getControl() != null && !getGraphicalViewer().getControl().isDisposed()) { getGraphicalViewer().getControl().removeDisposeListener( disposeListener); }*/ super.dispose(); } } }
package org.pentaho.reporting.platform.plugin; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Array; import java.net.URL; import java.util.Collections; import java.util.Date; import java.util.Map; import java.sql.Time; import java.sql.Timestamp; import javax.print.DocFlavor; import javax.print.PrintService; import javax.print.PrintServiceLookup; import javax.swing.table.TableModel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.commons.connection.IPentahoResultSet; import org.pentaho.platform.api.engine.IAcceptsRuntimeInputs; import org.pentaho.platform.api.engine.IActionSequenceResource; import org.pentaho.platform.api.engine.IPentahoSession; import org.pentaho.platform.api.engine.IStreamingPojo; import org.pentaho.platform.api.repository.IContentRepository; import org.pentaho.platform.engine.core.system.PentahoSystem; import org.pentaho.platform.plugin.action.jfreereport.helper.PentahoTableModel; import org.pentaho.reporting.engine.classic.core.AttributeNames; import org.pentaho.reporting.engine.classic.core.ClassicEngineBoot; import org.pentaho.reporting.engine.classic.core.MasterReport; import org.pentaho.reporting.engine.classic.core.metadata.ReportProcessTaskRegistry; import org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.PdfPageableModule; import org.pentaho.reporting.engine.classic.core.modules.output.pageable.plaintext.PlainTextPageableModule; import org.pentaho.reporting.engine.classic.core.modules.output.pageable.plaintext.driver.TextFilePrinterDriver; import org.pentaho.reporting.engine.classic.core.modules.output.table.csv.CSVTableModule; import org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlTableModule; import org.pentaho.reporting.engine.classic.core.modules.output.table.rtf.RTFTableModule; import org.pentaho.reporting.engine.classic.core.modules.output.table.xls.ExcelTableModule; import org.pentaho.reporting.engine.classic.core.modules.parser.base.ReportGenerator; import org.pentaho.reporting.engine.classic.core.parameters.DefaultParameterContext; import org.pentaho.reporting.engine.classic.core.parameters.ListParameter; import org.pentaho.reporting.engine.classic.core.parameters.ParameterContext; import org.pentaho.reporting.engine.classic.core.parameters.ParameterDefinitionEntry; import org.pentaho.reporting.engine.classic.core.util.beans.BeanException; import org.pentaho.reporting.engine.classic.core.util.beans.ConverterRegistry; import org.pentaho.reporting.engine.classic.core.util.beans.ValueConverter; import org.pentaho.reporting.engine.classic.extensions.modules.java14print.Java14PrintUtil; import org.pentaho.reporting.libraries.base.config.Configuration; import org.pentaho.reporting.libraries.base.util.StringUtils; import org.pentaho.reporting.libraries.resourceloader.ResourceException; import org.pentaho.reporting.platform.plugin.messages.Messages; import org.pentaho.reporting.platform.plugin.output.CSVOutput; import org.pentaho.reporting.platform.plugin.output.EmailOutput; import org.pentaho.reporting.platform.plugin.output.HTMLOutput; import org.pentaho.reporting.platform.plugin.output.PDFOutput; import org.pentaho.reporting.platform.plugin.output.PageableHTMLOutput; import org.pentaho.reporting.platform.plugin.output.PlainTextOutput; import org.pentaho.reporting.platform.plugin.output.RTFOutput; import org.pentaho.reporting.platform.plugin.output.XLSOutput; import org.xml.sax.InputSource; public class SimpleReportingComponent implements IStreamingPojo, IAcceptsRuntimeInputs { /** * The logging for logging messages from this component */ private static final Log log = LogFactory.getLog(SimpleReportingComponent.class); public static final String OUTPUT_TARGET = "output-target"; //$NON-NLS-1$ public static final String OUTPUT_TYPE = "output-type"; //$NON-NLS-1$ public static final String MIME_TYPE_HTML = "text/html"; //$NON-NLS-1$ public static final String MIME_TYPE_EMAIL = "mime-message/text/html"; //$NON-NLS-1$ public static final String MIME_TYPE_PDF = "application/pdf"; //$NON-NLS-1$ public static final String MIME_TYPE_XLS = "application/vnd.ms-excel"; //$NON-NLS-1$ public static final String MIME_TYPE_RTF = "application/rtf"; //$NON-NLS-1$ public static final String MIME_TYPE_CSV = "text/csv"; //$NON-NLS-1$ public static final String MIME_TYPE_TXT = "text/plain"; //$NON-NLS-1$ public static final String XLS_WORKBOOK_PARAM = "workbook"; //$NON-NLS-1$ public static final String REPORTLOAD_RESURL = "res-url"; //$NON-NLS-1$ public static final String REPORT_DEFINITION_INPUT = "report-definition"; //$NON-NLS-1$ public static final String USE_CONTENT_REPOSITORY = "useContentRepository"; //$NON-NLS-1$ public static final String REPORTHTML_CONTENTHANDLER_PATTERN = "content-handler-pattern"; //$NON-NLS-1$ public static final String REPORTGENERATE_YIELDRATE = "yield-rate"; //$NON-NLS-1$ public static final String ACCEPTED_PAGE = "accepted-page"; //$NON-NLS-1$ public static final String PAGINATE_OUTPUT = "paginate"; //$NON-NLS-1$ public static final String PRINT = "print"; //$NON-NLS-1$ public static final String PRINTER_NAME = "printer-name"; //$NON-NLS-1$ public static final String DASHBOARD_MODE = "dashboard-mode"; //$NON-NLS-1$ private static final String MIME_GENERIC_FALLBACK = "application/octet-stream"; //$NON-NLS-1$ /** * Static initializer block to guarantee that the ReportingComponent will be in a state where the reporting engine will be booted. We have a system listener * which will boot the reporting engine as well, but we do not want to solely rely on users having this setup correctly. The errors you receive if the engine * is not booted are not very helpful, especially to outsiders, so we are trying to provide multiple paths to success. Enjoy. */ static { final ReportingSystemStartupListener startup = new ReportingSystemStartupListener(); startup.startup(null); } /** * The output-type for the generated report, such as PDF, XLS, CSV, HTML, etc This must be the mime-type! */ private String outputType; private String outputTarget; private MasterReport report; private Map<String, Object> inputs; private OutputStream outputStream; private InputStream reportDefinitionInputStream; private Boolean useContentRepository = Boolean.FALSE; private IActionSequenceResource reportDefinition; private String reportDefinitionPath; private IPentahoSession session; private boolean paginateOutput = false; private int acceptedPage = -1; private int pageCount = -1; private boolean dashboardMode; /* * These fields are for enabling printing */ private boolean print = false; private String printer; /* * Default constructor */ public SimpleReportingComponent() { this.inputs = Collections.emptyMap(); } // BEGIN BEAN METHODS public String getOutputTarget() { return outputTarget; } public void setOutputTarget(final String outputTarget) { this.outputTarget = outputTarget; } /** * Sets the mime-type for determining which report output type to generate. This should be a mime-type for consistency with streaming output mime-types. * * @param outputType the desired output type (mime-type) for the report engine to generate */ public void setOutputType(final String outputType) { this.outputType = outputType; } /** * Gets the output type, this should be a mime-type for consistency with streaming output mime-types. * * @return the current output type for the report */ public String getOutputType() { return outputType; } /** * This method returns the resource for the report-definition, if available. * * @return the report-definition resource */ public IActionSequenceResource getReportDefinition() { return reportDefinition; } /** * Sets the report-definition if it is provided to us by way of an action-sequence resource. The name must be reportDefinition or report-definition. * * @param reportDefinition a report-definition as seen (wrapped) by an action-sequence */ public void setReportDefinition(final IActionSequenceResource reportDefinition) { this.reportDefinition = reportDefinition; } /** * This method will be called if an input is called reportDefinitionInputStream, or any variant of that with dashes report-definition-inputstream for example. * The primary purpose of this method is to facilitate unit testing. * * @param reportDefinitionInputStream any kind of InputStream which contains a valid report-definition */ public void setReportDefinitionInputStream(final InputStream reportDefinitionInputStream) { this.reportDefinitionInputStream = reportDefinitionInputStream; } /** * Returns the path to the report definition (for platform use this is a path in the solution repository) * * @return reportdefinitionPath */ public String getReportDefinitionPath() { return reportDefinitionPath; } /** * Sets the path to the report definition (platform path) * * @param reportDefinitionPath the path to the report definition. */ public void setReportDefinitionPath(final String reportDefinitionPath) { this.reportDefinitionPath = reportDefinitionPath; } /** * Returns true if the report engine will be asked to use a paginated (HTML) output processor * * @return paginated */ public boolean isPaginateOutput() { return paginateOutput; } /** * Set the paging mode used by the reporting engine. This will also be set if an input * * @param paginateOutput page mode */ public void setPaginateOutput(final boolean paginateOutput) { this.paginateOutput = paginateOutput; } public int getAcceptedPage() { return acceptedPage; } public void setAcceptedPage(final int acceptedPage) { this.acceptedPage = acceptedPage; } /** * This method sets the IPentahoSession to use in order to access the pentaho platform file repository and content repository. * * @param session a valid pentaho session */ public void setSession(final IPentahoSession session) { this.session = session; } public boolean isDashboardMode() { return dashboardMode; } public void setDashboardMode(final boolean dashboardMode) { this.dashboardMode = dashboardMode; } /** * This method returns the mime-type for the streaming output based on the effective output target. * * @return the mime-type for the streaming output * @see SimpleReportingComponent#computeEffectiveOutputTarget() */ public String getMimeType() { try { final String outputTarget = computeEffectiveOutputTarget(); if (log.isDebugEnabled()) { log.debug(Messages.getInstance().getString("ReportPlugin.logComputedOutputTarget", outputTarget)); } if (HtmlTableModule.TABLE_HTML_STREAM_EXPORT_TYPE.equals(outputTarget)) { return SimpleReportingComponent.MIME_TYPE_HTML; } if (HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE.equals(outputTarget)) { return SimpleReportingComponent.MIME_TYPE_HTML; } if (ExcelTableModule.EXCEL_FLOW_EXPORT_TYPE.equals(outputTarget)) { return SimpleReportingComponent.MIME_TYPE_XLS; } if (CSVTableModule.TABLE_CSV_STREAM_EXPORT_TYPE.equals(outputTarget)) { return SimpleReportingComponent.MIME_TYPE_CSV; } if (RTFTableModule.TABLE_RTF_FLOW_EXPORT_TYPE.equals(outputTarget)) { return SimpleReportingComponent.MIME_TYPE_RTF; } if (PdfPageableModule.PDF_EXPORT_TYPE.equals(outputTarget)) { return SimpleReportingComponent.MIME_TYPE_PDF; } if (PlainTextPageableModule.PLAINTEXT_EXPORT_TYPE.equals(outputTarget)) { return SimpleReportingComponent.MIME_TYPE_TXT; } if (SimpleReportingComponent.MIME_TYPE_EMAIL.equals(outputTarget)) { return SimpleReportingComponent.MIME_TYPE_EMAIL; } } catch (IOException e) { if (log.isDebugEnabled()) { log.warn(Messages.getInstance().getString("ReportPlugin.logErrorMimeTypeFull"), e); } else if (log.isWarnEnabled()) { log.warn(Messages.getInstance().getString("ReportPlugin.logErrorMimeTypeShort", e.getMessage())); } } catch (ResourceException e) { if (log.isDebugEnabled()) { log.warn(Messages.getInstance().getString("ReportPlugin.logErrorMimeTypeFull"), e); } else if (log.isWarnEnabled()) { log.warn(Messages.getInstance().getString("ReportPlugin.logErrorMimeTypeShort", e.getMessage())); } } return MIME_GENERIC_FALLBACK; } /** * This method sets the OutputStream to write streaming content on. * * @param outputStream an OutputStream to write to */ public void setOutputStream(final OutputStream outputStream) { this.outputStream = outputStream; } public void setUseContentRepository(final Boolean useContentRepository) { this.useContentRepository = useContentRepository; } /** * This method checks if the output is targeting a printer * * @return true if the output is supposed to go to a printer */ public boolean isPrint() { return print; } /** * Set whether or not to send the report to a printer * * @param print a flag indicating whether the report should be printed. */ public void setPrint(final boolean print) { this.print = print; } /** * This method gets the name of the printer the report will be sent to * * @return the name of the printer that the report will be sent to */ public String getPrinter() { return printer; } /** * Set the name of the printer to send the report to * * @param printer the name of the printer that the report will be sent to, a null value will be interpreted as the default printer */ public void setPrinter(final String printer) { this.printer = printer; } /** * This method sets the map of *all* the inputs which are available to this component. This allows us to use action-sequence inputs as parameters for our * reports. * * @param inputs a Map containing inputs */ public void setInputs(final Map<String, Object> inputs) { if (inputs == null) { this.inputs = Collections.emptyMap(); return; } this.inputs = inputs; if (inputs.containsKey(OUTPUT_TYPE)) { setOutputType(String.valueOf(inputs.get(OUTPUT_TYPE))); } if (inputs.containsKey(OUTPUT_TARGET)) { setOutputTarget(String.valueOf(inputs.get(OUTPUT_TARGET))); } if (inputs.containsKey(REPORT_DEFINITION_INPUT)) { setReportDefinitionInputStream((InputStream) inputs.get(REPORT_DEFINITION_INPUT)); } if (inputs.containsKey(USE_CONTENT_REPOSITORY)) { setUseContentRepository((Boolean) inputs.get(USE_CONTENT_REPOSITORY)); } if (inputs.containsKey(PAGINATE_OUTPUT)) { paginateOutput = "true".equals(String.valueOf(inputs.get(PAGINATE_OUTPUT))); //$NON-NLS-1$ if (paginateOutput && inputs.containsKey(ACCEPTED_PAGE)) { acceptedPage = Integer.parseInt(String.valueOf(inputs.get(ACCEPTED_PAGE))); //$NON-NLS-1$ } } if (inputs.containsKey(PRINT)) { print = "true".equals(String.valueOf(inputs.get(PRINT))); //$NON-NLS-1$ } if (inputs.containsKey(PRINTER_NAME)) { printer = String.valueOf(inputs.get(PRINTER_NAME)); } if (inputs.containsKey(DASHBOARD_MODE)) { dashboardMode = "true".equals(String.valueOf(inputs.get(DASHBOARD_MODE))); //$NON-NLS-1$ } } // END BEAN METHODS protected Object getInput(final String key, final Object defaultValue) { if (inputs != null) { final Object input = inputs.get(key); if (input != null) { return input; } } return defaultValue; } /** * Get the MasterReport for the report-definition, the MasterReport object will be cached as needed, using the PentahoResourceLoader. * * @return a parsed MasterReport object * @throws ResourceException * @throws IOException */ public MasterReport getReport() throws ResourceException, IOException { if (report == null) { if (reportDefinitionInputStream != null) { final ReportGenerator generator = ReportGenerator.createInstance(); final InputSource repDefInputSource = new InputSource(reportDefinitionInputStream); report = generator.parseReport(repDefInputSource, getDefinedResourceURL(null)); } else if (reportDefinition != null) { // load the report definition as an action-sequence resource report = ReportCreator.createReport(reportDefinition.getAddress(), session); } else { report = ReportCreator.createReport(reportDefinitionPath, session); } report.setReportEnvironment(new PentahoReportEnvironment(report.getConfiguration())); } return report; } private boolean isValidOutputType(final String outputType) { return ReportProcessTaskRegistry.getInstance().isExportTypeRegistered(outputType); } /** * Computes the effective output target that will be used when running the report. This method does not * modify any of the properties of this class. * <p/> * The algorithm to determine the output target is as follows: * <ul> * <li> * If the report attribute "lock-preferred-output-type" is set, and the attribute preferred-output-type is set, * the report will always be exported to the specified output type.</li> * <li>If the component has the parameter "output-target" set, this output target will be used.</li> * <li>If the component has the parameter "output-type" set, the mime-type will be translated into a suitable * output target (depends on other parameters like paginate as well.</li> * <li>If neither output-target or output-type are specified, the report's preferred output type will be used.</li> * <li>If no preferred output type is set, we default to HTML export.</li> * </ul> * <p/> * If the output type given is invalid, the report will not be executed and calls to * <code>SimpleReportingComponent#getMimeType()</code> will yield the generic "application/octet-stream" response. * * @return * @throws IOException * @throws ResourceException */ private String computeEffectiveOutputTarget() throws IOException, ResourceException { final MasterReport report = getReport(); if (Boolean.TRUE.equals(report.getAttribute(AttributeNames.Core.NAMESPACE, AttributeNames.Core.LOCK_PREFERRED_OUTPUT_TYPE))) { // preferred output type is one of the engine's output-target identifiers. It is not a mime-type string. // The engine supports multiple subformats per mime-type (example HTML: zipped/streaming/flow/pageable) // The mime-mapping would be inaccurate. final Object preferredOutputType = report.getAttribute (AttributeNames.Core.NAMESPACE, AttributeNames.Core.PREFERRED_OUTPUT_TYPE); if (preferredOutputType != null) { final String preferredOutputTypeString = String.valueOf(preferredOutputType); if (isValidOutputType(preferredOutputTypeString)) { // if it is a recognized process-type, then fine, return it. return preferredOutputTypeString; } final String mappedLegacyType = mapOutputTypeToOutputTarget(preferredOutputTypeString); if (mappedLegacyType != null) { log.warn(Messages.getInstance().getString("ReportPlugin.warnLegacyLockedOutput", preferredOutputTypeString)); return mappedLegacyType; } log.warn(Messages.getInstance().getString("ReportPlugin.warnInvalidLockedOutput", preferredOutputTypeString)); } } final String outputTarget = getOutputTarget(); if (outputTarget != null) { if (isValidOutputType(outputTarget) == false) { log.warn(Messages.getInstance().getString("ReportPlugin.warnInvalidOutputTarget", outputTarget)); } // if a engine-level output target is given, use it as it is. We can assume that the user knows how to // map from that to a real mime-type. return outputTarget; } final String mappingFromParams = mapOutputTypeToOutputTarget(getOutputType()); if (mappingFromParams != null) { return mappingFromParams; } // if nothing is specified explicity, we may as well ask the report what it prefers.. final Object preferredOutputType = report.getAttribute(AttributeNames.Core.NAMESPACE, AttributeNames.Core.PREFERRED_OUTPUT_TYPE); if (preferredOutputType != null) { final String preferredOutputTypeString = String.valueOf(preferredOutputType); if (isValidOutputType(preferredOutputTypeString)) { return preferredOutputTypeString; } final String mappedLegacyType = mapOutputTypeToOutputTarget(preferredOutputTypeString); if (mappedLegacyType != null) { log.warn(Messages.getInstance().getString("ReportPlugin.warnLegacyPreferredOutput", preferredOutputTypeString)); return mappedLegacyType; } log.warn(Messages.getInstance().getString("ReportPlugin.warnInvalidPreferredOutput", preferredOutputTypeString, HtmlTableModule.TABLE_HTML_STREAM_EXPORT_TYPE)); return HtmlTableModule.TABLE_HTML_STREAM_EXPORT_TYPE; } // if you have come that far, it means you really messed up. Sorry, this error is not a error caused // by our legacy code - it is more likely that you just entered values that are totally wrong. log.error(Messages.getInstance().getString("ReportPlugin.warnInvalidOutputType", getOutputType(), HtmlTableModule.TABLE_HTML_STREAM_EXPORT_TYPE)); return HtmlTableModule.TABLE_HTML_STREAM_EXPORT_TYPE; } private String mapOutputTypeToOutputTarget(final String outputType) { // if the user has given a mime-type instead of a output-target, lets map it to the "best" choice. If the // user wanted full control, he would have used the output-target property instead. if (MIME_TYPE_CSV.equals(outputType)) { return CSVTableModule.TABLE_CSV_STREAM_EXPORT_TYPE; } if (MIME_TYPE_HTML.equals(outputType)) { if (isPaginateOutput()) { return HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE; } return HtmlTableModule.TABLE_HTML_STREAM_EXPORT_TYPE; } if (MIME_TYPE_PDF.equals(outputType)) { return PdfPageableModule.PDF_EXPORT_TYPE; } if (MIME_TYPE_RTF.equals(outputType)) { return RTFTableModule.TABLE_RTF_FLOW_EXPORT_TYPE; } if (MIME_TYPE_XLS.equals(outputType)) { return ExcelTableModule.EXCEL_FLOW_EXPORT_TYPE; } if (MIME_TYPE_EMAIL.equals(outputType)) { return MIME_TYPE_EMAIL; } if (MIME_TYPE_TXT.equals(outputType)) { return PlainTextPageableModule.PLAINTEXT_EXPORT_TYPE; } if ("pdf".equalsIgnoreCase(outputType)) //$NON-NLS-1$ { log.warn(Messages.getInstance().getString("ReportPlugin.warnDeprecatedPDF")); return PdfPageableModule.PDF_EXPORT_TYPE; } else if ("html".equalsIgnoreCase(outputType)) //$NON-NLS-1$ { log.warn(Messages.getInstance().getString("ReportPlugin.warnDeprecatedHTML")); if (isPaginateOutput()) { return HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE; } return HtmlTableModule.TABLE_HTML_STREAM_EXPORT_TYPE; } else if ("csv".equalsIgnoreCase(outputType)) //$NON-NLS-1$ { log.warn(Messages.getInstance().getString("ReportPlugin.warnDeprecatedCSV")); return CSVTableModule.TABLE_CSV_STREAM_EXPORT_TYPE; } else if ("rtf".equalsIgnoreCase(outputType)) //$NON-NLS-1$ { log.warn(Messages.getInstance().getString("ReportPlugin.warnDeprecatedRTF")); return RTFTableModule.TABLE_RTF_FLOW_EXPORT_TYPE; } else if ("xls".equalsIgnoreCase(outputType)) //$NON-NLS-1$ { log.warn(Messages.getInstance().getString("ReportPlugin.warnDeprecatedXLS")); return ExcelTableModule.EXCEL_FLOW_EXPORT_TYPE; } else if ("txt".equalsIgnoreCase(outputType)) //$NON-NLS-1$ { log.warn(Messages.getInstance().getString("ReportPlugin.warnDeprecatedTXT")); return PlainTextPageableModule.PLAINTEXT_EXPORT_TYPE; } return null; } /** * Apply inputs (if any) to corresponding report parameters, care is taken when checking parameter types to perform any necessary casting and conversion. * * @param report a MasterReport object to apply parameters to * @param context a ParameterContext for which the parameters will be under * @deprecated use the single parameter version instead. This method will now fail with an error if the * report passed in is not the same as the report this component has. */ public void applyInputsToReportParameters(final MasterReport report, final ParameterContext context) { try { if (getReport() != report) { throw new IllegalStateException(Messages.getInstance().getString("ReportPlugin.errorForeignReportInput")); } applyInputsToReportParameters(context); } catch (IOException e) { throw new IllegalStateException(Messages.getInstance().getString("ReportPlugin.errorApplyInputsFailed"), e); } catch (ResourceException e) { throw new IllegalStateException(Messages.getInstance().getString("ReportPlugin.errorApplyInputsFailed"), e); } } /** * Apply inputs (if any) to corresponding report parameters, care is taken when checking parameter types to perform any necessary casting and conversion. * * @param context a ParameterContext for which the parameters will be under * @throws java.io.IOException if the report of this component could not be parsed. * @throws ResourceException if the report of this component could not be parsed. */ public void applyInputsToReportParameters(final ParameterContext context) throws IOException, ResourceException { // apply inputs to report if (inputs != null) { final MasterReport report = getReport(); final ParameterDefinitionEntry[] params = report.getParameterDefinition().getParameterDefinitions(); for (final ParameterDefinitionEntry param : params) { final String paramName = param.getName(); Object value = inputs.get(paramName); final Object defaultValue = param.getDefaultValue(context); if (value == null && defaultValue != null) { value = defaultValue; } if (value != null) { addParameter(report, param, paramName, value); } } } } private Object convert(final Class targetType, final Object rawValue) throws NumberFormatException { if (targetType == null) { throw new NullPointerException(); } if (rawValue == null) { return null; } if (targetType.isInstance(rawValue)) { return rawValue; } if (targetType.isAssignableFrom(TableModel.class) && IPentahoResultSet.class.isAssignableFrom(rawValue.getClass())) { // wrap IPentahoResultSet to simulate TableModel return new PentahoTableModel((IPentahoResultSet) rawValue); } final String valueAsString = String.valueOf(rawValue); if (StringUtils.isEmpty(valueAsString)) { return null; } if (targetType.equals(Timestamp.class)) { try { return new Timestamp(new Long(valueAsString)); } catch (NumberFormatException nfe) { // ignore, we try to parse it as real date now .. } } else if (targetType.equals(Time.class)) { try { return new Time(new Long(valueAsString)); } catch (NumberFormatException nfe) { // ignore, we try to parse it as real date now .. } } else if (targetType.equals(java.sql.Date.class)) { try { return new java.sql.Date(new Long(valueAsString)); } catch (NumberFormatException nfe) { // ignore, we try to parse it as real date now .. } } else if (targetType.equals(Date.class)) { try { return new Date(new Long(valueAsString)); } catch (NumberFormatException nfe) { // ignore, we try to parse it as real date now .. } } final ValueConverter valueConverter = ConverterRegistry.getInstance().getValueConverter(targetType); if (valueConverter != null) { try { return valueConverter.toPropertyValue(valueAsString); } catch (BeanException e) { throw new RuntimeException(Messages.getInstance().getString("ReportPlugin.unableToConvertParameter")); //$NON-NLS-1$ } } return rawValue; } private void addParameter(final MasterReport report, final ParameterDefinitionEntry param, final String key, final Object value) { if (value.getClass().isArray()) { final Class componentType; if (param.getValueType().isArray()) { componentType = param.getValueType().getComponentType(); } else { componentType = param.getValueType(); } final int length = Array.getLength(value); final Object array = Array.newInstance(componentType, length); for (int i = 0; i < length; i++) { Array.set(array, i, convert(componentType, Array.get(value, i))); } report.getParameterValues().put(key, array); } else if (isAllowMultiSelect(param)) { // if the parameter allows multi selections, wrap this single input in an array // and re-call addParameter with it final Object[] array = new Object[1]; array[0] = value; addParameter(report, param, key, array); } else { report.getParameterValues().put(key, convert(param.getValueType(), value)); } } private boolean isAllowMultiSelect(final ParameterDefinitionEntry parameter) { if (parameter instanceof ListParameter) { final ListParameter listParameter = (ListParameter) parameter; return listParameter.isAllowMultiSelection(); } return false; } private URL getDefinedResourceURL(final URL defaultValue) { if (inputs == null || inputs.containsKey(REPORTLOAD_RESURL) == false) { return defaultValue; } try { final String inputStringValue = (String) getInput(REPORTLOAD_RESURL, null); return new URL(inputStringValue); } catch (Exception e) { return defaultValue; } } protected int getYieldRate() { final Object yieldRate = getInput(REPORTGENERATE_YIELDRATE, null); if (yieldRate instanceof Number) { final Number n = (Number) yieldRate; if (n.intValue() < 1) { return 0; } return n.intValue(); } return 0; } /** * This method returns the number of logical pages which make up the report. This results of this method are available only after validate/execute have been * successfully called. This field has no setter, as it should never be set by users. * * @return the number of logical pages in the report */ public int getPageCount() { return pageCount; } /** * This method will determine if the component instance 'is valid.' The validate() is called after all of the bean 'setters' have been called, so we may * validate on the actual values, not just the presence of inputs as we were historically accustomed to. * <p/> * Since we should have a list of all action-sequence inputs, we can determine if we have sufficient inputs to meet the parameter requirements of the * report-definition. This would include validation of values and ranges of values. * * @return true if valid * @throws Exception */ public boolean validate() throws Exception { if (reportDefinition == null && reportDefinitionInputStream == null && reportDefinitionPath == null) { log.error(Messages.getInstance().getString("ReportPlugin.reportDefinitionNotProvided")); //$NON-NLS-1$ return false; } if (reportDefinition != null && reportDefinitionPath != null && session == null) { log.error(Messages.getInstance().getString("ReportPlugin.noUserSession")); //$NON-NLS-1$ return false; } if (outputStream == null && print == false) { log.error(Messages.getInstance().getString("ReportPlugin.outputStreamRequired")); //$NON-NLS-1$ return false; } return true; } /** * Perform the primary function of this component, this is, to execute. This method will be invoked immediately following a successful validate(). * * @return true if successful execution * @throws Exception */ public boolean execute() throws Exception { final MasterReport report = getReport(); try { final ParameterContext parameterContext = new DefaultParameterContext(report); // open parameter context parameterContext.open(); applyInputsToReportParameters(parameterContext); parameterContext.close(); if (isPrint()) { // handle printing // basic logic here is: get the default printer, attempt to resolve the user specified printer, default back as needed PrintService printService = PrintServiceLookup.lookupDefaultPrintService(); if (StringUtils.isEmpty(getPrinter()) == false) { final PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null); for (final PrintService service : services) { if (service.getName().equals(printer)) { printService = service; } } if ((printer == null) && (services.length > 0)) { printService = services[0]; } } Java14PrintUtil.printDirectly(report, printService); return true; } final String outputType = computeEffectiveOutputTarget(); final Configuration globalConfig = ClassicEngineBoot.getInstance().getGlobalConfig(); if (HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE.equals(outputType)) { if (dashboardMode) { report.getReportConfiguration().setConfigProperty(HtmlTableModule.BODY_FRAGMENT, "true"); } String contentHandlerPattern = (String) getInput(REPORTHTML_CONTENTHANDLER_PATTERN, globalConfig.getConfigProperty("org.pentaho.web.ContentHandler")); //$NON-NLS-1$ if (useContentRepository) { // use the content repository contentHandlerPattern = (String) getInput(REPORTHTML_CONTENTHANDLER_PATTERN, globalConfig.getConfigProperty("org.pentaho.web.resource.ContentHandler")); //$NON-NLS-1$ final IContentRepository contentRepository = PentahoSystem.get(IContentRepository.class, session); pageCount = PageableHTMLOutput.generate(session, report, acceptedPage, outputStream, contentRepository, contentHandlerPattern, getYieldRate()); return true; } else { // don't use the content repository pageCount = PageableHTMLOutput.generate(report, acceptedPage, outputStream, contentHandlerPattern, getYieldRate()); return true; } } if (HtmlTableModule.TABLE_HTML_STREAM_EXPORT_TYPE.equals(outputType)) { if (dashboardMode) { report.getReportConfiguration().setConfigProperty(HtmlTableModule.BODY_FRAGMENT, "true"); } String contentHandlerPattern = (String) getInput(REPORTHTML_CONTENTHANDLER_PATTERN, globalConfig .getConfigProperty("org.pentaho.web.ContentHandler")); //$NON-NLS-1$ if (useContentRepository) { // use the content repository contentHandlerPattern = (String) getInput(REPORTHTML_CONTENTHANDLER_PATTERN, globalConfig.getConfigProperty( "org.pentaho.web.resource.ContentHandler")); //$NON-NLS-1$ final IContentRepository contentRepository = PentahoSystem.get(IContentRepository.class, session); return HTMLOutput.generate(session, report, outputStream, contentRepository, contentHandlerPattern, getYieldRate()); } else { // don't use the content repository return HTMLOutput.generate(report, outputStream, contentHandlerPattern, getYieldRate()); } } if (PdfPageableModule.PDF_EXPORT_TYPE.equals(outputType)) { return PDFOutput.generate(report, outputStream, getYieldRate()); } if (ExcelTableModule.EXCEL_FLOW_EXPORT_TYPE.equals(outputType)) { final InputStream templateInputStream = (InputStream) getInput(XLS_WORKBOOK_PARAM, null); return XLSOutput.generate(report, outputStream, templateInputStream, getYieldRate()); } if (CSVTableModule.TABLE_CSV_STREAM_EXPORT_TYPE.equals(outputType)) { return CSVOutput.generate(report, outputStream, getYieldRate()); } if (RTFTableModule.TABLE_RTF_FLOW_EXPORT_TYPE.equals(outputType)) { return RTFOutput.generate(report, outputStream, getYieldRate()); } if (MIME_TYPE_EMAIL.equals(outputType)) { return EmailOutput.generate(report, outputStream, "cid:{0}", getYieldRate()); //$NON-NLS-1$ } if (PlainTextPageableModule.PLAINTEXT_EXPORT_TYPE.equals(outputType)) { final TextFilePrinterDriver driver = new TextFilePrinterDriver(outputStream, 12, 6); return PlainTextOutput.generate(report, outputStream, getYieldRate(), driver); } log.warn(Messages.getInstance().getString("ReportPlugin.warnUnprocessableRequest", outputType)); } catch (Throwable t) { log.error(Messages.getInstance().getString("ReportPlugin.executionFailed"), t); //$NON-NLS-1$ } // lets not pretend we were successfull, if the export type was not a valid one. return false; } }
package org.pentaho.reporting.platform.plugin; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Array; import java.net.URL; import java.util.Date; import java.util.Map; import javax.swing.table.TableModel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.commons.connection.IPentahoResultSet; import org.pentaho.platform.api.engine.IAcceptsRuntimeInputs; import org.pentaho.platform.api.engine.IActionSequenceResource; import org.pentaho.platform.api.engine.IPentahoSession; import org.pentaho.platform.api.engine.IStreamingPojo; import org.pentaho.platform.api.repository.IContentRepository; import org.pentaho.platform.engine.core.system.PentahoSystem; import org.pentaho.platform.plugin.action.jfreereport.helper.PentahoTableModel; import org.pentaho.reporting.engine.classic.core.AttributeNames; import org.pentaho.reporting.engine.classic.core.ClassicEngineBoot; import org.pentaho.reporting.engine.classic.core.MasterReport; import org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.PdfPageableModule; import org.pentaho.reporting.engine.classic.core.modules.output.table.csv.CSVTableModule; import org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlTableModule; import org.pentaho.reporting.engine.classic.core.modules.output.table.rtf.RTFTableModule; import org.pentaho.reporting.engine.classic.core.modules.output.table.xls.ExcelTableModule; import org.pentaho.reporting.engine.classic.core.modules.parser.base.ReportGenerator; import org.pentaho.reporting.engine.classic.core.parameters.DefaultParameterContext; import org.pentaho.reporting.engine.classic.core.parameters.ListParameter; import org.pentaho.reporting.engine.classic.core.parameters.ParameterContext; import org.pentaho.reporting.engine.classic.core.parameters.ParameterDefinitionEntry; import org.pentaho.reporting.engine.classic.core.util.beans.BeanException; import org.pentaho.reporting.engine.classic.core.util.beans.ConverterRegistry; import org.pentaho.reporting.engine.classic.core.util.beans.ValueConverter; import org.pentaho.reporting.libraries.base.util.StringUtils; import org.pentaho.reporting.libraries.resourceloader.ResourceException; import org.pentaho.reporting.platform.plugin.output.CSVOutput; import org.pentaho.reporting.platform.plugin.output.HTMLOutput; import org.pentaho.reporting.platform.plugin.output.PDFOutput; import org.pentaho.reporting.platform.plugin.output.PageableHTMLOutput; import org.pentaho.reporting.platform.plugin.output.RTFOutput; import org.pentaho.reporting.platform.plugin.output.XLSOutput; import org.xml.sax.InputSource; public class SimpleReportingComponent implements IStreamingPojo, IAcceptsRuntimeInputs { /** * The logging for logging messages from this component */ private static final Log log = LogFactory.getLog(SimpleReportingComponent.class); public static final String OUTPUT_TYPE = "output-type"; public static final String MIME_TYPE_HTML = "text/html"; public static final String MIME_TYPE_PDF = "application/pdf"; public static final String MIME_TYPE_XLS = "application/vnd.ms-excel"; public static final String MIME_TYPE_RTF = "application/rtf"; public static final String MIME_TYPE_CSV = "text/csv"; public static final String XLS_WORKBOOK_PARAM = "workbook"; public static final String REPORTLOAD_RESURL = "res-url"; public static final String REPORT_DEFINITION_INPUT = "report-definition"; public static final String USE_CONTENT_REPOSITORY = "useContentRepository"; public static final String REPORTHTML_CONTENTHANDLER_PATTERN = "content-handler-pattern"; //$NON-NLS-1$ public static final String REPORTGENERATE_YIELDRATE = "yield-rate"; //$NON-NLS-1$ public static final String ACCEPTED_PAGE = "accepted-page"; public static final String PAGINATE_OUTPUT = "paginate"; /** * Static initializer block to guarantee that the ReportingComponent will be in a state where the reporting engine will be booted. We have a system listener * which will boot the reporting engine as well, but we do not want to solely rely on users having this setup correctly. The errors you receive if the engine * is not booted are not very helpful, especially to outsiders, so we are trying to provide multiple paths to success. Enjoy. */ static { final ReportingSystemStartupListener startup = new ReportingSystemStartupListener(); startup.startup(null); } /** * The output-type for the generated report, such as PDF, XLS, CSV, HTML, etc This must be the mime-type! */ private String outputType; private String outputTarget; private MasterReport report; private Map<String, Object> inputs; private OutputStream outputStream; private InputStream reportDefinitionInputStream; private Boolean useContentRepository = Boolean.FALSE; private IActionSequenceResource reportDefinition; private String reportDefinitionPath; private IPentahoSession session; private boolean paginateOutput = false; private int acceptedPage = -1; private int pageCount = -1; /* * Default constructor */ public SimpleReportingComponent() { } // BEGIN BEAN METHODS public String getOutputTarget() { return outputTarget; } public void setOutputTarget(final String outputTarget) { this.outputTarget = outputTarget; } /** * Sets the mime-type for determining which report output type to generate. This should be a mime-type for consistency with streaming output mime-types. * * @param outputType the desired output type (mime-type) for the report engine to generate */ public void setOutputType(String outputType) { this.outputType = outputType; } /** * Gets the output type, this should be a mime-type for consistency with streaming output mime-types. * * @return the current output type for the report */ public String getOutputType() { return outputType; } /** * This method returns the resource for the report-definition, if available. * * @return the report-definition resource */ public IActionSequenceResource getReportDefinition() { return reportDefinition; } /** * Sets the report-definition if it is provided to us by way of an action-sequence resource. The name must be reportDefinition or report-definition. * * @param reportDefinition a report-definition as seen (wrapped) by an action-sequence */ public void setReportDefinition(IActionSequenceResource reportDefinition) { this.reportDefinition = reportDefinition; } /** * This method will be called if an input is called reportDefinitionInputStream, or any variant of that with dashes report-definition-inputstream for example. * The primary purpose of this method is to facilitate unit testing. * * @param reportDefinitionInputStream any kind of InputStream which contains a valid report-definition */ public void setReportDefinitionInputStream(InputStream reportDefinitionInputStream) { this.reportDefinitionInputStream = reportDefinitionInputStream; } /** * Returns the path to the report definition (for platform use this is a path in the solution repository) * * @return reportdefinitionPath */ public String getReportDefinitionPath() { return reportDefinitionPath; } /** * Sets the path to the report definition (platform path) * * @param reportDefinitionPath */ public void setReportDefinitionPath(String reportDefinitionPath) { this.reportDefinitionPath = reportDefinitionPath; } /** * Returns true if the report engine will be asked to use a paginated (HTML) output processor * * @return paginated */ public boolean isPaginateOutput() { return paginateOutput; } /** * Set the paging mode used by the reporting engine. This will also be set if an input * * @param paginateOutput page mode */ public void setPaginateOutput(boolean paginateOutput) { this.paginateOutput = paginateOutput; } public int getAcceptedPage() { return acceptedPage; } public void setAcceptedPage(int acceptedPage) { this.acceptedPage = acceptedPage; } /** * This method sets the IPentahoSession to use in order to access the pentaho platform file repository and content repository. * * @param session a valid pentaho session */ public void setSession(IPentahoSession session) { this.session = session; } /** * This method returns the output-type for the streaming output, it is the same as what is returned by getOutputType() for consistency. * * @return the mime-type for the streaming output */ public String getMimeType() { return outputType; } /** * This method sets the OutputStream to write streaming content on. * * @param outputStream an OutputStream to write to */ public void setOutputStream(OutputStream outputStream) { this.outputStream = outputStream; } public void setUseContentRepository(Boolean useContentRepository) { this.useContentRepository = useContentRepository; } /** * This method sets the map of *all* the inputs which are available to this component. This allows us to use action-sequence inputs as parameters for our * reports. * * @param inputs a Map containing inputs */ public void setInputs(Map<String, Object> inputs) { this.inputs = inputs; if (inputs.containsKey(REPORT_DEFINITION_INPUT)) { setReportDefinitionInputStream((InputStream) inputs.get(REPORT_DEFINITION_INPUT)); } if (inputs.containsKey(USE_CONTENT_REPOSITORY)) { setUseContentRepository((Boolean) inputs.get(USE_CONTENT_REPOSITORY)); } if (inputs.containsKey(PAGINATE_OUTPUT)) { paginateOutput = "true".equalsIgnoreCase("" + inputs.get(PAGINATE_OUTPUT)); if (paginateOutput && inputs.containsKey(ACCEPTED_PAGE)) { acceptedPage = Integer.parseInt("" + inputs.get(ACCEPTED_PAGE)); } } } // END BEAN METHODS protected Object getInput(final String key, final Object defaultValue) { if (inputs != null) { Object input = inputs.get(key); if (input != null) { return input; } } return defaultValue; } /** * Get the MasterReport for the report-definition, the MasterReport object will be cached as needed, using the PentahoResourceLoader. * * @return a parsed MasterReport object * @throws ResourceException * @throws IOException */ public MasterReport getReport() throws ResourceException, IOException { if (report == null) { if (reportDefinitionInputStream != null) { ReportGenerator generator = ReportGenerator.createInstance(); InputSource repDefInputSource = new InputSource(reportDefinitionInputStream); report = generator.parseReport(repDefInputSource, getDefinedResourceURL(null)); } else if (reportDefinition != null) { // load the report definition as an action-sequence resource report = ReportCreator.createReport(reportDefinition.getAddress(), session); } else { report = ReportCreator.createReport(reportDefinitionPath, session); } report.setReportEnvironment(new PentahoReportEnvironment(report.getConfiguration())); } return report; } private String computeEffectiveOutputTarget(final MasterReport report) { if (outputTarget != null) { return outputTarget; } if (MIME_TYPE_CSV.equals(outputType)) { return CSVTableModule.TABLE_CSV_STREAM_EXPORT_TYPE; } if (MIME_TYPE_HTML.equals(outputType)) { if (isPaginateOutput()) { return HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE; } return HtmlTableModule.TABLE_HTML_STREAM_EXPORT_TYPE; } if (MIME_TYPE_PDF.equals(outputType)) { return PdfPageableModule.PDF_EXPORT_TYPE; } if (MIME_TYPE_RTF.equals(outputType)) { return RTFTableModule.TABLE_RTF_FLOW_EXPORT_TYPE; } if (MIME_TYPE_XLS.equals(outputType)) { return ExcelTableModule.EXCEL_FLOW_EXPORT_TYPE; } // if nothing is specified explicity, we may as well ask the report what it prefers.. final Object preferredOutputType = report.getAttribute(AttributeNames.Core.NAMESPACE, AttributeNames.Core.PREFERRED_OUTPUT_TYPE); if (preferredOutputType != null) { return String.valueOf(preferredOutputType); } // default to HTML stream .. return HtmlTableModule.TABLE_HTML_STREAM_EXPORT_TYPE; } /** * Apply inputs (if any) to corresponding report parameters, care is taken when checking parameter types to perform any necessary casting and conversion. * * @param report a MasterReport object to apply parameters to * @param context a ParameterContext for which the parameters will be under */ public void applyInputsToReportParameters(final MasterReport report, final ParameterContext context) { // apply inputs to report if (inputs != null) { ParameterDefinitionEntry[] params = report.getParameterDefinition().getParameterDefinitions(); for (ParameterDefinitionEntry param : params) { String paramName = param.getName(); Object value = inputs.get(paramName); Object defaultValue = param.getDefaultValue(context); if (value == null && defaultValue != null) { value = defaultValue; } if (value != null) { addParameter(report, param, paramName, value); } } } } private Object convert(final Class targetType, final Object rawValue) throws NumberFormatException { if (targetType == null) { throw new NullPointerException(); } if (rawValue == null) { return null; } if (targetType.isInstance(rawValue)) { return rawValue; } if (targetType.isAssignableFrom(TableModel.class) && IPentahoResultSet.class.isAssignableFrom(rawValue.getClass())) { // wrap IPentahoResultSet to simulate TableModel return new PentahoTableModel((IPentahoResultSet) rawValue); } final String valueAsString = String.valueOf(rawValue); if (StringUtils.isEmpty(valueAsString)) { return null; } if (targetType.equals(Date.class)) { return new Date(new Long(valueAsString)); } else { final ValueConverter valueConverter = ConverterRegistry.getInstance().getValueConverter(targetType); if (valueConverter != null) { try { return valueConverter.toPropertyValue(valueAsString); } catch (BeanException e) { throw new RuntimeException("Unable to convert parameter from String to real value."); } } } return rawValue; } private void addParameter(MasterReport report, ParameterDefinitionEntry param, String key, Object value) { if (value.getClass().isArray()) { final Class componentType; if (param.getValueType().isArray()) { componentType = param.getValueType().getComponentType(); } else { componentType = param.getValueType(); } final int length = Array.getLength(value); Object array = Array.newInstance(componentType, length); for (int i = 0; i < length; i++) { Array.set(array, i, convert(componentType, Array.get(value, i))); } report.getParameterValues().put(key, array); } else if (isAllowMultiSelect(param)) { // if the parameter allows multi selections, wrap this single input in an array // and re-call addParameter with it Object[] array = new Object[1]; array[0] = value; addParameter(report, param, key, array); } else { report.getParameterValues().put(key, convert(param.getValueType(), value)); } } private boolean isAllowMultiSelect(ParameterDefinitionEntry parameter) { if (parameter instanceof ListParameter) { return ((ListParameter) parameter).isAllowMultiSelection(); } return false; } private URL getDefinedResourceURL(final URL defaultValue) { if (inputs == null || inputs.containsKey(REPORTLOAD_RESURL) == false) { return defaultValue; } try { final String inputStringValue = (String) getInput(REPORTLOAD_RESURL, null); return new URL(inputStringValue); } catch (Exception e) { return defaultValue; } } protected int getYieldRate() { if (getInput(REPORTGENERATE_YIELDRATE, null) != null) { final Object inputValue = inputs.get(REPORTGENERATE_YIELDRATE); if (inputValue instanceof Number) { Number n = (Number) inputValue; if (n.intValue() < 1) { return 0; } return n.intValue(); } } return 0; } /** * This method returns the number of logical pages which make up the report. This results of this method are available only after validate/execute have been * successfully called. This field has no setter, as it should never be set by users. * * @return the number of logical pages in the report */ public int getPageCount() { return pageCount; } /** * This method will determine if the component instance 'is valid.' The validate() is called after all of the bean 'setters' have been called, so we may * validate on the actual values, not just the presence of inputs as we were historically accustomed to. * <p/> * Since we should have a list of all action-sequence inputs, we can determine if we have sufficient inputs to meet the parameter requirements of the * report-definition. This would include validation of values and ranges of values. * * @return true if valid * @throws Exception */ public boolean validate() throws Exception { if (reportDefinition == null && reportDefinitionInputStream == null && reportDefinitionPath == null) { log.error("[input] A report-definition was not provided."); return false; } if (paginateOutput && acceptedPage < 0) { log.warn("[input] With pageable output, accepted-page should be provided and >= 0 (using default)."); } if (reportDefinition != null && reportDefinitionPath != null && session == null) { log.error("[session] A valid session must be provided if the report-definition is given as a resource or by path."); return false; } if (outputStream == null) { log.error("[output] A valid OutputStream was not provided."); return false; } return true; } /** * Perform the primary function of this component, this is, to execute. This method will be invoked immediately following a successful validate(). * * @return true if successful execution * @throws Exception */ public boolean execute() throws Exception { MasterReport report = getReport(); try { ParameterContext parameterContext = new DefaultParameterContext(report); // open parameter context parameterContext.open(); applyInputsToReportParameters(report, parameterContext); parameterContext.close(); final String outputType = computeEffectiveOutputTarget(report); if (HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE.equals(outputType)) { String contentHandlerPattern = (String) getInput(REPORTHTML_CONTENTHANDLER_PATTERN, ClassicEngineBoot.getInstance().getGlobalConfig() .getConfigProperty("org.pentaho.web.ContentHandler")); if (useContentRepository) { // use the content repository contentHandlerPattern = (String) getInput(REPORTHTML_CONTENTHANDLER_PATTERN, ClassicEngineBoot.getInstance().getGlobalConfig().getConfigProperty( "org.pentaho.web.resource.ContentHandler")); IContentRepository contentRepository = PentahoSystem.get(IContentRepository.class, session); pageCount = PageableHTMLOutput.generate(session, report, acceptedPage, outputStream, contentRepository, contentHandlerPattern, getYieldRate()); return true; } else { // don't use the content repository pageCount = PageableHTMLOutput.generate(report, acceptedPage, outputStream, contentHandlerPattern, getYieldRate()); return true; } } if (HtmlTableModule.TABLE_HTML_STREAM_EXPORT_TYPE.equals(outputType)) { String contentHandlerPattern = (String) getInput(REPORTHTML_CONTENTHANDLER_PATTERN, ClassicEngineBoot.getInstance().getGlobalConfig() .getConfigProperty("org.pentaho.web.ContentHandler")); if (useContentRepository) { // use the content repository contentHandlerPattern = (String) getInput(REPORTHTML_CONTENTHANDLER_PATTERN, ClassicEngineBoot.getInstance().getGlobalConfig().getConfigProperty( "org.pentaho.web.resource.ContentHandler")); IContentRepository contentRepository = PentahoSystem.get(IContentRepository.class, session); return HTMLOutput.generate(session, report, outputStream, contentRepository, contentHandlerPattern, getYieldRate()); } else { // don't use the content repository return HTMLOutput.generate(report, outputStream, contentHandlerPattern, getYieldRate()); } } else if (PdfPageableModule.PDF_EXPORT_TYPE.equals(outputType)) { return PDFOutput.generate(report, outputStream, getYieldRate()); } else if (ExcelTableModule.EXCEL_FLOW_EXPORT_TYPE.equals(outputType)) { final InputStream templateInputStream = (InputStream) getInput(XLS_WORKBOOK_PARAM, null); return XLSOutput.generate(report, outputStream, templateInputStream, getYieldRate()); } else if (CSVTableModule.TABLE_CSV_STREAM_EXPORT_TYPE.equals(outputType)) { return CSVOutput.generate(report, outputStream, getYieldRate()); } else if (RTFTableModule.TABLE_RTF_FLOW_EXPORT_TYPE.equals(outputType)) { return RTFOutput.generate(report, outputStream, getYieldRate()); } } catch (Throwable t) { log.error("[execute] Component execution failed.", t); } // lets not pretend we were successfull, if the export type was not a valid one. return false; } }
package it.sephiroth.android.library.bottomnavigation; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v7.content.res.AppCompatResources; public class BottomNavigationItem { private final int id; private final int iconResource; private String title; private int color; private boolean enabled; public BottomNavigationItem(final int id, final int iconResource, final String title) { this.id = id; this.iconResource = iconResource; this.title = title; this.enabled = true; } protected Drawable getIcon(Context context) { return AppCompatResources.getDrawable(context, this.iconResource); } protected String getTitle() { return title; } public void setColor(final int color) { this.color = color; } public boolean hasColor() { return color != 0; } public int getColor() { return color; } public int getId() { return id; } public void setEnabled(final boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled; } @Override public String toString() { return "BottomNavigationItem{" + "id=" + id + ", iconResource=" + String.format("%x", iconResource) + ", title='" + title + '\'' + ", color=" + String.format("%x", color) + ", enabled=" + enabled + '}'; } }
package jsky.app.ot.gemini.editor.targetComponent; import edu.gemini.ags.api.*; import edu.gemini.pot.ModelConverters; import edu.gemini.pot.sp.ISPObsComponent; import edu.gemini.pot.sp.ISPObservation; import edu.gemini.shared.skyobject.Magnitude; import edu.gemini.shared.util.immutable.*; import edu.gemini.spModel.core.Angle; import edu.gemini.spModel.core.Coordinates; import edu.gemini.spModel.guide.*; import edu.gemini.spModel.obs.context.ObsContext; import edu.gemini.spModel.obscomp.SPInstObsComp; import edu.gemini.spModel.target.SPTarget; import edu.gemini.spModel.target.TelescopePosWatcher; import edu.gemini.spModel.target.WatchablePos; import edu.gemini.spModel.target.env.*; import edu.gemini.spModel.target.obsComp.TargetObsComp; import edu.gemini.spModel.target.obsComp.TargetSelection; import edu.gemini.spModel.target.offset.OffsetPosBase; import edu.gemini.spModel.target.offset.OffsetPosList; import edu.gemini.spModel.target.offset.OffsetUtil; import edu.gemini.spModel.util.SPTreeUtil; import jsky.app.ot.OT; import jsky.app.ot.OTOptions; import jsky.app.ot.util.Resources; import jsky.util.gui.TableUtil; import javax.swing.*; import javax.swing.border.Border; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.NumberFormat; import java.util.*; import java.util.List; import java.util.stream.Collectors; /** * An extension of the TableWidget to support telescope target lists. */ public final class TelescopePosTableWidget extends JTable implements TelescopePosWatcher { private static final Icon errorIcon = Resources.getIcon("eclipse/error.gif"); // Used to format values as strings. private static final NumberFormat nf = NumberFormat.getInstance(Locale.US); static { nf.setMaximumFractionDigits(2); } static class TableData extends AbstractTableModel { enum Col { TAG("Type Tag") { public String getValue(final Row row) { return row.tag(); } }, NAME("Name") { public String getValue(final Row row) { return row.name(); } }, RA("RA") { public String getValue(final Row row) { return row.target().flatMap(t -> t.getRaString(row.when())).getOrElse(""); } }, DEC("Dec") { public String getValue(final Row row) { return row.target().flatMap(t -> t.getDecString(row.when())).getOrElse(""); } }, DIST("Dist") { public String getValue(final Row row) { return row.distance().map(nf::format).getOrElse(""); } }; private final String displayName; Col(final String displayName) { this.displayName = displayName; } public String displayName() { return displayName; } public abstract String getValue(final Row row); } interface Row { boolean enabled(); String tag(); String name(); // really we want: GuideGroup \/ SPTarget default Option<SPTarget> target() { return None.instance(); } default Option<IndexedGuideGroup> group() { return None.instance(); } default Option<Double> distance() { return None.instance(); } default List<Row> children() { return Collections.emptyList(); } default Icon getIcon() { return null; } default boolean editable() { return true; } default boolean movable() { return true; } default Border border(int col) { return col == 0 ? BorderFactory.createEmptyBorder(0, 5, 0, 0) : null; } String formatMagnitude(Magnitude.Band band); Option<Long> when(); } static abstract class AbstractRow implements Row { private final boolean enabled; private final String tag; private final String name; private final Option<SPTarget> target; private final Option<Long> when; AbstractRow(final boolean enabled, final String tag, final String name, final Option<SPTarget> target, final Option<Long> when) { this.enabled = enabled; this.tag = tag; this.name = name; this.target = target; this.when = when; } @Override public boolean enabled() { return enabled; } @Override public String tag() { return tag; } @Override public String name() { return name; } @Override public Option<SPTarget> target() { return target; } @Override public Option<Long> when() { return when; } public Option<Magnitude> getMagnitude(final Magnitude.Band band) { return target.flatMap(t -> t.getMagnitude(band)); } @Override public String formatMagnitude(final Magnitude.Band band) { return getMagnitude(band).map(MagnitudeEditor::formatBrightness).getOrElse(""); } } static final class BaseTargetRow extends AbstractRow { BaseTargetRow(final SPTarget target, final Option<Long> when) { super(true, TargetEnvironment.BASE_NAME, target.getName(), new Some<>(target), when); } @Override public boolean movable() { return false; } } static abstract class NonBaseTargetRow extends AbstractRow { private final Option<Double> distance; NonBaseTargetRow(final boolean enabled, final String tag, final SPTarget target, final Option<Coordinates> baseCoords, final Option<Long> when) { super(enabled, tag, target.getName(), new Some<>(target), when); final Option<Coordinates> coords = getCoordinates(target, when); distance = baseCoords.flatMap(bc -> coords.map(c -> bc.angularDistance(c).toArcmins() ) ); } @Override public Option<Double> distance() { return distance; } } static final class GuideTargetRow extends NonBaseTargetRow { private final boolean isActiveGuideProbe; private final Option<AgsGuideQuality> quality; private final boolean editable; private final boolean movable; GuideTargetRow(final boolean isActiveGuideProbe, final Option<AgsGuideQuality> quality, final boolean enabled, final boolean editable, final boolean movable, final GuideProbe probe, final int index, final SPTarget target, final Option<Coordinates> baseCoords, final Option<Long> when) { super(enabled, String.format("%s (%d)", probe.getKey(), index), target, baseCoords, when); this.isActiveGuideProbe = isActiveGuideProbe; this.quality = quality; this.editable = editable; this.movable = movable; } @Override public Border border(int col) { return col == 0 ? BorderFactory.createEmptyBorder(0, 16, 0, 0) : null; } @Override public Icon getIcon() { return isActiveGuideProbe ? GuidingIcon.apply(quality.getOrElse(AgsGuideQuality.Unusable$.MODULE$), enabled()) : errorIcon; } @Override public boolean editable() { return editable; } @Override public boolean movable() { return movable; } } static final class UserTargetRow extends NonBaseTargetRow { UserTargetRow(final int index, final SPTarget target, final Option<Coordinates> baseCoords, final Option<Long> when) { super(true, String.format("%s (%d)", TargetEnvironment.USER_NAME, index), target, baseCoords, when); } @Override public boolean movable() { return false; } } static final class GroupRow extends AbstractRow { private static String extractName(final GuideGroup group) { final GuideGrp grp = group.grp(); final String name; if (grp.isAutomatic()) { if (grp instanceof AutomaticGroup.Disabled$) { name = "Auto (Disabled)"; } else { name = "Auto"; } } else { name = group.getName().getOrElse("Manual"); } return name; } private final Option<IndexedGuideGroup> group; private final List<Row> children; private final boolean editable; GroupRow(final boolean enabled, final boolean editable, final int index, final GuideGroup group, final List<Row> children) { super(enabled, extractName(group), "", None.instance(), None.instance()); this.group = new Some<>(IndexedGuideGroup$.MODULE$.apply(index, group)); this.children = Collections.unmodifiableList(children); this.editable = editable; } @Override public Option<IndexedGuideGroup> group() { return group; } @Override public List<Row> children() { return children; } @Override public boolean editable() { return editable; } @Override public boolean movable() { return false; } } // Collection of rows, which may include "subrows". private final ImList<Row> rows; // Total number of rows, including subrows. Precalculated as swing uses this value frequently. private final int numRows; private final ImList<Magnitude.Band> bands; private final ImList<String> columnHeaders; private final TargetEnvironment env; TableData() { rows = DefaultImList.create(); numRows = 0; bands = DefaultImList.create(); columnHeaders = computeColumnHeaders(bands); env = null; } private static Option<AgsGuideQuality> guideQuality(final Option<Tuple2<ObsContext, AgsMagnitude.MagnitudeTable>> ags, final GuideProbe guideProbe, final SPTarget guideStar) { return ags.flatMap(tup -> { if (guideProbe instanceof ValidatableGuideProbe) { final ObsContext ctx = tup._1(); final AgsMagnitude.MagnitudeTable magTable = tup._2(); final ValidatableGuideProbe vgp = (ValidatableGuideProbe) guideProbe; return AgsRegistrar.instance().currentStrategyForJava(ctx).map(strategy -> { final Option<AgsAnalysis> agsAnalysis = strategy.analyzeForJava(ctx, magTable, vgp, ModelConverters.toSideralTarget(guideStar)); return agsAnalysis.map(AgsAnalysis::quality); }).getOrElse(None.instance()); } else { return None.instance(); } }); } TableData(final Option<ObsContext> ctx, final TargetEnvironment env) { this.env = env; bands = getSortedBands(env); columnHeaders = computeColumnHeaders(bands); final List<Row> rowList = createRows(ctx); rows = DefaultImList.create(rowList); numRows = countRows(); } // Create rows for all the guide groups and targets, and keep track of the number of rows created. private List<Row> createRows(final Option<ObsContext> ctx) { final List<Row> tmpRows = new ArrayList<>(); // Add the base position first. final SPTarget base = env.getBase(); final Option<Long> when = ctx.flatMap(ObsContext::getSchedulingBlockStart); final Option<Coordinates> baseCoords = getCoordinates(base, when); tmpRows.add(new BaseTargetRow(base, when)); // Add all the guide groups and targets. final Option<Tuple2<ObsContext, AgsMagnitude.MagnitudeTable>> ags = ctx.map(oc -> new Pair<>(oc, OT.getMagnitudeTable())); final GuideEnvironment ge = env.getGuideEnvironment(); final ImList<GuideGroup> groups = ge.getOptions(); // Process each group. groups.zipWithIndex().foreach(gtup -> { final GuideGroup group = gtup._1(); final int groupIndex = gtup._2(); final boolean isPrimaryGroup = ge.getPrimaryIndex() == groupIndex; final boolean editable = group.isManual(); final boolean movable = group.isManual(); final List<Row> rowList = new ArrayList<>(); // Process the guide probe targets for this group. group.getAll().foreach(gpt -> { final GuideProbe guideProbe = gpt.getGuider(); final boolean isActive = ctx.exists(c -> GuideProbeUtil.instance.isAvailable(c, guideProbe)); final Option<SPTarget> primary = gpt.getPrimary(); // Add all the targets. gpt.getTargets().zipWithIndex().foreach(tup -> { final SPTarget target = tup._1(); final int index = tup._2() + 1; final Option<AgsGuideQuality> quality = guideQuality(ags, guideProbe, target); final boolean enabled = isPrimaryGroup && primary.exists(target::equals); final Row row = new GuideTargetRow(isActive, quality, enabled, editable, movable, guideProbe, index, target, baseCoords, when); rowList.add(row); }); }); tmpRows.add(new GroupRow(isPrimaryGroup, editable, groupIndex, group, rowList)); }); // Add the user positions. env.getUserTargets().zipWithIndex().foreach(tup -> { final SPTarget target = tup._1(); final int index = tup._2() + 1; tmpRows.add(new UserTargetRow(index, target, baseCoords, when)); }); return tmpRows; } // Pre-compute the number of rows as this will be frequently used. private int countRows() { return rows.foldLeft(0, (numRows, row) -> numRows + row.children().size() + 1); } // Gets all the magnitude bands used by targets in the target // environment. private ImList<Magnitude.Band> getSortedBands(final TargetEnvironment env) { // Keep a sorted set of bands, sorted by the name. final Set<Magnitude.Band> bands = new TreeSet<>(Magnitude.Band.WAVELENGTH_COMPARATOR); // Extract all the magnitude bands from the environment. env.getTargets().foreach(spTarget -> bands.addAll(spTarget.getMagnitudeBands())); // Create an immutable sorted list containing the results. return DefaultImList.create(bands); } /** * Conversions between SPTarget and row index. */ public Option<Integer> rowIndexForTarget(final SPTarget target) { if (target == null) return None.instance(); int index = 0; for (final Row row : rows) { if (row.target().getOrNull() == target) return new Some<>(index); ++index; for (final Row row2 : row.children()) { if (row2.target().getOrNull() == target) return new Some<>(index); ++index; } } return None.instance(); } public Option<SPTarget> targetAtRowIndex(final int index) { return rowAtRowIndex(index).flatMap(Row::target); } /** * Conversions between group index (index of group in list of groups) and row index. */ public Option<Integer> rowIndexForGroupIndex(final int gpIdx) { final ImList<GuideGroup> groups = env.getGroups(); if (gpIdx < 0 || gpIdx >= groups.size()) return None.instance(); int index = 0; for (final Row row : rows) { if (row.group().exists(igg -> igg.index() == gpIdx)) return new Some<>(index); index += row.children().size() + 1; } return None.instance(); } public Option<IndexedGuideGroup> groupAtRowIndex(final int index) { return rowAtRowIndex(index).flatMap(Row::group); } /** * Get the Row object for a given index. */ public Option<Row> rowAtRowIndex(final int index) { if (index >= 0) { int i = 0; for (final Row row : rows) { if (i == index) return new Some<>(row); ++i; final List<Row> children = row.children(); final int cindex = index - i; if (cindex < children.size()) { return new Some<>(children.get(cindex)); } else { i += children.size(); } } } return None.instance(); } private static ImList<String> computeColumnHeaders(final ImList<Magnitude.Band> bands) { // First add the fixed column headers final List<String> hdr = Arrays.stream(Col.values()).map(Col::displayName).collect(Collectors.toList()); // Add each magnitude band name hdr.addAll(bands.map(Magnitude.Band::name).toList()); return DefaultImList.create(hdr); } @Override public int getColumnCount() { return Col.values().length + bands.size(); } @Override public String getColumnName(final int index) { return columnHeaders.get(index); } @Override public Object getValueAt(final int rowIndex, final int columnIndex) { if (rowIndex < 0 || rowIndex >= numRows) return null; final Col[] cols = Col.values(); return rowAtRowIndex(rowIndex).map(row -> (columnIndex < cols.length) ? cols[columnIndex].getValue(row) : row.formatMagnitude(bands.get(columnIndex - cols.length)) ).getOrNull(); } @Override public int getRowCount() { return numRows; } } // Return the world coordinates for the given target private static Option<Coordinates> getCoordinates(final SPTarget tp, final Option<Long> when) { return tp.getRaDegrees(when).flatMap(ra -> tp.getDecDegrees(when).flatMap(dec -> ImOption.apply(Coordinates.fromDegrees(ra, dec).getOrElse(null)) ) ); } // Telescope position list private ISPObsComponent _obsComp; private TargetObsComp _dataObject; private TargetEnvironment _env; private TableData _tableData; // if true, ignore selections private boolean _ignoreSelection; private final EdCompTargetList owner; private final TelescopePosTableDropTarget dropTarget; private final TelescopePosTableDragSource dragSource; /** * Default constructor. */ public TelescopePosTableWidget(final EdCompTargetList owner) { this.owner = owner; setAutoResizeMode(JTable.AUTO_RESIZE_OFF); setModel(new TableData()); getSelectionModel().addListSelectionListener(e -> { if (_ignoreSelection) return; final TableData tableData = (TableData) getModel(); final int idx = getSelectionModel().getMinSelectionIndex(); tableData.rowAtRowIndex(idx).foreach(this::notifySelect); }); getTableHeader().setReorderingAllowed(false); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setShowHorizontalLines(false); setShowVerticalLines(true); getColumnModel().setColumnMargin(1); setRowSelectionAllowed(true); setDefaultRenderer(Object.class, new DefaultTableCellRenderer() { private final Color ODD_ROW_COLOR = new Color(248, 247, 255); @Override public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); _tableData.rowAtRowIndex(row).foreach(tableDataRow -> { // If we are in column 0, we treat this differently. if (column == 0) { if (tableDataRow.group().isDefined()) { final String name = tableDataRow.name(); final String tag = tableDataRow.tag(); label.setText(name != null && !name.equals("") ? name : tag); } else { label.setText(tableDataRow.tag()); } label.setIcon(tableDataRow.getIcon()); label.setDisabledIcon(tableDataRow.getIcon()); } else { label.setIcon(null); label.setDisabledIcon(null); } label.setBorder(tableDataRow.border(column)); final int style = tableDataRow.enabled() ? Font.PLAIN : Font.ITALIC; final Font font = label.getFont().deriveFont(style); label.setFont(font); final Color c = tableDataRow.enabled() ? Color.BLACK : Color.GRAY; label.setForeground(c); label.setEnabled(tableDataRow.enabled()); // If the row is not selected, set the background to alternating stripes. if (!isSelected) { label.setBackground(row % 2 == 0 ? Color.WHITE : ODD_ROW_COLOR); } }); return label; } }); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { if (e.getClickCount() != 2) return; updatePrimaryStar(); } }); // Add drag and drop features dropTarget = new TelescopePosTableDropTarget(this); dragSource = new TelescopePosTableDragSource(this); } @Override public void telescopePosUpdate(final WatchablePos tp) { final int index = getSelectedRow(); _resetTable(_env); // Restore the selection without firing new selection events. final boolean tmp = _ignoreSelection; try { _ignoreSelection = true; _setSelectedRow(index); } finally { _ignoreSelection = tmp; } } /** * Reinitialize the table. */ public void reinit(final TargetObsComp dataObject) { dragSource.setEditable(false); dropTarget.setEditable(false); // Remove all target listeners for the old target environment. if (_env != null) { _env.getTargets().foreach(t -> t.deleteWatcher(TelescopePosTableWidget.this)); } // Stop watching for changes on the obsComp stopWatchingSelection(); stopWatchingEnv(); // Watch the new list, and add all of its positions at once _obsComp = owner.getContextTargetObsComp(); _dataObject = dataObject; startWatchingEnv(); startWatchingSelection(); final TargetEnvironment env = _dataObject.getTargetEnvironment(); env.getTargets().foreach(t -> t.addWatcher(TelescopePosTableWidget.this)); final Option<SPTarget> tpOpt = TargetSelection.getTargetForNode(_dataObject.getTargetEnvironment(), _obsComp); _resetTable(_dataObject.getTargetEnvironment()); final Option<Integer> index = tpOpt.flatMap(_tableData::rowIndexForTarget); if (index.isDefined()) { _setSelectedRow(index.getValue()); } else { selectBasePos(); } final boolean editable = OTOptions.isEditable(owner.getProgram(), owner.getContextObservation()); dragSource.setEditable(editable); dropTarget.setEditable(editable); } private void stopWatchingSelection() { TargetSelection.deafTo(_obsComp, selectionListener); } private void startWatchingSelection() { TargetSelection.listenTo(_obsComp, selectionListener); } private void stopWatchingEnv() { if (_dataObject == null) return; _dataObject.removePropertyChangeListener(TargetObsComp.TARGET_ENV_PROP, envChangeListener); } private void startWatchingEnv() { if (_dataObject == null) return; _dataObject.addPropertyChangeListener(TargetObsComp.TARGET_ENV_PROP, envChangeListener); } /** * Notify the TargetSelection object when a row in the table has been selected. * This can either be a target row, or a group row. */ private void notifySelect(final TableData.Row row) { // Only one of these cases will hold. row.target().foreach(target -> { stopWatchingSelection(); try { TargetSelection.setTargetForNode(_env, _obsComp, target); } finally { startWatchingSelection(); } }); row.group().foreach(igg -> TargetSelection.setGuideGroupByIndex(_env, _obsComp, igg.index())); } private final PropertyChangeListener selectionListener = evt -> { if (_tableData == null) return; TargetSelection.getTargetForNode(_env, _obsComp) .flatMap(_tableData::rowIndexForTarget).foreach(this::_setSelectedRow); }; private final PropertyChangeListener envChangeListener = new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { final TargetEnvironment oldEnv = (TargetEnvironment) evt.getOldValue(); final TargetEnvironment newEnv = (TargetEnvironment) evt.getNewValue(); final TargetEnvironmentDiff diff = TargetEnvironmentDiff.all(oldEnv, newEnv); final Collection<SPTarget> rmTargets = diff.getRemovedTargets(); final Collection<SPTarget> addTargets = diff.getAddedTargets(); // First update the target listeners according to what was added and removed. rmTargets.forEach (t -> t.deleteWatcher(TelescopePosTableWidget.this)); addTargets.forEach(t -> t.addWatcher(TelescopePosTableWidget.this)); // Remember what was selected before the reset below. final int oldSelIndex = getSelectedRow(); final Option<SPTarget> oldSelTarget = _tableData.rowAtRowIndex(oldSelIndex).flatMap(TableData.Row::target); // Update the table -- setting _tableData .... _resetTable(newEnv); // Update the selection. if (rmTargets.isEmpty() && (addTargets.size() == 1)) { // A single position was added, so just select it. selectTarget(addTargets.iterator().next()); return; } // If obs comp has a selected target, then honor it. final Option<SPTarget> newSelectedTarget = TargetSelection.getTargetForNode(_env, _obsComp); if (newSelectedTarget.isDefined()) { _tableData.rowIndexForTarget(newSelectedTarget.getValue()) .foreach(TelescopePosTableWidget.this::_setSelectedRow); return; } // If a new group was added, select it. final Option<IndexedGuideGroup> newGpIdx = TargetSelection.getIndexedGuideGroupForNode(_env, _obsComp); if (newGpIdx.isDefined()) { final Option<Integer> rowIdx = _tableData.rowIndexForGroupIndex(newGpIdx.getValue().index()); if (rowIdx.isDefined()) { _setSelectedRow(rowIdx.getValue()); return; } } // Try to select the same target that was selected before, if it is there in the new table. if (oldSelTarget.exists(t -> _tableData.rowIndexForTarget(t).isDefined())) { oldSelTarget.foreach(TelescopePosTableWidget.this::selectTarget); return; } // Okay, the old selected target or group was removed. Try to select the // target or group at the same position as the old selection. final int newSelIndex = (oldSelIndex >= getRowCount()) ? getRowCount() - 1 : oldSelIndex; if (newSelIndex >= 0) { selectRowAt(newSelIndex); } else { selectBasePos(); } } }; private void _resetTable(final TargetEnvironment env) { _env = env; final Option<ObsContext> ctx = ObsContext.create(owner.getContextObservation()).map(c -> c.withTargets(env)); _tableData = new TableData(ctx, env); _ignoreSelection = true; try { setModel(_tableData); } finally { _ignoreSelection = false; } TableUtil.initColumnSizes(this); } /** * Update the primary star in a set of guide targets to the currently selected target. */ void updatePrimaryStar() { if (_env == null || !OTOptions.isEditable(_obsComp.getProgram(), _obsComp.getContextObservation())) return; // TODO: This method must be tested in greater detail, since custom guiding is required for offset positions. final Option<SPTarget> targetOpt = getSelectedPos(); if (targetOpt.isDefined()) { final boolean autoGroup = targetOpt.flatMap(this::getTargetGroup).exists(igg -> igg.group().isAutomatic()); if (!autoGroup) PrimaryTargetToggle.instance.toggle(_dataObject, targetOpt.getValue()); } else { getSelectedGroup().foreach(igg -> { final TargetEnvironment env = _dataObject.getTargetEnvironment(); final GuideGroup primary = env.getOrCreatePrimaryGuideGroup(); if (primary != igg.group() && confirmGroupChange(primary, igg.group())) { final GuideEnvironment ge = env.getGuideEnvironment(); if (ge != null) { _dataObject.setTargetEnvironment(env.setGuideEnvironment(ge.setPrimaryIndex(igg.index()))); // If we are switching to an automatic group, we also // possibly need to update the position angle. final GuideGrp grp = igg.group().grp(); if (grp instanceof AutomaticGroup.Active) { updatePosAngle(((AutomaticGroup.Active) grp).posAngle()); } } } }); } } // Finds the instrument component in the observation that houses the // target component being edited and then sets its position angle to the // given value. This is done in response to making the automatic guide // group primary. private void updatePosAngle(Angle posAngle) { final ISPObservation obs = _obsComp.getContextObservation(); if (obs != null) { final ISPObsComponent oc = SPTreeUtil.findInstrument(obs); if (oc != null) { final SPInstObsComp inst = (SPInstObsComp) oc.getDataObject(); final double oldPosAngle = inst.getPosAngleDegrees(); final double newPosAngle = posAngle.toDegrees(); if (oldPosAngle != newPosAngle) { inst.setPosAngleDegrees(newPosAngle); oc.setDataObject(inst); } } } } /** * Get the position that is currently selected. */ private Option<SPTarget> getSelectedPos() { return TargetSelection.getTargetForNode(_env, _obsComp); } /** * Get the group that is currently selected. */ private Option<IndexedGuideGroup> getSelectedGroup() { return TargetSelection.getIndexedGuideGroupForNode(_env, _obsComp); } /** * Get the group that is currently selected or the parent group of the selected node. * @param env the target environment to use */ public Option<IndexedGuideGroup> getSelectedGroupOrParentGroup(final TargetEnvironment env) { final Option<IndexedGuideGroup> groupOpt = getSelectedGroup(); if (groupOpt.isDefined()) return groupOpt; return getSelectedPos() .map(target -> env.getGroups().zipWithIndex().find(gg -> gg._1().containsTarget(target)).map(IndexedGuideGroup$.MODULE$::fromReverseTuple)) .getOrElse(None.instance()); } /** * Returns the selected node (currently only single select is allowed). */ public Option<TableData.Row> getSelectedNode() { return _tableData.rowAtRowIndex(getSelectedRow()); } /** * Returns true if it is ok to add the given item row to the given parent row. * For this to be the case, the item must be movable, the parent must be an editable guide group row. */ public boolean isOkayToAdd(final TableData.Row item, final TableData.Row parent) { if (item == parent) return false; final Option<GuideGroup> groupOpt = parent.group().map(IndexedGuideGroup::group); final Option<SPTarget> targetOpt = item.target(); return item.movable() && (parent instanceof TableData.GroupRow) && parent.editable() && !groupOpt.exists(g -> targetOpt.exists(g::containsTarget)); } /** * Returns true if it is ok to move the given row item to the given parent row */ public boolean isOkayToMove(TableData.Row item, TableData.Row parent) { return isOkayToAdd(item, parent); } /** * Moves the given row item to the given parent row. * In this case, a guide star to a group. */ public void moveTo(final TableData.Row item, final TableData.Row parent) { if (item == null) return; final Option<IndexedGuideGroup> snkGrpOpt = parent.group(); final SPTarget target = item.target().getOrNull(); if (snkGrpOpt.exists(igg -> igg.group().containsTarget(target))) return; snkGrpOpt.foreach(snkGrp -> getTargetGroup(target).foreach(srcGrp -> { final ImList<GuideProbeTargets> targetList = srcGrp.group().getAllContaining(target); if (targetList.isEmpty()) return; final GuideProbeTargets src = targetList.get(0); final GuideProbe guideprobe = src.getGuider(); GuideProbeTargets snk = snkGrp.group().get(guideprobe).getOrNull(); if (snk == null) { snk = GuideProbeTargets.create(guideprobe); } final boolean isPrimary = src.getPrimary().getOrNull() == target; final GuideProbeTargets newSrc = src.removeTarget(target); final SPTarget newTarget = target.clone(); GuideProbeTargets newSnk = snk.setOptions(snk.getOptions().append(newTarget)); if (isPrimary) { newSnk = newSnk.selectPrimary(newTarget); } final GuideEnvironment guideEnv = _env.getGuideEnvironment(); final GuideEnvironment newGuideEnv = guideEnv.putGuideProbeTargets(srcGrp.index(), newSrc).putGuideProbeTargets(snkGrp.index(), newSnk); final TargetEnvironment newTargetEnv = _env.setGuideEnvironment(newGuideEnv); _dataObject.setTargetEnvironment(newTargetEnv); }) ); } /** * Get the group to which this target belongs, or null. */ private Option<IndexedGuideGroup> getTargetGroup(final SPTarget target) { return _env.getGuideEnvironment().getOptions().zipWithIndex().find(gg -> gg._1().containsTarget(target)) .map(IndexedGuideGroup$.MODULE$::fromReverseTuple); } /** * Updates the TargetSelection's target or group, and selects the relevant row in the table. */ public void selectRowAt(final int index) { if (_tableData == null) return; final SPTarget target = _tableData.targetAtRowIndex(index).getOrNull(); if (target != null) { selectTarget(target); } else { _tableData.groupAtRowIndex(index).foreach(this::selectGroup); } } /** * Select the base position, updating the TargetSelection's target, and set the relevant row in the table. */ void selectBasePos() { selectTarget(_env.getBase()); } /** * Updates the TargetSelection's target, and sets the relevant row in the table. */ void selectTarget(final SPTarget tp) { TargetSelection.setTargetForNode(_env, _obsComp, tp); _tableData.rowIndexForTarget(tp).foreach(this::_setSelectedRow); } /** * Update the TargetSelection's group, and sets the relevant row in the table. */ void selectGroup(final IndexedGuideGroup igg) { TargetSelection.setGuideGroupByIndex(_env, _obsComp, igg.index()); _tableData.rowIndexForGroupIndex(igg.index()).foreach(this::_setSelectedRow); } /** * Selects the table row at the given location. */ public void setSelectedRow(final Point location) { selectRowAt(rowAtPoint(location)); } /** * Returns the node at the given location or null if not found. */ public TableData.Row getNode(final Point location) { return _tableData.rowAtRowIndex(rowAtPoint(location)).getOrNull(); } /** * Selects the relevant row in the table. */ private void _setSelectedRow(final int index) { if ((index < 0) || (index >= getRowCount())) return; getSelectionModel().setSelectionInterval(index, index); } public void setIgnoreSelection(boolean ignore) { _ignoreSelection = ignore; } public String toString() { final String head = getClass().getName() + "[\n"; String body = ""; final int numRows = getRowCount(); final int numCols = getColumnCount(); for (int row = 0; row < numRows; ++row) { for (int col = 0; col < numCols; ++col) { body += "\t" + _tableData.getValueAt(col, row); } body += "\n"; } body += "]"; return head + body; } // OT-32: Displays a warning/confirmation dialog when guiding config is impacted // by changes to primary group. // Returns true if the new primary guide group should be set, false to cancel // the operation. boolean confirmGroupChange(final GuideGroup oldPrimary, final GuideGroup newPrimary) { final List<OffsetPosList<OffsetPosBase>> posLists = OffsetUtil.allOffsetPosLists(owner.getContextObservation()); if (!posLists.isEmpty()) { final SortedSet<GuideProbe> oldGuideProbes = oldPrimary.getReferencedGuiders(); final SortedSet<GuideProbe> newGuideProbes = newPrimary.getReferencedGuiders(); final Set<String> warnSet = new TreeSet<>(); for (OffsetPosList<OffsetPosBase> posList : posLists) { for (OffsetPosBase offsetPos : posList.getAllPositions()) { for (GuideProbe guideProbe : oldGuideProbes) { final GuideOption guideOption = offsetPos.getLink(guideProbe); final GuideOptions options = guideProbe.getGuideOptions(); if (guideOption != null && guideOption != options.getDefaultActive() && !newGuideProbes.contains(guideProbe)) { warnSet.add(guideProbe.getKey()); } } } } if (!warnSet.isEmpty()) { return confirmGroupChangeDialog(warnSet); } } return true; } // OT-32: Displays a warning/confirmation dialog when the given guide probe configs are impacted private boolean confirmGroupChangeDialog(final Set<String> warnSet) { final StringBuilder msg = new StringBuilder(); msg.append("<html>Changing the primary group will result in losing the existing " + "offset iterator guiding configuration for:<ul>"); warnSet.forEach(key -> msg.append("<li>").append(key).append("</li>")); msg.append("</ul><p>Continue?"); return JOptionPane.showConfirmDialog(this, msg.toString(), "Warning", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION; } }
package gov.nih.nci.caintegrator2.application.study.deployment; import gov.nih.nci.caintegrator2.application.analysis.GenePatternClientFactory; import gov.nih.nci.caintegrator2.application.arraydata.ArrayDataService; import gov.nih.nci.caintegrator2.application.study.DeploymentListener; import gov.nih.nci.caintegrator2.application.study.Status; import gov.nih.nci.caintegrator2.application.study.StudyConfiguration; import gov.nih.nci.caintegrator2.application.study.ValidationException; import gov.nih.nci.caintegrator2.common.DateUtil; import gov.nih.nci.caintegrator2.data.CaIntegrator2Dao; import gov.nih.nci.caintegrator2.external.ConnectionException; import gov.nih.nci.caintegrator2.external.DataRetrievalException; import gov.nih.nci.caintegrator2.external.bioconductor.BioconductorService; import gov.nih.nci.caintegrator2.external.caarray.CaArrayFacade; import java.util.Date; import org.apache.log4j.Logger; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * Performs study deployments and notifies clients. */ @Transactional (propagation = Propagation.REQUIRED) public class DeploymentServiceImpl implements DeploymentService { private static final Logger LOGGER = Logger.getLogger(DeploymentServiceImpl.class); private CaArrayFacade caArrayFacade; private CaIntegrator2Dao dao; private ArrayDataService arrayDataService; private BioconductorService bioconductorService; private CopyNumberHandlerFactory copyNumberHandlerFactory = new CopyNumberHandlerFactoryImpl(); private GenePatternClientFactory genePatternClientFactory; /** * {@inheritDoc} */ @SuppressWarnings("PMD.AvoidReassigningParameters") // preferable in this instance for error handling. public Status prepareForDeployment(StudyConfiguration studyConfiguration, DeploymentListener listener) { try { studyConfiguration = getDao().get(studyConfiguration.getId(), StudyConfiguration.class); return startDeployment(studyConfiguration, listener); } catch (Exception e) { return handleDeploymentFailure(studyConfiguration, listener, e); } } /** * {@inheritDoc} */ @SuppressWarnings("PMD.AvoidReassigningParameters") // preferable in this instance for error handling. public Status performDeployment(StudyConfiguration studyConfiguration, DeploymentListener listener) { try { studyConfiguration = getDao().get(studyConfiguration.getId(), StudyConfiguration.class); if (!Status.PROCESSING.equals(studyConfiguration.getStatus())) { startDeployment(studyConfiguration, listener); } return doDeployment(studyConfiguration, listener); } catch (Exception e) { return handleDeploymentFailure(studyConfiguration, listener, e); } catch (Error e) { return handleDeploymentFailure(studyConfiguration, listener, e); } } private Status handleDeploymentFailure(StudyConfiguration studyConfiguration, DeploymentListener listener, Throwable e) { LOGGER.error("Deployment of study " + studyConfiguration.getStudy().getShortTitleText() + " failed.", e); studyConfiguration.setStatusDescription((e.getMessage() != null) ? e.getMessage() : e.toString()); studyConfiguration.setStatus(Status.ERROR); updateStatus(studyConfiguration, listener); return studyConfiguration.getStatus(); } private void updateStatus(StudyConfiguration studyConfiguration, DeploymentListener listener) { getDao().save(studyConfiguration); if (listener != null) { listener.statusUpdated(studyConfiguration); } } private Status doDeployment(StudyConfiguration studyConfiguration, DeploymentListener listener) throws ConnectionException, DataRetrievalException, ValidationException { if (!studyConfiguration.getGenomicDataSources().isEmpty()) { GenomicDataHelper genomicDataHelper = new GenomicDataHelper(getCaArrayFacade(), getArrayDataService(), getDao(), getBioconductorService(), getCopyNumberHandlerFactory()); genomicDataHelper.setGenePatternClientFactory(getGenePatternClientFactory()); genomicDataHelper.loadData(studyConfiguration); } studyConfiguration.setStatus(Status.DEPLOYED); studyConfiguration.setDeploymentFinishDate(new Date()); studyConfiguration.setStatusDescription("Minutes for deployment (approx): " + DateUtil.compareDatesInMinutes(studyConfiguration.getDeploymentStartDate(), studyConfiguration.getDeploymentFinishDate())); updateStatus(studyConfiguration, listener); return studyConfiguration.getStatus(); } private Status startDeployment(StudyConfiguration studyConfiguration, DeploymentListener listener) { studyConfiguration.setDeploymentStartDate(new Date()); studyConfiguration.setDeploymentFinishDate(null); studyConfiguration.setStatusDescription(null); studyConfiguration.setStatus(Status.PROCESSING); updateStatus(studyConfiguration, listener); return studyConfiguration.getStatus(); } /** * @return the caArrayFacade */ public CaArrayFacade getCaArrayFacade() { return caArrayFacade; } /** * @param caArrayFacade the caArrayFacade to set */ public void setCaArrayFacade(CaArrayFacade caArrayFacade) { this.caArrayFacade = caArrayFacade; } /** * @return the dao */ public CaIntegrator2Dao getDao() { return dao; } /** * @param dao the dao to set */ public void setDao(CaIntegrator2Dao dao) { this.dao = dao; } /** * @return the arrayDataService */ public ArrayDataService getArrayDataService() { return arrayDataService; } /** * @param arrayDataService the arrayDataService to set */ public void setArrayDataService(ArrayDataService arrayDataService) { this.arrayDataService = arrayDataService; } /** * @return the bioconductorService */ public BioconductorService getBioconductorService() { return bioconductorService; } /** * @param bioconductorService the bioconductorService to set */ public void setBioconductorService(BioconductorService bioconductorService) { this.bioconductorService = bioconductorService; } /** * @return the copyNumberHandlerFactory */ public CopyNumberHandlerFactory getCopyNumberHandlerFactory() { return copyNumberHandlerFactory; } /** * @param copyNumberHandlerFactory the copyNumberHandlerFactory to set */ public void setCopyNumberHandlerFactory(CopyNumberHandlerFactory copyNumberHandlerFactory) { this.copyNumberHandlerFactory = copyNumberHandlerFactory; } /** * @return the genePatternClientFactory */ public GenePatternClientFactory getGenePatternClientFactory() { return genePatternClientFactory; } /** * @param genePatternClientFactory the genePatternClientFactory to set */ public void setGenePatternClientFactory(GenePatternClientFactory genePatternClientFactory) { this.genePatternClientFactory = genePatternClientFactory; } }
package com.linkedin.camus.etl.kafka.common; import com.linkedin.camus.coders.CamusWrapper; import com.linkedin.camus.etl.IEtlKey; import com.linkedin.camus.etl.RecordWriterProvider; import com.linkedin.camus.etl.kafka.mapred.EtlMultiOutputFormat; import java.io.IOException; import org.apache.hadoop.fs.Path; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.SequenceFile.CompressionType; import org.apache.hadoop.io.compress.DefaultCodec; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.conf.Configuration; import org.apache.log4j.Logger; /** * Provides a RecordWriter that uses SequenceFile.Writer to write * SequenceFiles records to HDFS. Compression settings are controlled via * the usual hadoop configuration values. * * - mapreduce.output.fileoutputformat.compress - true or false * - mapreduce.output.fileoutputformat.compress.codec - org.apache.hadoop.io.compress.* (SnappyCodec, etc.) * - mapreduce.output.fileoutputformat.compress.type - BLOCK or RECORD * */ public class SequenceFileRecordWriterProvider implements RecordWriterProvider { public static final String ETL_OUTPUT_RECORD_DELIMITER = "etl.output.record.delimiter"; public static final String DEFAULT_RECORD_DELIMITER = ""; private static Logger log = Logger.getLogger(SequenceFileRecordWriterProvider.class); protected String recordDelimiter = null; // TODO: Make this configurable somehow. // To do this, we'd have to make SequenceFileRecordWriterProvider have an // init(JobContext context) method signature that EtlMultiOutputFormat would always call. @Override public String getFilenameExtension() { return ""; } @Override public RecordWriter<IEtlKey, CamusWrapper> getDataRecordWriter( TaskAttemptContext context, String fileName, CamusWrapper camusWrapper, FileOutputCommitter committer) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); // If recordDelimiter hasn't been initialized, do so now if (recordDelimiter == null) { recordDelimiter = conf.get( ETL_OUTPUT_RECORD_DELIMITER, DEFAULT_RECORD_DELIMITER ); } CompressionCodec compressionCodec = null; CompressionType compressionType = CompressionType.NONE; // Determine compression type (BLOCK or RECORD) and compression codec to use. if (SequenceFileOutputFormat.getCompressOutput(context)) { compressionType = SequenceFileOutputFormat.getOutputCompressionType(context); Class<?> codecClass = SequenceFileOutputFormat.getOutputCompressorClass(context, DefaultCodec.class); // Instantiate the CompressionCodec Class compressionCodec = (CompressionCodec)ReflectionUtils.newInstance(codecClass, conf); } // Get the filename for this RecordWriter. Path path = new Path( committer.getWorkPath(), EtlMultiOutputFormat.getUniqueFile( context, fileName, getFilenameExtension() ) ); log.info("Creating new SequenceFile.Writer with compression type " + compressionType + " and compression codec " + compressionCodec.getClass().getName()); final SequenceFile.Writer writer = SequenceFile.createWriter( path.getFileSystem(conf), conf, path, LongWritable.class, Text.class, compressionType, compressionCodec, context ); // Return a new anonymous RecordWriter that uses the // SequenceFile.Writer to write data to HDFS return new RecordWriter<IEtlKey, CamusWrapper>() { @Override public void write(IEtlKey key, CamusWrapper data) throws IOException, InterruptedException { String record = (String)data.getRecord() + recordDelimiter; // Use the timestamp from the EtlKey as the key for this record. // TODO: Is there a better key to use here? writer.append(new LongWritable(key.getTime()), new Text(record)); } @Override public void close(TaskAttemptContext context) throws IOException, InterruptedException { writer.close(); } }; } }
package org.jasig.cas.web.flow; import org.springframework.util.StringUtils; import org.springframework.webflow.conversation.*; import org.springframework.webflow.execution.FlowExecution; import org.springframework.webflow.execution.FlowExecutionKey; import org.springframework.webflow.execution.repository.BadlyFormattedFlowExecutionKeyException; import org.springframework.webflow.execution.repository.FlowExecutionRepositoryException; import org.springframework.webflow.execution.repository.impl.DefaultFlowExecutionRepository; import org.springframework.webflow.execution.repository.snapshot.FlowExecutionSnapshotFactory; import org.springframework.webflow.execution.repository.support.CompositeFlowExecutionKey; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.IvParameterSpec; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.nio.charset.Charset; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.UUID; /** * Extension to the default Spring Web Flow {@link DefaultFlowExecutionRepository}. We override a number of protected methods to * provide our own key which includes a random part. Due to the structure of the super class, we've also had to copy a * number of private methods to the sub class in order to have it actually work. <strong>This is not a good idea.</strong> * * @author Scott Battaglia * @version $Revision$ $Date$ * @since 3.4.7 */ public final class CasFlowExecutionKeyFactory extends DefaultFlowExecutionRepository { public static final String DEFAULT_ENCRYPTION_ALGORITHM = "AES"; public static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; private boolean defaultBehavior = false; @NotNull private final ConversationManager conversationManager; @NotNull private final Key key; @NotNull private final String cipherAlgorithm; private final byte[] initialVector = getRandomSalt(16); private final IvParameterSpec ivs = new IvParameterSpec(this.initialVector); public CasFlowExecutionKeyFactory(final ConversationManager conversationManager, final FlowExecutionSnapshotFactory snapshotFactory) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException { this(conversationManager, snapshotFactory, DEFAULT_CIPHER_ALGORITHM, KeyGenerator.getInstance(DEFAULT_ENCRYPTION_ALGORITHM).generateKey()); } public CasFlowExecutionKeyFactory(final ConversationManager conversationManager, final FlowExecutionSnapshotFactory snapshotFactory, final String cipherAlgorithm, final Key secretKey) { super(conversationManager, snapshotFactory); this.conversationManager = conversationManager; this.key = secretKey; this.cipherAlgorithm = cipherAlgorithm; } private static byte[] getRandomSalt(final int size) { final SecureRandom secureRandom = new SecureRandom(); final byte[] bytes = new byte[size]; secureRandom.nextBytes(bytes); return bytes; } protected String decrypt(final String value) { if (value == null) { return null; } try { final Cipher cipher = Cipher.getInstance(this.cipherAlgorithm); cipher.init(Cipher.DECRYPT_MODE, this.key, this.ivs); return new String(cipher.doFinal(hexStringToByteArray(value))); } catch (final Exception e) { throw new RuntimeException(e); } } protected String encrypt(final String value) { if (value == null) { return null; } try { final Cipher cipher = Cipher.getInstance(this.cipherAlgorithm); cipher.init(Cipher.ENCRYPT_MODE, this.key, this.ivs); return byteArrayToHexString(cipher.doFinal(value.getBytes())); } catch (final Exception e) { throw new RuntimeException(e); } } public static String byteArrayToHexString(byte[] b){ StringBuffer sb = new StringBuffer(b.length * 2); for (int i = 0; i < b.length; i++){ int v = b[i] & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } return sb.toString().toUpperCase(); } protected static byte[] hexStringToByteArray(final String s) { byte[] b = new byte[s.length() / 2]; for (int i = 0; i < b.length; i++){ int index = i * 2; int v = Integer.parseInt(s.substring(index, index + 2), 16); b[i] = (byte)v; } return b; } public FlowExecutionKey getKey(final FlowExecution execution) { if (this.defaultBehavior) { return super.getKey(execution); } final CasFlowExecutionKey key = (CasFlowExecutionKey) execution.getKey(); if (key == null) { final Conversation conversation = beginConversation(execution); final ConversationId executionId = conversation.getId(); final Serializable nextSnapshotId = nextSnapshotId(executionId); final String unencryptedVersion = UUID.randomUUID().toString() + CasFlowExecutionKey.KEY_SEPARATOR + "e" + executionId + "s" + nextSnapshotId; final String encryptedVersion = encrypt(unencryptedVersion); return new CasFlowExecutionKey(executionId, nextSnapshotId, encryptedVersion); } else { if (getAlwaysGenerateNewNextKey()) { final Serializable executionId = key.getExecutionId(); final Serializable snapshotId = nextSnapshotId(key.getExecutionId()); final String unencryptedVersion = UUID.randomUUID().toString() + CasFlowExecutionKey.KEY_SEPARATOR + "e" + executionId + "s" + snapshotId; final String encryptedVersion = encrypt(unencryptedVersion); return new CasFlowExecutionKey(executionId, snapshotId, encryptedVersion); } else { return execution.getKey(); } } } public FlowExecutionKey parseFlowExecutionKey(final String encodedKey) throws FlowExecutionRepositoryException { if (this.defaultBehavior) { return super.parseFlowExecutionKey(encodedKey); } if (!StringUtils.hasText(encodedKey)) { throw new BadlyFormattedFlowExecutionKeyException(encodedKey, "The string-encoded flow execution key is required"); } final String unencryptedVersion = decrypt(encodedKey); String[] keyParts = CasFlowExecutionKey.keyParts(unencryptedVersion); Serializable executionId = parseExecutionId(keyParts[0], encodedKey); Serializable snapshotId = parseSnapshotId(keyParts[1], encodedKey); return new CasFlowExecutionKey(executionId, snapshotId, encodedKey); } private ConversationId parseExecutionId(final String encodedId, final String encodedKey) throws BadlyFormattedFlowExecutionKeyException { try { return this.conversationManager.parseConversationId(encodedId); } catch (ConversationException e) { throw new BadlyFormattedFlowExecutionKeyException(encodedKey, CompositeFlowExecutionKey.getFormat(), e); } } private Serializable parseSnapshotId(final String encodedId, final String encodedKey) throws BadlyFormattedFlowExecutionKeyException { try { return Integer.valueOf(encodedId); } catch (NumberFormatException e) { throw new BadlyFormattedFlowExecutionKeyException(encodedKey, CompositeFlowExecutionKey.getFormat(), e); } } /** * Copied from super-class since its marked as private. * @param execution * @return */ private Conversation beginConversation(FlowExecution execution) { ConversationParameters parameters = createConversationParameters(execution); Conversation conversation = this.conversationManager.beginConversation(parameters); return conversation; } public void setDefaultBehavior(final boolean defaultBehavior) { this.defaultBehavior = defaultBehavior; } }
package org.jasig.cas.authentication.principal; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jasig.cas.util.DefaultUniqueTicketIdGenerator; import org.jasig.cas.util.SamlUtils; import org.jasig.cas.util.UniqueTicketIdGenerator; public abstract class AbstractWebApplicationService implements WebApplicationService { protected static final Log LOG = LogFactory.getLog(SamlService.class); private static final Map<String, Object> EMPTY_MAP = Collections.unmodifiableMap(new HashMap<String, Object>()); private static final UniqueTicketIdGenerator GENERATOR = new DefaultUniqueTicketIdGenerator(); /** The id of the service. */ private final String id; /** The original url provided, used to reconstruct the redirect url. */ private final String originalUrl; private final String artifactId; private Principal principal; private boolean loggedOutAlready = false; protected AbstractWebApplicationService(final String id, final String originalUrl, final String artifactId) { this.id = id; this.originalUrl = originalUrl; this.artifactId = artifactId; } public final String getId() { return this.id; } public final String getArtifactId() { return this.artifactId; } public final Map<String, Object> getAttributes() { return EMPTY_MAP; } protected static final String cleanupUrl(final String url) { if (url == null) { return null; } final int jsessionPosition = url.indexOf(";jsession"); if (jsessionPosition == -1) { return url; } final int questionMarkPosition = url.indexOf("?"); if (questionMarkPosition < jsessionPosition) { return url.substring(0, url.indexOf(";jsession")); } return url.substring(0, jsessionPosition) + url.substring(questionMarkPosition); } protected final String getOriginalUrl() { return this.originalUrl; } public boolean equals(final Object object) { if (object == null) { return false; } if (object instanceof Service) { final Service service = (Service) object; return getId().equals(service.getId()); } return false; } protected Principal getPrincipal() { return this.principal; } public void setPrincipal(final Principal principal) { this.principal = principal; } public boolean matches(final Service service) { return this.id.equals(service.getId()); } public synchronized boolean logOutOfService(final String sessionIdentifier) { if (this.loggedOutAlready) { return true; } LOG.debug("Sending logout request for: " + getId()); final String logoutRequest = "<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\"" + GENERATOR.getNewTicketId("LR") + "\" Version=\"2.0\" IssueInstant=\"" + SamlUtils.getCurrentDateAndTime() + "\"><saml:NameID xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\">@NOT_USED@</saml:NameID><samlp:SessionIndex>" + sessionIdentifier + "</samlp:SessionIndex></samlp:LogoutRequest>"; HttpURLConnection connection = null; try { final URL logoutUrl = new URL(getOriginalUrl()); final String output = "logoutRequest=" + logoutRequest; connection = (HttpURLConnection) logoutUrl.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Content-Length", "" + Integer.toString(output.getBytes().length)); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); final DataOutputStream printout = new DataOutputStream(connection .getOutputStream()); printout.writeBytes(output); printout.flush(); printout.close(); final BufferedReader in = new BufferedReader(new InputStreamReader(connection .getInputStream())); while (in.readLine() != null) { // nothing to do } return true; } catch (final Exception e) { return false; } finally { if (connection != null) { connection.disconnect(); } this.loggedOutAlready = true; } } }
package com.ejl.searcher.implement; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import com.ejl.searcher.SearchSql; import com.ejl.searcher.SearchSqlResolver; import com.ejl.searcher.SearcherException; import com.ejl.searcher.beanmap.SearchBeanMap; import com.ejl.searcher.dialect.Dialect; import com.ejl.searcher.dialect.Dialect.PaginateSql; import com.ejl.searcher.param.FilterParam; import com.ejl.searcher.param.Operator; import com.ejl.searcher.param.SearchParam; import com.ejl.searcher.util.StrUtils; /** * SQL * * @author Troy.Zhou @ 2017-03-20 * @since V1.1.1 */ public class MainSearchSqlResolver implements SearchSqlResolver { static final Pattern DATE_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}"); static final Pattern DATE_MINUTE_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}"); static final Pattern DATE_SECOND_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}"); private Dialect dialect; private String virtualParamPrefix = ":"; @Override public SearchSql resolve(SearchBeanMap searchBeanMap, SearchParam searchParam) { if (!searchBeanMap.isVirtualResolved()) { resolveVirtualParams(searchBeanMap); } List<String> fieldList = searchBeanMap.getFieldList(); Map<String, String> fieldDbMap = searchBeanMap.getFieldDbMap(); Map<String, String> fieldDbAliasMap = searchBeanMap.getFieldDbAliasMap(); Map<String, Class<?>> fieldTypeMap = searchBeanMap.getFieldTypeMap(); Map<String, String> virtualParamMap = searchParam.getVirtualParamMap(); SearchSql searchSql = new SearchSql(); StringBuilder builder = new StringBuilder("select "); if (searchBeanMap.isDistinct()) { builder.append("distinct "); } int fieldCount = fieldList.size(); for (int i = 0; i < fieldCount; i++) { String field = fieldList.get(i); String dbField = fieldDbMap.get(field); String dbAlias = fieldDbAliasMap.get(field); builder.append(dbField).append(" ").append(dbAlias); if (i < fieldCount - 1) { builder.append(", "); } for (String key: searchBeanMap.getFieldVirtualParams(field)) { String sqlParam = virtualParamMap.get(key); searchSql.addListSqlParam(sqlParam); searchSql.addCountSqlParam(sqlParam); } searchSql.addAlias(dbAlias); } String fieldSelectSql = builder.toString(); builder = new StringBuilder(" from "); builder.append(searchBeanMap.getTalbes()); for (String key: searchBeanMap.getTableVirtualParams()) { String sqlParam = virtualParamMap.get(key); searchSql.addListSqlParam(sqlParam); searchSql.addCountSqlParam(sqlParam); } String joinCond = searchBeanMap.getJoinCond(); boolean hasJoinCond = joinCond != null && !"".equals(joinCond.trim()); List<FilterParam> filterParamList = searchParam.getFilterParamList(); if (hasJoinCond || filterParamList.size() > 0) { builder.append(" where "); if (hasJoinCond) { builder.append("(").append(joinCond).append(")"); for (String key: searchBeanMap.getJoinCondVirtualParams()) { String sqlParam = virtualParamMap.get(key); searchSql.addListSqlParam(sqlParam); searchSql.addCountSqlParam(sqlParam); } } } for (int i = 0; i < filterParamList.size(); i++) { if (i > 0 || hasJoinCond) { builder.append(" and "); } FilterParam filterParam = filterParamList.get(i); String fieldName = filterParam.getName(); List<Object> sqlParams = appendFilterConditionSql(builder, fieldTypeMap.get(fieldName), fieldDbMap.get(fieldName), filterParam); for (Object sqlParam : sqlParams) { searchSql.addListSqlParam(sqlParam); searchSql.addCountSqlParam(sqlParam); } } String groupBy = searchBeanMap.getGroupBy(); if (groupBy != null && !"".equals(groupBy.trim())) { builder.append(" group by " + groupBy); String fromWhereSql = builder.toString(); String tableAlias = generateTableAlias(fromWhereSql); if (searchBeanMap.isDistinct()) { String originalSql = fieldSelectSql + fromWhereSql; searchSql.setCountSqlString("select count(1) from (" + originalSql + ") " + tableAlias); } else { searchSql.setCountSqlString("select count(1) from (select count(1)" + fromWhereSql + ") " + tableAlias); } } else { if (searchBeanMap.isDistinct()) { String fromWhereSql = builder.toString(); String originalSql = fieldSelectSql + fromWhereSql; String tableAlias = generateTableAlias(fromWhereSql); searchSql.setCountSqlString("select count(1) from (" + originalSql + ") " + tableAlias); } else { searchSql.setCountSqlString("select count(1)" + builder.toString()); } } String sortDbAlias = fieldDbAliasMap.get(searchParam.getSort()); if (sortDbAlias != null) { builder.append(" order by ").append(sortDbAlias); String order = searchParam.getOrder(); if (order != null) { builder.append(" ").append(order); } } String fromWhereSql = builder.toString(); PaginateSql paginateSql = dialect.forPaginate(fieldSelectSql, fromWhereSql, searchParam.getMax(), searchParam.getOffset()); searchSql.setListSqlString(paginateSql.getSql()); searchSql.addListSqlParams(paginateSql.getParams()); return searchSql; } private void resolveVirtualParams(SearchBeanMap searchBeanMap) { VirtualSolution solution = resolveVirtualParams(searchBeanMap.getTalbes()); searchBeanMap.setTalbes(solution.getSqlSnippet()); searchBeanMap.setTableVirtualParams(solution.getVirtualParams()); solution = resolveVirtualParams(searchBeanMap.getJoinCond()); searchBeanMap.setJoinCond(solution.getSqlSnippet()); searchBeanMap.setJoinCondVirtualParams(solution.getVirtualParams()); Map<String, String> fieldDbMap = searchBeanMap.getFieldDbMap(); for (String field : searchBeanMap.getFieldList()) { solution = resolveVirtualParams(fieldDbMap.get(field)); fieldDbMap.put(field, solution.getSqlSnippet()); searchBeanMap.putFieldVirtualParam(field, solution.getVirtualParams()); } searchBeanMap.setVirtualResolved(true); } private VirtualSolution resolveVirtualParams(String sqlSnippet) { VirtualSolution solution = new VirtualSolution(); int index1 = sqlSnippet.indexOf(virtualParamPrefix); while (index1 > 0) { int index2 = sqlSnippet.indexOf(" ", index1); if (index2 < 0) index2 = sqlSnippet.indexOf("+", index1); if (index2 < 0) index2 = sqlSnippet.indexOf("-", index1); if (index2 < 0) index2 = sqlSnippet.indexOf("*", index1); if (index2 < 0) index2 = sqlSnippet.indexOf("/", index1); if (index2 < 0) index2 = sqlSnippet.indexOf("=", index1); if (index2 < 0) index2 = sqlSnippet.indexOf("!", index1); if (index2 < 0) index2 = sqlSnippet.indexOf(">", index1); if (index2 < 0) index2 = sqlSnippet.indexOf("<", index1); if (index2 < 0) index2 = sqlSnippet.indexOf(",", index1); if (index2 < 0) index2 = sqlSnippet.indexOf(")", index1); String virtualParam = null; if (index2 > 0) { virtualParam = sqlSnippet.substring(index1, index2); } else { virtualParam = sqlSnippet.substring(index1); } if (StrUtils.isBlank(virtualParam) || virtualParam.length() < 2 || virtualParam.contains(" ") || virtualParam.contains("+") || virtualParam.contains("-") || virtualParam.contains("*") || virtualParam.contains("/") || virtualParam.contains("=") || virtualParam.contains("!") || virtualParam.contains(">") || virtualParam.contains("<") || virtualParam.contains(",") || virtualParam.contains(")")) { throw new SearcherException("" + sqlSnippet); } sqlSnippet = sqlSnippet.replace(virtualParam, "?"); solution.addVirtualParam(virtualParam.substring(1)); index1 = sqlSnippet.indexOf(virtualParamPrefix); } solution.setSqlSnippet(sqlSnippet); return solution; } class VirtualSolution { String sqlSnippet; List<String> virtualParams = new ArrayList<>(); public String getSqlSnippet() { return sqlSnippet; } public void setSqlSnippet(String sqlSnippet) { this.sqlSnippet = sqlSnippet; } public List<String> getVirtualParams() { return virtualParams; } public void addVirtualParam(String virtualParam) { this.virtualParams.add(virtualParam); } } private String generateTableAlias(String originalSql) { String tableAlias = "tbl_a_"; while (originalSql.contains(tableAlias)) { tableAlias += "_"; } return tableAlias; } /** * @return */ private List<Object> appendFilterConditionSql(StringBuilder builder, Class<?> fieldType, String dbField, FilterParam filterParam) { String[] values = filterParam.getValues(); boolean ignoreCase = filterParam.isIgnoreCase(); Operator operator = filterParam.getOperator(); String firstRealValue = filterParam.firstNotNullValue(); if (ignoreCase) { for (int i = 0; i < values.length; i++) { String val = values[i]; if (val != null) { values[i] = val.toUpperCase(); } } if (firstRealValue != null) { firstRealValue = firstRealValue.toUpperCase(); } } if (operator != Operator.MultiValue) { if (ignoreCase) { dialect.toUpperCase(builder, dbField); } else if (Date.class.isAssignableFrom(fieldType) && firstRealValue != null) { appendDateFieldWithDialect(builder, dbField, firstRealValue); } else { builder.append(dbField); } } List<Object> params = new ArrayList<>(2); switch (operator) { case Include: builder.append(" like ?"); params.add("%" + firstRealValue + "%"); break; case Equal: builder.append(" = ?"); params.add(firstRealValue); break; case GreaterEqual: builder.append(" >= ?"); params.add(firstRealValue); break; case GreaterThan: builder.append(" > ?"); params.add(firstRealValue); break; case LessEqual: builder.append(" <= ?"); params.add(firstRealValue); break; case LessThan: builder.append(" < ?"); params.add(firstRealValue); break; case NotEqual: builder.append(" != ?"); params.add(firstRealValue); break; case Empty: builder.append(" is null"); break; case NotEmpty: builder.append(" is not null"); break; case StartWith: builder.append(" like ?"); params.add(firstRealValue + "%"); break; case EndWith: builder.append(" like ?"); params.add("%" + firstRealValue); break; case Between: boolean val1Null = false; boolean val2Null = false; if (values[0] == null || StrUtils.isBlank(values[0])) { val1Null = true; } if (values[1] == null || StrUtils.isBlank(values[1])) { val2Null = true; } if (!val1Null && !val2Null) { builder.append(" between ? and ? "); params.add(values[0]); params.add(values[1]); } else if (val1Null && !val2Null) { builder.append(" <= ? "); params.add(values[1]); } else if (!val1Null && val2Null) { builder.append(" >= ? "); params.add(values[0]); } break; case MultiValue: builder.append("("); for (int i = 0; i < values.length; i++) { String value = values[i]; if (value != null && "NULL".equals(value.toUpperCase())) { builder.append(dbField).append(" is null"); } else if (ignoreCase) { dialect.toUpperCase(builder, dbField); builder.append(" = ?"); params.add(value); } else if (Date.class.isAssignableFrom(fieldType)) { appendDateFieldWithDialect(builder, dbField, value); builder.append(" = ?"); params.add(value); } else { builder.append(dbField).append(" = ?"); params.add(value); } if (i < values.length - 1) { builder.append(" or "); } } builder.append(")"); break; } return params; } private void appendDateFieldWithDialect(StringBuilder builder, String dbField, String value) { if (DATE_PATTERN.matcher(value).matches()) { dialect.truncateToDateStr(builder, dbField); } else if (DATE_MINUTE_PATTERN.matcher(value).matches()) { dialect.truncateToDateMinuteStr(builder, dbField); } else if (DATE_SECOND_PATTERN.matcher(value).matches()) { dialect.truncateToDateSecondStr(builder, dbField); } else { builder.append(dbField); } } public void setDialect(Dialect dialect) { this.dialect = dialect; } public void setVirtualParamPrefix(String virtualParamPrefix) { this.virtualParamPrefix = virtualParamPrefix; } }
package com.continuuity.data.metadata; import com.continuuity.data.hbase.HBaseTestBase; import com.continuuity.data.operation.executor.OperationExecutor; import com.continuuity.data.runtime.DataFabricDistributedModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.name.Names; import org.junit.AfterClass; import org.junit.BeforeClass; public abstract class HBaseMetaDataStoreTest extends MetaDataStoreTest { @BeforeClass public static void setupOpex() throws Exception { HBaseTestBase.startHBase(); DataFabricDistributedModule module = new DataFabricDistributedModule(HBaseTestBase.getConfiguration()); Injector injector = Guice.createInjector(module); opex = injector.getInstance(Key.get( OperationExecutor.class, Names.named("DataFabricOperationExecutor"))); } @AfterClass public static void stopHBase() throws Exception { HBaseTestBase.stopHBase(); } }
package com.kancolle.server.service.member; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.kancolle.server.model.po.member.Member; import com.kancolle.server.utils.LoginUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class}) @RunWith(SpringJUnit4ClassRunner.class) @ContextHierarchy({ @ContextConfiguration(name = "parent", locations = "classpath:spring/spring-context.xml"), @ContextConfiguration(name = "child", locations = "classpath:spring/spring-mvc.xml") }) @Sql(value = {"classpath:sql/kancolle-dump.sql"}) public class MemberServiceTest { @Autowired private MemberService memberService; public void testAddMember(){ Member member = new Member(); memberService.addMember(member); } @Test public void testUpdateToken() { String memberId = "9007383"; Member member = memberService.getMember(memberId); String token = member.getToken(); memberService.updateMemberToken(memberId); member = memberService.getMember(memberId); Assert.assertFalse(token.equals(member.getToken())); } public void createNewMember(){ Member member = Member.builder() .nickName("sage417") .fleetName("") .maxChara(150) .maxSlotItem(500) .token(LoginUtils.generateMemberToken()) .build(); memberService.addMember(member); } }
package jx86.lang; /** * Represents an x86 machine instruction. * * @author David J. Pearce * */ public interface Instruction { /** * Represents a label in an instruction sequence which could be a branch * target, etc. * * @author David J. Pearce * */ public final class Label implements Instruction { public final String label; public final int alignment; public final boolean global; public Label(String label) { this.label = label; this.alignment = 1; this.global = false; } public Label(String label, int alignment, boolean global) { this.label = label; this.alignment = alignment; this.global = global; } public String toString() { return label + ":"; } } // Unit Operationrs public enum UnitOp { clc, // Clear Carry flag cdc, // Clear direction flag cli, // Clear interrupt flag cltd, // Convert Signed Long to Signed Double Long cqto, // Convert Signed quad to oct cmc, // Complement carry flag cbw, // Convert byte to word cwde, // Convert word to double word cwd, // Convert word to double word cwq, // Convert double word to quad word cpuid, // CPU identification enter, // Make stack frame hlt, // Halt invd, // Invalidate internal caches iret, // Interrupt return iretd, // Interrupt return (double word operand) lahf, // Load Status Flags into AH Register lar, // Load Access Rights Byte lds, // Load Far Pointer les, // Load Far Pointer lfs, // Load Far Pointer lgs, // Load Far Pointer lss, // Load Far Pointer leave, // destroy stack frame nop, // no operation popa, // Pop All General-Purpose Registers popf, // Pop into flags pusha, // Push All General-Purpose Registers pushf, // Push EFLAGS Register onto the Stack ret // return from function } /** * Represents a unit instruction (e.g. <code>ret</code>, <code>nop</code>, * <code>popf</code>, <code>clc</code>, etc) which has no operands. * * @author David J. Pearce * */ public final class Unit implements Instruction { public final UnitOp operation; /** * Create a unary instruction with a register operand. * * @param operation * Operation to perform */ public Unit(UnitOp operation) { this.operation = operation; } public String toString() { return operation.toString(); } } // Unary Operations public enum RegOp { dec, // Decrement by 1 inc, // Increment by 1 in, Int, // Call to interrupt invlpg, // Invalidate TLB entry div, // unsigned divide idiv, // signed division neg, // Two's Complement Negation not, // One's Complement Negation out, // Output to Port push, pop, rcl, // Rotate carry left rcr, // Rotate carry right rol, // Rotate left ror, // Rotate right sahf, // Store AH into Flags sal, // Shift Arithmetic Left sar, // Shift Arithmetic Right shl, // Shift Left shr, // Shift Right } /** * Represents a unary instruction (e.g. <code>push</code>, <code>pop</code>, * etc) with a register operand. For example: * * <pre> * pushq % eax * </pre> * * This pushes the contents of the <code>%eax</code> register on to the * stack. * * @author David J. Pearce * */ public final class Reg implements Instruction { public final RegOp operation; public final Register operand; /** * Create a unary instruction with a register operand. * * @param operation * Operation to perform * @param operand * Register operand */ public Reg(RegOp operation, Register operand) { this.operation = operation; this.operand = operand; } public String toString() { return operation.toString() + " " + Register.suffix(operand.width()) + " %" + operand; } } // Binary Operations public enum RegRegOp { mov, adc, // Add with Carry add, sub, mul, // unsigned multiplication imul, // signed multiplication div, cmp, cmpxchg, // compare and exchange cmpxchg8b, // compare and exchange 8 bytes comi, // compare scalar ordered double-precision floating point or, // Logical Inclusive OR and, // Logical AND xor, // Logical Exclusive OR xchg } /** * Represents a binary instruction (e.g. <code>mov</code>, <code>add</code>, * etc) with register operands. For example: * * <pre> * movl %eax, %ebx * </pre> * * This assigns the contents of the <code>%eax</code> register to the * <code>%ebx</code> register. * * @author David J. Pearce * */ public final class RegReg implements Instruction { public final RegRegOp operation; public final Register leftOperand; public final Register rightOperand; /** * Create a binary instruction with two register operands. The width of * registers must equal, or an exception is raised. * * @param operation * Operation to perform * @param leftOperand * Register operand on left-hand side * @param rightOperand * Register operand on right-hand side */ public RegReg(RegRegOp operation, Register leftOperand, Register rightOperand) { if(!Register.areCompatiable(leftOperand.width(),rightOperand.width())) { throw new IllegalArgumentException("Register operands must have identical width"); } this.operation = operation; this.leftOperand = leftOperand; this.rightOperand = rightOperand; } public String toString() { return operation.toString() + " " + Register.suffix(leftOperand.width(), rightOperand.width()) + " %" + leftOperand + ", %" + rightOperand; } } public enum ImmRegOp { mov, adc, // Add with Carry add, sub, mul, // unsigned multiplication imul, // signed multiplication cmp, cmpxchg, // compare and exchange cmpxchg8b, // compare and exchange 8 bytes or, // Logical Inclusive OR and, // Logical AND xor, // Logical Exclusive OR } /** * Represents a binary instruction (e.g. <code>mov</code>, <code>add</code>, * etc) with an immediate source operand and a register target operand. For * example: * * <pre> * movl $3, %eax * </pre> * * This assigns the constant 3 to the <code>%eax</code> register. * * @author David J. Pearce * */ public final class ImmReg implements Instruction { public final ImmRegOp operation; public final long leftOperand; public final Register rightOperand; /** * Create a binary instruction from one register to another. The * immediate operand must fit within the width of the target register, * or an exception is raised. * * @param leftOperand * Immediate operand on left-hand side. This is always * interpreted as a signed integer, regardless of width. For * example, if the <code>rhs</code> has byte width then the * accepted range for the immediate operand is -128 .. 127. * @param rightOperand * Register operand on right-hand side. */ public ImmReg(ImmRegOp operation, long leftOperand, Register rightOperand) { switch(rightOperand.width()) { case Byte: if(leftOperand < Byte.MIN_VALUE || leftOperand > Byte.MAX_VALUE) { throw new IllegalArgumentException("immediate operand does not fit into byte"); } break; case Word: if(leftOperand < Short.MIN_VALUE || leftOperand > Short.MAX_VALUE) { throw new IllegalArgumentException("immediate operand does not fit into word"); } break; case Long: if(leftOperand < Integer.MIN_VALUE || leftOperand > Integer.MAX_VALUE) { throw new IllegalArgumentException("immediate operand does not fit into double word"); } break; default: // this case is always true by construction } this.operation = operation; this.leftOperand = leftOperand; this.rightOperand = rightOperand; } public String toString() { return operation.toString() + Register.suffix(rightOperand.width()) + "$" + leftOperand + ", %" + rightOperand; } } // Ternary Operations public enum ImmIndRegOp { mov } /** * Create a ternary instruction with a register target operand and an * indirect source operand (whose address is determined from a register and * an immediate offset). For example: * * <pre> * movl -8(%ebp), %eax * </pre> * * This loads the value from the location 8 bytes below where the * <code>ebp</code> register currently points into the <code>%eax</code> * register. * * @author David J. Pearce * */ public final class ImmIndReg implements Instruction { public final ImmIndRegOp operation; public final long immediateOffset; public final Register baseOperand; public final Register targetOperand; /** * Create a binary instruction which operates on a register and an * indirect location (whose address is determined from a register and an * immediate offset). The immediate operand must fit within the width of * the target register, or an exception is raised. * * @param leftOperandImm * Immediate operand on left-hand side. This is always * interpreted as a signed integer, regardless of width. For * example, if the <code>rhs</code> has byte width then the * accepted range for the immediate operand is -128 .. 127. * @param leftOperandReg * Register operand used on left-hand side. * @param rightOperand * Register operand on right-hand side. */ public ImmIndReg(ImmIndRegOp operation, long leftOperandImm, Register leftOperandReg, Register rightOperand) { switch(rightOperand.width()) { case Byte: if(leftOperandImm < Byte.MIN_VALUE || leftOperandImm > Byte.MAX_VALUE) { throw new IllegalArgumentException("immediate operand does not fit into byte"); } break; case Word: if(leftOperandImm < Short.MIN_VALUE || leftOperandImm > Short.MAX_VALUE) { throw new IllegalArgumentException("immediate operand does not fit into word"); } break; case Long: if(leftOperandImm < Integer.MIN_VALUE || leftOperandImm > Integer.MAX_VALUE) { throw new IllegalArgumentException("immediate operand does not fit into double word"); } break; default: // this case is always true by construction } this.operation = operation; this.baseOperand = leftOperandReg; this.immediateOffset = leftOperandImm; this.targetOperand = rightOperand; } public String toString() { return operation.toString() + Register.suffix(targetOperand.width()) + immediateOffset + "(%" + baseOperand + "), %" + targetOperand; } } public enum RegImmIndOp { mov } /** * Create a ternary instruction with a register source operand and an * indirect target operand (whose address is determined from a register and * an immediate offset). For example: * * <pre> * movl %eax, -8(%ebp) * </pre> * * This loads the value from the <code>%eax</code> register into the * location 8 bytes below where the <code>ebp</code> register currently * points. * * @author David J. Pearce * */ public final class RegImmInd implements Instruction { public final RegImmIndOp operation; public final Register sourceOperand; public final long immediateOffset; public final Register baseOperand; /** * Create a binary instruction which operates on a register and an * indirect location (whose address is determined from a register and an * immediate offset). The immediate operand must fit within the width of * the target register, or an exception is raised. * */ public RegImmInd(RegImmIndOp operation, Register sourceOperand, long immediateOffset, Register baseOperand) { switch(sourceOperand.width()) { case Byte: if(immediateOffset < Byte.MIN_VALUE || immediateOffset > Byte.MAX_VALUE) { throw new IllegalArgumentException("immediate operand does not fit into byte"); } break; case Word: if(immediateOffset < Short.MIN_VALUE || immediateOffset > Short.MAX_VALUE) { throw new IllegalArgumentException("immediate operand does not fit into word"); } break; case Long: if(immediateOffset < Integer.MIN_VALUE || immediateOffset > Integer.MAX_VALUE) { throw new IllegalArgumentException("immediate operand does not fit into double word"); } break; default: // this case is always true by construction } this.operation = operation; this.sourceOperand = sourceOperand; this.baseOperand = baseOperand; this.immediateOffset = immediateOffset; } public String toString() { return operation.toString() + Register.suffix(sourceOperand.width()) + " %" + sourceOperand + ", " + immediateOffset + "(%" + baseOperand + ")"; } } // Quaternary Operations public enum IndRegImmRegOp { mov } /** * Create a quaternary instruction with a register source operand and an * indirect target operand (whose address is determined from a two registers * and a scaling). For example: * * <pre> * movl (%ebx,%esi,4),%eax * </pre> * * This loads the value from the location determined by %ebx + (%esi*4) into * the <code>%eax</code> register. Here, <code>%ebx</code> is the base * operand and <code>%esi</code> is the index operand. * * @author David J. Pearce * */ public final class IndRegImmReg implements Instruction { public final IndRegImmRegOp operation; public final Register baseOperand; public final Register indexOperand; public final long scaling; public final Register targetOperand; public IndRegImmReg(IndRegImmRegOp op, Register baseOperand, Register indexOperand, long scaling, Register targetOperand) { this.operation = op; this.baseOperand = baseOperand; this.indexOperand = indexOperand; this.scaling = scaling; this.targetOperand = targetOperand; } public String toString() { return operation.toString() + Register.suffix(targetOperand.width()) + " (%" + baseOperand + ",%" + indexOperand + "," + scaling + "), %" + targetOperand; } } public enum RegIndRegImmOp { mov } /** * Create a quaternary instruction with a register source operand and an * indirect target operand (whose address is determined from a two registers * and a scaling). For example: * * <pre> * movl %eax, (%ebx,%esi,4) * </pre> * * This loads the value from the <code>%eax</code> register into the * location determined by %ebx + (%esi*4). Here, <code>%ebx</code> is the * base operand and <code>%esi</code> is the index operand. * * @author David J. Pearce * */ public final class RegIndRegImm implements Instruction { public final RegIndRegImmOp operation; public final Register sourceOperand; public final Register baseOperand; public final Register indexOperand; public final long scaling; public RegIndRegImm(RegIndRegImmOp op, Register sourceOperand, Register baseOperand, Register indexOperand, long scaling) { this.operation = op; this.sourceOperand = sourceOperand; this.baseOperand = baseOperand; this.indexOperand = indexOperand; this.scaling = scaling; } public String toString() { return operation.toString() + Register.suffix(sourceOperand.width()) + " %" + sourceOperand + ", (%" + baseOperand + ",%" + indexOperand + "," + scaling + ")"; } } // Branch Operations public enum AddrOp { call, // Call procedure ja, // Jump if above (CF == 0 and ZF == 0) jae, // Jump if above or equal (CF == 0) jb, // Jump if below (CF == 1) jbe, // Jump if below or equal (CF == 1 or ZF == 1) jc, // Jump if carry (CF == 1) jcxz, // Jump if cx == 0 jecxz, // Jump if ecx == 0 je, // Jump if equal (ZF == 1) jg, // Jump if greater (ZF == 0 and SF==OF) jge, // Jump if greater or equal (SF==OF) jl, // Jump if less (SF<>OF) jle, // Jump if less or equal (ZF == 1 or SF<>OF) jna, // Jump if not above (CF == 1 or ZF == 1) jnae, // Jump if not above or equals (CF==1) jmp, // Unconditional Jump jnb, // Jump if not below (CF=0) jnbe, // Jump if not below or equal (CF=0 and ZF=0) jnc, // Jump if not carry (CF=0) jne, // Jump if not equal (ZF=0) jng, // Jump if not greater (ZF=1 or SF<>OF) jnge, // Jump if not greater or equal (SF<>OF) jnl, // Jump if not less (SF=OF) jnle, // Jump if not less or equal (ZF=0 and SF=OF) jno, // Jump if not overflow (OF=0) jnp, // Jump if not parity (PF=0) jns, // Jump if not sign (SF=0) jnz, // Jump if not zero (ZF=0) jo, // Jump if overflow (OF=1) jp, // Jump if parity (PF=1) jpe, // Jump if parity even (PF=1) jpo, // Jump if parity odd (PF=0) js, // Jump if sign (SF=1) jz, // Jump if zero (ZF = 1) loop, // Loop according r/e/cx loope, // Loop according r/e/cx loopz, // Loop according r/e/cx loopne, // Loop according r/e/cx loopnz, // Loop according r/e/cx } /** * Represents a unary instruction which uses a constant address operand * (represented with a label). For example, branching instructions (e.g. * <code>jmp</code>, <code>ja</code>, etc) with a label operand are * implemented in this way: * * <pre> * cmp %eax,%ebx * ja target * </pre> * * This compares the <code>eax</code> and <code>ebx</code> registesr and * branches to <code>target</code> if <code>eax</code> is above * <code>ebx</code>. * * @author David J. Pearce * */ public final class Addr implements Instruction { public final AddrOp operation; public final String operand; /** * Create a unary instruction with a register operand. * * @param operation * Operation to perform * @param operand * Register operand */ public Addr(AddrOp operation, String operand) { this.operation = operation; this.operand = operand; } public String toString() { return operation.toString() + " " + operand; } } public enum AddrRegOp { lea, // Load effective address mov, // Load effective address } /** * Represents a binary instruction which uses a constant address operand * (represented with a label) and a register operand. For example, the * <code>lea</code> instruction is implemented in this way: * * <pre> * lea $label,%eax * </pre> * * This loads the address of the given label into the <code>eax</code> * register. * * @author David J. Pearce * */ public final class AddrReg implements Instruction { public final AddrRegOp operation; public final String leftOperand; public final Register rightOperand; /** * Create a unary instruction with a register operand. * * @param operation * Operation to perform * @param operand * Register operand */ public AddrReg(AddrRegOp operation, String leftOperand, Register rightOperand) { this.operation = operation; this.leftOperand = leftOperand; this.rightOperand = rightOperand; } public String toString() { return operation.toString() + " " + leftOperand + ", %" + rightOperand; } } public enum AddrRegRegOp { lea, // Load effective address mov } /** * Represents a ternary instruction which uses an operand constructed from a * constant address and a register and a register operand. For example, the * <code>lea</code> instruction is implemented in this way: * * <pre> * lea $label,%eax * </pre> * * This loads the address of the given label into the <code>eax</code> * register. * * @author David J. Pearce * */ public final class AddrRegReg implements Instruction { public final AddrRegRegOp operation; public final String leftOperand_1; public final Register leftOperand_2; public final Register rightOperand; /** * Create a ternary instruction with an composite address/register * source operand, and a register target operand. * * @param operation * Operation to perform * @param operand * Register operand */ public AddrRegReg(AddrRegRegOp operation, String leftOperand_1, Register leftOperand_2, Register rightOperand) { this.operation = operation; this.leftOperand_1 = leftOperand_1; this.leftOperand_2 = leftOperand_2; this.rightOperand = rightOperand; } public String toString() { return operation.toString() + " " + leftOperand_1 + "(%" + leftOperand_2 + "), %" + rightOperand; } } }
package bot; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import org.junit.Test; /** * Test cases where we didn't lose but made a bad choice * * @author Ben Thurley * */ public class BadMovesTest { MoveEngine mover = new MoveEngine(); @Test public void testMove1() { Field field = new Field(7, 6); field.parseFromString( "0,0,0,2,0,0,0;0,0,1,2,0,0,0;2,0,2,1,2,0,1;1,0,1,1,1,0,2;2,0,1,2,1,0,2;2,1,1,1,2,0,2"); field.printField(); int move = mover.makeTurn(25, field, 1); System.out.println(move); assertEquals("Need to go in column 4 to set up the win", 4, move); } @Test public void testMove2() { Field field = new Field(7, 6); field.parseFromString( "0,0,0,2,0,0,0;0,0,0,1,0,0,0;0,1,0,1,2,0,0;0,2,2,1,1,1,0;2,2,1,2,1,2,0;2,2,1,1,2,1,0"); field.printField(); int move = mover.makeTurn(23, field, 1); System.out.println(move); assertEquals("Need to go in column 2 to win", 2, move); } @Test public void testMove3() { Field field = new Field(7, 6); field.parseFromString( "0,0,0,0,0,0,0;0,0,0,0,0,0,0;0,0,0,0,0,0,0;0,0,0,2,0,0,0;0,0,1,1,1,0,0;0,0,2,1,2,0,2"); field.printField(); int move = mover.makeTurn(9, field, 1); System.out.println(move); assertNotEquals("Avoid column 1 giving the win away", 1, move); assertNotEquals("Avoid column 5 giving the win away", 5, move); } }
package com.aerospike.client.query; import com.aerospike.client.Value; /** * Query statement parameters. */ public final class Statement { String namespace; String setName; String indexName; String[] binNames; Filter[] filters; String packageName; String functionName; Value[] functionArgs; int taskId; boolean returnData; /** * Set query namespace. */ public void setNamespace(String namespace) { this.namespace = namespace; } /** * Set optional query setname. */ public void setSetName(String setName) { this.setName = setName; } /** * Set optional query index name. If not set, the server * will determine the index from the filter's bin name. */ public void setIndexName(String indexName) { this.indexName = indexName; } /** * Set query bin names. */ public void setBinNames(String... binNames) { this.binNames = binNames; } /** * Set optional query filters. */ public void setFilters(Filter... filters) { this.filters = filters; } /** * Set optional query task id. */ public void setTaskId(int taskId) { this.taskId = taskId; } /** * Set Lua aggregation function parameters. This function will be called on both the server * and client for each selected item. * * @param packageName server package where user defined function resides * @param functionName aggregation function name * @param functionArgs arguments to pass to function name, if any */ void setAggregateFunction(String packageName, String functionName, Value[] functionArgs, boolean returnData) { this.packageName = packageName; this.functionName = functionName; this.functionArgs = functionArgs; this.returnData = returnData; } /** * Return aggregation file name. */ public String getPackageName() { return packageName; } /** * Return aggregation function name. */ public String getFunctionName() { return functionName; } /** * Return aggregation function arguments. */ public Value[] getFunctionArgs() { return functionArgs; } }
package jadx.gui.ui; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.DisplayMode; import java.awt.Font; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.ProgressMonitor; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeWillExpandListener; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.fife.ui.rsyntaxtextarea.Theme; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxArgs; import jadx.api.JavaClass; import jadx.api.JavaNode; import jadx.api.ResourceFile; import jadx.gui.JadxWrapper; import jadx.gui.jobs.BackgroundExecutor; import jadx.gui.jobs.BackgroundWorker; import jadx.gui.jobs.DecompileJob; import jadx.gui.jobs.IndexJob; import jadx.gui.settings.JadxProject; import jadx.gui.settings.JadxSettings; import jadx.gui.settings.JadxSettingsWindow; import jadx.gui.treemodel.ApkSignature; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JLoadableNode; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JPackage; import jadx.gui.treemodel.JResource; import jadx.gui.treemodel.JRoot; import jadx.gui.update.JadxUpdate; import jadx.gui.update.JadxUpdate.IUpdateCallback; import jadx.gui.update.data.Release; import jadx.gui.utils.CacheObject; import jadx.gui.utils.FontUtils; import jadx.gui.utils.JumpPosition; import jadx.gui.utils.Link; import jadx.gui.utils.NLS; import jadx.gui.utils.SystemInfo; import jadx.gui.utils.UiUtils; import static io.reactivex.internal.functions.Functions.EMPTY_RUNNABLE; import static javax.swing.KeyStroke.getKeyStroke; @SuppressWarnings("serial") public class MainWindow extends JFrame { private static final Logger LOG = LoggerFactory.getLogger(MainWindow.class); private static final String DEFAULT_TITLE = "jadx-gui"; private static final double BORDER_RATIO = 0.15; private static final double WINDOW_RATIO = 1 - BORDER_RATIO * 2; private static final double SPLIT_PANE_RESIZE_WEIGHT = 0.15; private static final ImageIcon ICON_OPEN = UiUtils.openIcon("folder"); private static final ImageIcon ICON_SAVE_ALL = UiUtils.openIcon("disk_multiple"); private static final ImageIcon ICON_EXPORT = UiUtils.openIcon("database_save"); private static final ImageIcon ICON_CLOSE = UiUtils.openIcon("cross"); private static final ImageIcon ICON_SYNC = UiUtils.openIcon("sync"); private static final ImageIcon ICON_FLAT_PKG = UiUtils.openIcon("empty_logical_package_obj"); private static final ImageIcon ICON_SEARCH = UiUtils.openIcon("wand"); private static final ImageIcon ICON_FIND = UiUtils.openIcon("magnifier"); private static final ImageIcon ICON_BACK = UiUtils.openIcon("icon_back"); private static final ImageIcon ICON_FORWARD = UiUtils.openIcon("icon_forward"); private static final ImageIcon ICON_PREF = UiUtils.openIcon("wrench"); private static final ImageIcon ICON_DEOBF = UiUtils.openIcon("lock_edit"); private static final ImageIcon ICON_LOG = UiUtils.openIcon("report"); private static final ImageIcon ICON_JADX = UiUtils.openIcon("jadx-logo"); private final transient JadxWrapper wrapper; private final transient JadxSettings settings; private final transient CacheObject cacheObject; private transient JadxProject project; private transient Action newProjectAction; private transient Action saveProjectAction; private JPanel mainPanel; private JSplitPane splitPane; private JTree tree; private DefaultTreeModel treeModel; private JRoot treeRoot; private TabbedPane tabbedPane; private HeapUsageBar heapUsageBar; private transient boolean treeReloading; private boolean isFlattenPackage; private JToggleButton flatPkgButton; private JCheckBoxMenuItem flatPkgMenuItem; private JToggleButton deobfToggleBtn; private JCheckBoxMenuItem deobfMenuItem; private transient Link updateLink; private transient ProgressPanel progressPane; private transient BackgroundWorker backgroundWorker; private transient BackgroundExecutor backgroundExecutor; private transient Theme editorTheme; public MainWindow(JadxSettings settings) { this.wrapper = new JadxWrapper(settings); this.settings = settings; this.cacheObject = new CacheObject(); resetCache(); FontUtils.registerBundledFonts(); initUI(); initMenuAndToolbar(); registerMouseNavigationButtons(); UiUtils.setWindowIcons(this); loadSettings(); checkForUpdate(); newProject(); this.backgroundExecutor = new BackgroundExecutor(this); } public void init() { pack(); setLocationAndPosition(); splitPane.setDividerLocation(settings.getTreeWidth()); heapUsageBar.setVisible(settings.isShowHeapUsageBar()); setVisible(true); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { closeWindow(); } }); processCommandLineArgs(); } private void processCommandLineArgs() { if (settings.getFiles().isEmpty()) { openFileOrProject(); } else { Path openFile = Paths.get(settings.getFiles().get(0)); open(openFile, this::handleSelectClassOption); } } private void handleSelectClassOption() { if (settings.getCmdSelectClass() != null) { JavaNode javaNode = wrapper.searchJavaClassByClassName(settings.getCmdSelectClass()); if (javaNode == null) { JOptionPane.showMessageDialog(this, NLS.str("msg.cmd_select_class_error", settings.getCmdSelectClass()), NLS.str("error_dialog.title"), JOptionPane.ERROR_MESSAGE); } else { JNode node = cacheObject.getNodeCache().makeFrom(javaNode); tabbedPane.codeJump(new JumpPosition(node.getRootClass(), node.getLine())); } } } private void checkForUpdate() { if (!settings.isCheckForUpdates()) { return; } JadxUpdate.check(new IUpdateCallback() { @Override public void onUpdate(Release r) { SwingUtilities.invokeLater(() -> { updateLink.setText(NLS.str("menu.update_label", r.getName())); updateLink.setVisible(true); }); } }); } public void openFileOrProject() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setAcceptAllFileFilterUsed(true); String[] exts = { JadxProject.PROJECT_EXTENSION, "apk", "dex", "jar", "class", "smali", "zip", "aar", "arsc" }; String description = "supported files: " + Arrays.toString(exts).replace('[', '(').replace(']', ')'); fileChooser.setFileFilter(new FileNameExtensionFilter(description, exts)); fileChooser.setToolTipText(NLS.str("file.open_action")); Path currentDirectory = settings.getLastOpenFilePath(); if (currentDirectory != null) { fileChooser.setCurrentDirectory(currentDirectory.toFile()); } int ret = fileChooser.showDialog(mainPanel, NLS.str("file.open_title")); if (ret == JFileChooser.APPROVE_OPTION) { settings.setLastOpenFilePath(fileChooser.getCurrentDirectory().toPath()); open(fileChooser.getSelectedFile().toPath()); } } private void newProject() { if (!ensureProjectIsSaved()) { return; } project = new JadxProject(settings); update(); clearTree(); } private void saveProject() { if (project.getProjectPath() == null) { saveProjectAs(); } else { project.save(); update(); } } private void saveProjectAs() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setAcceptAllFileFilterUsed(true); String[] exts = { JadxProject.PROJECT_EXTENSION }; String description = "supported files: " + Arrays.toString(exts).replace('[', '(').replace(']', ')'); fileChooser.setFileFilter(new FileNameExtensionFilter(description, exts)); fileChooser.setToolTipText(NLS.str("file.save_project")); Path currentDirectory = settings.getLastSaveProjectPath(); if (currentDirectory != null) { fileChooser.setCurrentDirectory(currentDirectory.toFile()); } int ret = fileChooser.showSaveDialog(mainPanel); if (ret == JFileChooser.APPROVE_OPTION) { settings.setLastSaveProjectPath(fileChooser.getCurrentDirectory().toPath()); Path path = fileChooser.getSelectedFile().toPath(); if (!path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(JadxProject.PROJECT_EXTENSION)) { path = path.resolveSibling(path.getFileName() + "." + JadxProject.PROJECT_EXTENSION); } if (Files.exists(path)) { int res = JOptionPane.showConfirmDialog( this, NLS.str("confirm.save_as_message", path.getFileName()), NLS.str("confirm.save_as_title"), JOptionPane.YES_NO_OPTION); if (res == JOptionPane.NO_OPTION) { return; } } project.saveAs(path); update(); } } void open(Path path) { open(path, EMPTY_RUNNABLE); } void open(Path path, Runnable onFinish) { if (path.getFileName().toString().toLowerCase(Locale.ROOT) .endsWith(JadxProject.PROJECT_EXTENSION)) { openProject(path); onFinish.run(); } else { project.setFilePath(path); clearTree(); backgroundExecutor.execute(NLS.str("progress.load"), () -> wrapper.openFile(path.toFile()), () -> { deobfToggleBtn.setSelected(settings.isDeobfuscationOn()); initTree(); update(); runBackgroundJobs(); onFinish.run(); }); } } private boolean ensureProjectIsSaved() { if (project != null && !project.isSaved() && !project.isInitial()) { int res = JOptionPane.showConfirmDialog( this, NLS.str("confirm.not_saved_message"), NLS.str("confirm.not_saved_title"), JOptionPane.YES_NO_CANCEL_OPTION); if (res == JOptionPane.CANCEL_OPTION) { return false; } if (res == JOptionPane.YES_OPTION) { project.save(); } } return true; } private void openProject(Path path) { if (!ensureProjectIsSaved()) { return; } project = JadxProject.from(path, settings); if (project == null) { JOptionPane.showMessageDialog( this, NLS.str("msg.project_error"), NLS.str("msg.project_error_title"), JOptionPane.INFORMATION_MESSAGE); return; } update(); settings.addRecentProject(path); Path filePath = project.getFilePath(); if (filePath == null) { clearTree(); } else { open(filePath); } } private void update() { newProjectAction.setEnabled(!project.isInitial()); saveProjectAction.setEnabled(!project.isSaved()); Path projectPath = project.getProjectPath(); String pathString; if (projectPath == null) { pathString = ""; } else { pathString = " [" + projectPath.getParent().toAbsolutePath() + ']'; } setTitle((project.isSaved() ? "" : '*') + project.getName() + pathString + " - " + DEFAULT_TITLE); } protected void resetCache() { cacheObject.reset(); // TODO: decompilation freezes sometime with several threads int threadsCount = settings.getThreadsCount(); cacheObject.setDecompileJob(new DecompileJob(wrapper, threadsCount)); cacheObject.setIndexJob(new IndexJob(wrapper, cacheObject, threadsCount)); } private synchronized void runBackgroundJobs() { cancelBackgroundJobs(); backgroundWorker = new BackgroundWorker(cacheObject, progressPane); if (settings.isAutoStartJobs()) { new Timer().schedule(new TimerTask() { @Override public void run() { backgroundWorker.exec(); } }, 1000); } } public synchronized void cancelBackgroundJobs() { backgroundExecutor.cancelAll(); if (backgroundWorker != null) { backgroundWorker.stop(); backgroundWorker = new BackgroundWorker(cacheObject, progressPane); resetCache(); } } public void reOpenFile() { File openedFile = wrapper.getOpenFile(); Map<String, Integer> openTabs = storeOpenTabs(); if (openedFile != null) { open(openedFile.toPath(), () -> restoreOpenTabs(openTabs)); } } @NotNull private Map<String, Integer> storeOpenTabs() { Map<String, Integer> openTabs = new LinkedHashMap<>(); for (Map.Entry<JNode, ContentPanel> entry : tabbedPane.getOpenTabs().entrySet()) { JavaNode javaNode = entry.getKey().getJavaNode(); String classRealName = ""; if (javaNode instanceof JavaClass) { JavaClass javaClass = (JavaClass) javaNode; classRealName = javaClass.getRawName(); } @Nullable JumpPosition position = entry.getValue().getTabbedPane().getCurrentPosition(); int line = 0; if (position != null) { line = position.getLine(); } openTabs.put(classRealName, line); } return openTabs; } private void restoreOpenTabs(Map<String, Integer> openTabs) { for (Map.Entry<String, Integer> entry : openTabs.entrySet()) { String classRealName = entry.getKey(); int position = entry.getValue(); @Nullable JavaClass newClass = wrapper.searchJavaClassByRawName(classRealName); if (newClass == null) { continue; } JNode newNode = cacheObject.getNodeCache().makeFrom(newClass); tabbedPane.codeJump(new JumpPosition(newNode, position)); } } private void saveAll(boolean export) { JadxArgs decompilerArgs = wrapper.getArgs(); if ((!decompilerArgs.isFsCaseSensitive() && !decompilerArgs.isRenameCaseSensitive()) || !decompilerArgs.isRenameValid() || !decompilerArgs.isRenamePrintable()) { JOptionPane.showMessageDialog( this, NLS.str("msg.rename_disabled", settings.getLangLocale()), NLS.str("msg.rename_disabled_title", settings.getLangLocale()), JOptionPane.INFORMATION_MESSAGE); } JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setToolTipText(NLS.str("file.save_all_msg")); Path currentDirectory = settings.getLastSaveFilePath(); if (currentDirectory != null) { fileChooser.setCurrentDirectory(currentDirectory.toFile()); } int ret = fileChooser.showSaveDialog(mainPanel); if (ret == JFileChooser.APPROVE_OPTION) { decompilerArgs.setExportAsGradleProject(export); if (export) { decompilerArgs.setSkipSources(false); decompilerArgs.setSkipResources(false); } else { decompilerArgs.setSkipSources(settings.isSkipSources()); decompilerArgs.setSkipResources(settings.isSkipResources()); } settings.setLastSaveFilePath(fileChooser.getCurrentDirectory().toPath()); ProgressMonitor progressMonitor = new ProgressMonitor(mainPanel, NLS.str("msg.saving_sources"), "", 0, 100); progressMonitor.setMillisToPopup(0); wrapper.saveAll(fileChooser.getSelectedFile(), progressMonitor); } } private void initTree() { treeRoot = new JRoot(wrapper); treeRoot.setFlatPackages(isFlattenPackage); treeModel.setRoot(treeRoot); reloadTree(); } private void clearTree() { tabbedPane.closeAllTabs(); resetCache(); treeRoot = null; treeModel.setRoot(treeRoot); treeModel.reload(); } private void reloadTree() { treeReloading = true; treeModel.reload(); List<String[]> treeExpansions = project.getTreeExpansions(); if (!treeExpansions.isEmpty()) { expand(treeRoot, treeExpansions); } else { tree.expandRow(1); } treeReloading = false; } private void expand(TreeNode node, List<String[]> treeExpansions) { TreeNode[] pathNodes = treeModel.getPathToRoot(node); if (pathNodes == null) { return; } TreePath path = new TreePath(pathNodes); for (String[] expansion : treeExpansions) { if (Arrays.equals(expansion, getPathExpansion(path))) { tree.expandPath(path); break; } } for (int i = node.getChildCount() - 1; i >= 0; i expand(node.getChildAt(i), treeExpansions); } } private void toggleFlattenPackage() { setFlattenPackage(!isFlattenPackage); } private void setFlattenPackage(boolean value) { isFlattenPackage = value; settings.setFlattenPackage(isFlattenPackage); flatPkgButton.setSelected(isFlattenPackage); flatPkgMenuItem.setState(isFlattenPackage); Object root = treeModel.getRoot(); if (root instanceof JRoot) { JRoot treeRoot = (JRoot) root; treeRoot.setFlatPackages(isFlattenPackage); reloadTree(); } } private void toggleDeobfuscation() { boolean deobfOn = !settings.isDeobfuscationOn(); settings.setDeobfuscationOn(deobfOn); settings.sync(); deobfToggleBtn.setSelected(deobfOn); deobfMenuItem.setState(deobfOn); reOpenFile(); } private void nodeClickAction(@Nullable Object obj) { try { if (obj == null) { return; } if (obj instanceof JResource) { JResource res = (JResource) obj; ResourceFile resFile = res.getResFile(); if (resFile != null && JResource.isSupportedForView(resFile.getType())) { tabbedPane.showResource(res); } } else if (obj instanceof ApkSignature) { tabbedPane.showSimpleNode((JNode) obj); } else if (obj instanceof JNode) { JNode node = (JNode) obj; JClass cls = node.getRootClass(); if (cls != null) { tabbedPane.codeJump(new JumpPosition(cls, node.getLine())); } } } catch (Exception e) { LOG.error("Content loading error", e); } } private void treeRightClickAction(MouseEvent e) { Object obj = getJNodeUnderMouse(e); if (obj instanceof JPackage) { JPackagePopUp menu = new JPackagePopUp((JPackage) obj); menu.show(e.getComponent(), e.getX(), e.getY()); } } @Nullable private JNode getJNodeUnderMouse(MouseEvent mouseEvent) { TreePath path = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY()); if (path != null) { Object obj = path.getLastPathComponent(); if (obj instanceof JNode) { return (JNode) obj; } } return null; } private void syncWithEditor() { ContentPanel selectedContentPanel = tabbedPane.getSelectedCodePanel(); if (selectedContentPanel == null) { return; } JNode node = selectedContentPanel.getNode(); if (node.getParent() == null && treeRoot != null) { // node not register in tree node = treeRoot.searchClassInTree(node); if (node == null) { LOG.error("Class not found in tree"); return; } } TreeNode[] pathNodes = treeModel.getPathToRoot(node); if (pathNodes == null) { return; } TreePath path = new TreePath(pathNodes); tree.setSelectionPath(path); tree.makeVisible(path); tree.scrollPathToVisible(path); tree.requestFocus(); } private void initMenuAndToolbar() { Action openAction = new AbstractAction(NLS.str("file.open_action"), ICON_OPEN) { @Override public void actionPerformed(ActionEvent e) { openFileOrProject(); } }; openAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("file.open_action")); openAction.putValue(Action.ACCELERATOR_KEY, getKeyStroke(KeyEvent.VK_O, UiUtils.ctrlButton())); newProjectAction = new AbstractAction(NLS.str("file.new_project")) { @Override public void actionPerformed(ActionEvent e) { newProject(); } }; newProjectAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("file.new_project")); saveProjectAction = new AbstractAction(NLS.str("file.save_project")) { @Override public void actionPerformed(ActionEvent e) { saveProject(); } }; saveProjectAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("file.save_project")); Action saveProjectAsAction = new AbstractAction(NLS.str("file.save_project_as")) { @Override public void actionPerformed(ActionEvent e) { saveProjectAs(); } }; saveProjectAsAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("file.save_project_as")); Action saveAllAction = new AbstractAction(NLS.str("file.save_all"), ICON_SAVE_ALL) { @Override public void actionPerformed(ActionEvent e) { saveAll(false); } }; saveAllAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("file.save_all")); saveAllAction.putValue(Action.ACCELERATOR_KEY, getKeyStroke(KeyEvent.VK_S, UiUtils.ctrlButton())); Action exportAction = new AbstractAction(NLS.str("file.export_gradle"), ICON_EXPORT) { @Override public void actionPerformed(ActionEvent e) { saveAll(true); } }; exportAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("file.export_gradle")); exportAction.putValue(Action.ACCELERATOR_KEY, getKeyStroke(KeyEvent.VK_E, UiUtils.ctrlButton())); JMenu recentProjects = new JMenu(NLS.str("menu.recent_projects")); recentProjects.addMenuListener(new RecentProjectsMenuListener(recentProjects)); Action prefsAction = new AbstractAction(NLS.str("menu.preferences"), ICON_PREF) { @Override public void actionPerformed(ActionEvent e) { new JadxSettingsWindow(MainWindow.this, settings).setVisible(true); } }; prefsAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("menu.preferences")); prefsAction.putValue(Action.ACCELERATOR_KEY, getKeyStroke(KeyEvent.VK_P, UiUtils.ctrlButton() | KeyEvent.SHIFT_DOWN_MASK)); Action exitAction = new AbstractAction(NLS.str("file.exit"), ICON_CLOSE) { @Override public void actionPerformed(ActionEvent e) { closeWindow(); } }; isFlattenPackage = settings.isFlattenPackage(); flatPkgMenuItem = new JCheckBoxMenuItem(NLS.str("menu.flatten"), ICON_FLAT_PKG); flatPkgMenuItem.setState(isFlattenPackage); JCheckBoxMenuItem heapUsageBarMenuItem = new JCheckBoxMenuItem(NLS.str("menu.heapUsageBar")); heapUsageBarMenuItem.setState(settings.isShowHeapUsageBar()); heapUsageBarMenuItem.addActionListener(event -> { settings.setShowHeapUsageBar(!settings.isShowHeapUsageBar()); heapUsageBar.setVisible(settings.isShowHeapUsageBar()); }); Action syncAction = new AbstractAction(NLS.str("menu.sync"), ICON_SYNC) { @Override public void actionPerformed(ActionEvent e) { syncWithEditor(); } }; syncAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("menu.sync")); syncAction.putValue(Action.ACCELERATOR_KEY, getKeyStroke(KeyEvent.VK_T, UiUtils.ctrlButton())); Action textSearchAction = new AbstractAction(NLS.str("menu.text_search"), ICON_SEARCH) { @Override public void actionPerformed(ActionEvent e) { new SearchDialog(MainWindow.this, true).setVisible(true); } }; textSearchAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("menu.text_search")); textSearchAction.putValue(Action.ACCELERATOR_KEY, getKeyStroke(KeyEvent.VK_F, UiUtils.ctrlButton() | KeyEvent.SHIFT_DOWN_MASK)); Action clsSearchAction = new AbstractAction(NLS.str("menu.class_search"), ICON_FIND) { @Override public void actionPerformed(ActionEvent e) { new SearchDialog(MainWindow.this, false).setVisible(true); } }; clsSearchAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("menu.class_search")); clsSearchAction.putValue(Action.ACCELERATOR_KEY, getKeyStroke(KeyEvent.VK_N, UiUtils.ctrlButton())); Action deobfAction = new AbstractAction(NLS.str("menu.deobfuscation"), ICON_DEOBF) { @Override public void actionPerformed(ActionEvent e) { toggleDeobfuscation(); } }; deobfAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("preferences.deobfuscation")); deobfAction.putValue(Action.ACCELERATOR_KEY, getKeyStroke(KeyEvent.VK_D, UiUtils.ctrlButton() | KeyEvent.ALT_DOWN_MASK)); deobfToggleBtn = new JToggleButton(deobfAction); deobfToggleBtn.setSelected(settings.isDeobfuscationOn()); deobfToggleBtn.setText(""); deobfMenuItem = new JCheckBoxMenuItem(deobfAction); deobfMenuItem.setState(settings.isDeobfuscationOn()); Action logAction = new AbstractAction(NLS.str("menu.log"), ICON_LOG) { @Override public void actionPerformed(ActionEvent e) { new LogViewer(MainWindow.this).setVisible(true); } }; logAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("menu.log")); logAction.putValue(Action.ACCELERATOR_KEY, getKeyStroke(KeyEvent.VK_L, UiUtils.ctrlButton() | KeyEvent.SHIFT_DOWN_MASK)); Action aboutAction = new AbstractAction(NLS.str("menu.about"), ICON_JADX) { @Override public void actionPerformed(ActionEvent e) { new AboutDialog().setVisible(true); } }; Action backAction = new AbstractAction(NLS.str("nav.back"), ICON_BACK) { @Override public void actionPerformed(ActionEvent e) { tabbedPane.navBack(); } }; backAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("nav.back")); backAction.putValue(Action.ACCELERATOR_KEY, getKeyStroke(KeyEvent.VK_LEFT, UiUtils.ctrlButton() | KeyEvent.ALT_DOWN_MASK)); Action forwardAction = new AbstractAction(NLS.str("nav.forward"), ICON_FORWARD) { @Override public void actionPerformed(ActionEvent e) { tabbedPane.navForward(); } }; forwardAction.putValue(Action.SHORT_DESCRIPTION, NLS.str("nav.forward")); forwardAction.putValue(Action.ACCELERATOR_KEY, getKeyStroke(KeyEvent.VK_RIGHT, UiUtils.ctrlButton() | KeyEvent.ALT_DOWN_MASK)); JMenu file = new JMenu(NLS.str("menu.file")); file.setMnemonic(KeyEvent.VK_F); file.add(openAction); file.addSeparator(); file.add(newProjectAction); file.add(saveProjectAction); file.add(saveProjectAsAction); file.addSeparator(); file.add(saveAllAction); file.add(exportAction); file.addSeparator(); file.add(recentProjects); file.addSeparator(); file.add(prefsAction); file.addSeparator(); file.add(exitAction); JMenu view = new JMenu(NLS.str("menu.view")); view.setMnemonic(KeyEvent.VK_V); view.add(flatPkgMenuItem); view.add(syncAction); view.add(heapUsageBarMenuItem); JMenu nav = new JMenu(NLS.str("menu.navigation")); nav.setMnemonic(KeyEvent.VK_N); nav.add(textSearchAction); nav.add(clsSearchAction); nav.addSeparator(); nav.add(backAction); nav.add(forwardAction); JMenu tools = new JMenu(NLS.str("menu.tools")); tools.setMnemonic(KeyEvent.VK_T); tools.add(deobfMenuItem); tools.add(logAction); JMenu help = new JMenu(NLS.str("menu.help")); help.setMnemonic(KeyEvent.VK_H); help.add(aboutAction); JMenuBar menuBar = new JMenuBar(); menuBar.add(file); menuBar.add(view); menuBar.add(nav); menuBar.add(tools); menuBar.add(help); setJMenuBar(menuBar); flatPkgButton = new JToggleButton(ICON_FLAT_PKG); flatPkgButton.setSelected(isFlattenPackage); ActionListener flatPkgAction = e -> toggleFlattenPackage(); flatPkgMenuItem.addActionListener(flatPkgAction); flatPkgButton.addActionListener(flatPkgAction); flatPkgButton.setToolTipText(NLS.str("menu.flatten")); updateLink = new Link("", JadxUpdate.JADX_RELEASES_URL); updateLink.setVisible(false); JToolBar toolbar = new JToolBar(); toolbar.setFloatable(false); toolbar.add(openAction); toolbar.add(saveAllAction); toolbar.add(exportAction); toolbar.addSeparator(); toolbar.add(syncAction); toolbar.add(flatPkgButton); toolbar.addSeparator(); toolbar.add(textSearchAction); toolbar.add(clsSearchAction); toolbar.addSeparator(); toolbar.add(backAction); toolbar.add(forwardAction); toolbar.addSeparator(); toolbar.add(deobfToggleBtn); toolbar.addSeparator(); toolbar.add(logAction); toolbar.addSeparator(); toolbar.add(prefsAction); toolbar.addSeparator(); toolbar.add(Box.createHorizontalGlue()); toolbar.add(updateLink); mainPanel.add(toolbar, BorderLayout.NORTH); } private void initUI() { setMinimumSize(new Dimension(200, 150)); mainPanel = new JPanel(new BorderLayout()); splitPane = new JSplitPane(); splitPane.setResizeWeight(SPLIT_PANE_RESIZE_WEIGHT); mainPanel.add(splitPane); DefaultMutableTreeNode treeRootNode = new DefaultMutableTreeNode(NLS.str("msg.open_file")); treeModel = new DefaultTreeModel(treeRootNode); tree = new JTree(treeModel); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { nodeClickAction(getJNodeUnderMouse(e)); } else if (SwingUtilities.isRightMouseButton(e)) { treeRightClickAction(e); } } }); tree.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { nodeClickAction(tree.getLastSelectedPathComponent()); } } }); tree.setCellRenderer(new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean isLeaf, int row, boolean focused) { Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, isLeaf, row, focused); if (value instanceof JNode) { setIcon(((JNode) value).getIcon()); } if (value instanceof JPackage) { setEnabled(((JPackage) value).isEnabled()); } return c; } }); tree.addTreeWillExpandListener(new TreeWillExpandListener() { @Override public void treeWillExpand(TreeExpansionEvent event) { TreePath path = event.getPath(); Object node = path.getLastPathComponent(); if (node instanceof JLoadableNode) { ((JLoadableNode) node).loadNode(); } if (!treeReloading) { project.addTreeExpansion(getPathExpansion(event.getPath())); update(); } } @Override public void treeWillCollapse(TreeExpansionEvent event) { if (!treeReloading) { project.removeTreeExpansion(getPathExpansion(event.getPath())); update(); } } }); progressPane = new ProgressPanel(this, true); JPanel leftPane = new JPanel(new BorderLayout()); JScrollPane treeScrollPane = new JScrollPane(tree); treeScrollPane.setMinimumSize(new Dimension(100, 150)); leftPane.add(treeScrollPane, BorderLayout.CENTER); leftPane.add(progressPane, BorderLayout.PAGE_END); splitPane.setLeftComponent(leftPane); tabbedPane = new TabbedPane(this); tabbedPane.setMinimumSize(new Dimension(150, 150)); splitPane.setRightComponent(tabbedPane); new DropTarget(this, DnDConstants.ACTION_COPY, new MainDropTarget(this)); heapUsageBar = new HeapUsageBar(); mainPanel.add(heapUsageBar, BorderLayout.SOUTH); setContentPane(mainPanel); setTitle(DEFAULT_TITLE); } private void registerMouseNavigationButtons() { Toolkit toolkit = Toolkit.getDefaultToolkit(); toolkit.addAWTEventListener(event -> { if (event instanceof MouseEvent) { MouseEvent mouseEvent = (MouseEvent) event; if (mouseEvent.getID() == MouseEvent.MOUSE_PRESSED) { int rawButton = mouseEvent.getButton(); if (rawButton <= 3) { return; } int button = remapMouseButton(rawButton); switch (button) { case 4: tabbedPane.navBack(); break; case 5: tabbedPane.navForward(); break; } } } }, AWTEvent.MOUSE_EVENT_MASK); } private static int remapMouseButton(int rawButton) { if (SystemInfo.IS_LINUX) { if (rawButton == 6) { return 4; } if (rawButton == 7) { return 5; } } return rawButton; } private static String[] getPathExpansion(TreePath path) { List<String> pathList = new ArrayList<>(); while (path != null) { Object node = path.getLastPathComponent(); String name; if (node instanceof JClass) { name = ((JClass) node).getCls().getClassNode().getClassInfo().getFullName(); } else { name = node.toString(); } pathList.add(name); path = path.getParentPath(); } return pathList.toArray(new String[pathList.size()]); } public static void getExpandedPaths(JTree tree, TreePath path, List<TreePath> list) { if (tree.isExpanded(path)) { list.add(path); TreeNode node = (TreeNode) path.getLastPathComponent(); for (int i = node.getChildCount() - 1; i >= 0; i TreeNode n = node.getChildAt(i); TreePath child = path.pathByAddingChild(n); getExpandedPaths(tree, child, list); } } } public void setLocationAndPosition() { if (settings.loadWindowPos(this)) { return; } GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); DisplayMode mode = gd.getDisplayMode(); int w = mode.getWidth(); int h = mode.getHeight(); setBounds((int) (w * BORDER_RATIO), (int) (h * BORDER_RATIO), (int) (w * WINDOW_RATIO), (int) (h * WINDOW_RATIO)); setLocationRelativeTo(null); } private void setEditorTheme(String editorThemePath) { try (InputStream is = getClass().getResourceAsStream(editorThemePath)) { editorTheme = Theme.load(is); } catch (Exception e) { LOG.error("Can't load editor theme from classpath: {}", editorThemePath); try (InputStream is = new FileInputStream(editorThemePath)) { editorTheme = Theme.load(is); } catch (Exception ex) { LOG.error("Can't load editor theme from file: {}", editorThemePath); } } } public Theme getEditorTheme() { return editorTheme; } public void loadSettings() { Font font = settings.getFont(); Font largerFont = font.deriveFont(font.getSize() + 2.f); setFont(largerFont); setEditorTheme(settings.getEditorThemePath()); tree.setFont(largerFont); tree.setRowHeight(-1); tabbedPane.loadSettings(); } private void closeWindow() { if (!ensureProjectIsSaved()) { return; } settings.setTreeWidth(splitPane.getDividerLocation()); settings.saveWindowPos(this); settings.setMainWindowExtendedState(getExtendedState()); cancelBackgroundJobs(); dispose(); System.exit(0); } public JadxWrapper getWrapper() { return wrapper; } public TabbedPane getTabbedPane() { return tabbedPane; } public JadxSettings getSettings() { return settings; } public CacheObject getCacheObject() { return cacheObject; } public BackgroundWorker getBackgroundWorker() { return backgroundWorker; } public ProgressPanel getProgressPane() { return progressPane; } private class RecentProjectsMenuListener implements MenuListener { private final JMenu recentProjects; public RecentProjectsMenuListener(JMenu recentProjects) { this.recentProjects = recentProjects; } @Override public void menuSelected(MenuEvent menuEvent) { recentProjects.removeAll(); File openFile = wrapper.getOpenFile(); Path currentPath = openFile == null ? null : openFile.toPath(); for (Path path : settings.getRecentProjects()) { if (!path.equals(currentPath)) { JMenuItem menuItem = new JMenuItem(path.toAbsolutePath().toString()); recentProjects.add(menuItem); menuItem.addActionListener(e -> open(path)); } } if (recentProjects.getItemCount() == 0) { recentProjects.add(new JMenuItem(NLS.str("menu.no_recent_projects"))); } } @Override public void menuDeselected(MenuEvent e) { } @Override public void menuCanceled(MenuEvent e) { } } private class JPackagePopUp extends JPopupMenu { JMenuItem excludeItem = new JCheckBoxMenuItem(NLS.str("popup.exclude")); public JPackagePopUp(JPackage pkg) { excludeItem.setSelected(!pkg.isEnabled()); add(excludeItem); excludeItem.addItemListener(e -> { String fullName = pkg.getFullName(); if (excludeItem.isSelected()) { wrapper.addExcludedPackage(fullName); } else { wrapper.removeExcludedPackage(fullName); } reOpenFile(); }); } } }
package org.menacheri; import static org.junit.Assert.assertEquals; import java.net.InetSocketAddress; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.junit.Test; import org.menacheri.util.NettyUtils; /** * Unit test for simple App. */ public class AppTest { @Test public void nettyUtilStringWriteRead() { String msg = "Hello World!"; ChannelBuffer stringBuffer = NettyUtils.writeString(msg); String reply = NettyUtils.readString(stringBuffer); assertEquals(msg, reply); } @Test public void nettyUtilMultiStringWriteRead() { String hello = "Hello "; String world = "World!"; ChannelBuffer stringBuffer1 = NettyUtils.writeString(hello); ChannelBuffer stringBuffer2 = NettyUtils.writeString(world); ChannelBuffer stringBuffer = ChannelBuffers.wrappedBuffer(stringBuffer1,stringBuffer2); String helloReply = NettyUtils.readString(stringBuffer); String worldReply = NettyUtils.readString(stringBuffer); assertEquals(hello, helloReply); assertEquals(worldReply, world); } @Test public void nettyUtilVarArgsStringWriteRead() { String hello = "Hello "; String world = "World!"; ChannelBuffer stringBuffer = NettyUtils.writeStrings(hello,world); String helloReply = NettyUtils.readString(stringBuffer); String worldReply = NettyUtils.readString(stringBuffer); assertEquals(hello, helloReply); assertEquals(worldReply, world); } @Test public void readWriteSocketAddress() { InetSocketAddress socketAddress = new InetSocketAddress("localhost", 18090); ChannelBuffer buffer = NettyUtils.writeSocketAddress(socketAddress); InetSocketAddress readAddress = NettyUtils.readSocketAddress(buffer); assertEquals(socketAddress,readAddress); } }
package joliex.util; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Vector; import jolie.net.CommMessage; import jolie.runtime.FaultException; import jolie.runtime.JavaService; import jolie.runtime.Value; import jolie.runtime.ValueVector; public class ExecService extends JavaService { public CommMessage exec( CommMessage request ) throws FaultException { Vector< String > command = new Vector< String >(); String[] str = request.value().strValue().split( " " ); for( int i = 0; i < str.length; i++ ) { command.add( str[i] ); } for( Value v : request.value().getChildren( "args" ) ) { command.add( v.strValue() ); } //String input = null; ProcessBuilder builder = new ProcessBuilder( command ); //builder.redirectErrorStream( true ); try { Value response = Value.create(); Process p = builder.start(); ValueVector waitFor = request.value().children().get( "waitFor" ); if ( waitFor == null || waitFor.first().intValue() > 0 ) { int exitCode = p.waitFor(); response.getNewChild( "exitCode" ).setValue( exitCode ); int len = p.getInputStream().available(); if ( len > 0 ) { char[] buffer = new char[ len ]; BufferedReader reader = new BufferedReader( new InputStreamReader( p.getInputStream() ) ); reader.read( buffer, 0, len ); response.setValue( new String( buffer ) ); } } return CommMessage.createResponse( request, response ); } catch( Exception e ) { throw new FaultException( e ); } } }
package GcAlgorithm; import java.lang.ref.WeakReference; public class WeakRef { public static class User { public User(int id, String name) { this.id=id; this.name=name; } public int id; public String name; } public static void main(String[] args) { User u=new User(1,"chenyang"); WeakReference<User> userWeakRef=new WeakReference<User>(u); u=null; System.out.println(userWeakRef.get()); System.gc(); System.out.println("After GC:"); System.out.println(userWeakRef.get()); } }
package tp.pr5.Resources; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.util.Scanner; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import tp.pr5.logic.Board; import tp.pr5.logic.Counter; import tp.pr5.logic.Game; import tp.pr5.logic.GravityMove; import tp.pr5.logic.InvalidMove; import tp.pr5.logic.Move; import tp.pr5.logic.ReversiMove; import tp.pr5.logic.SwappedMove; public class Resources { // Global Variables and Constants public static int DIMX_GRAVITY = 10, DIMY_GRAVITY = 10; // Is not final, cause we can modify it on the program public static final String RESOURCES_URL = "src/icons/"; public static final int MAX_STACK = 100, TILES_TO_WIN = 4, DIMX_CONNECT4 = 7, DIMY_CONNECT4 = 6, DIMX_COMPLICA = 4, DIMY_COMPLICA = 7, DIMX_REVERSI = 8, DIMY_REVERSI = 8; // Comprueba si alguna de las celdas empty, con el color del jugador actual, forman un posible movimiento public static boolean canMakeMove(Board b, Counter color) { // como se usa desde main y se usa una read only board no usar ningun metodo que sea para cambiar la tabla int column = 1, row = 1, total = 0; boolean valid = false; while(column <= b.getWidth() && !valid) { row = 1; while(row <= b.getHeight() && !valid) { if (b.getPosition(column, row) == Counter.EMPTY) { total = 0; total += checkHorizontal(b, color, column, row); // True = Left total += checkVertical(b, color, column, row); // False = Down total += checkDiagonal1(b, color, column, row); // False = Bottom Right total += checkDiagonal2(b, color, column, row); // False = Bottom Left if (total >= 1) { // => Si se ha formado al menos una check, significa que hay alguna celda flrmDa, por tanto, el movimiento es valido valid = true; } } row++; } column++; } return valid; } // CheckHorizontal: Function to Check left and right colors given a fixed position public static int checkHorizontal(Board b, Counter color, int x, int y) { int total = 0, accumulateTiles = 0, auxColumn = x; Counter nextColor = changeColor(color); // Check Left tiles while((auxColumn >= 1) && (b.getPosition(auxColumn - 1, y) == nextColor)) { auxColumn--; accumulateTiles++; } if (accumulateTiles >= 1 && (b.getPosition(auxColumn - 1, y) == color)) { total++; } // Check Right tiles while((auxColumn <= b.getWidth()) && (b.getPosition(auxColumn + 1, y) == nextColor)) { auxColumn++; accumulateTiles++; } if (accumulateTiles >= 1 && (b.getPosition(auxColumn + 1, y) == color)) { total++; } return total; } // CheckVertical: Function to Check top and bottom colors given a fixed position public static int checkVertical(Board b, Counter color, int x, int y) { int total = 0, accumulateTiles = 0, auxRow = y; Counter nextColor = changeColor(color); // Check up Tiles while((auxRow >= 1) && (b.getPosition(x, auxRow - 1) == nextColor)) { auxRow--; accumulateTiles++; } if (accumulateTiles >= 1 && (b.getPosition(x, auxRow - 1) == color)) { total++; } // Check Down tiles while((auxRow <= b.getHeight()) && (b.getPosition(x, auxRow + 1) == nextColor)) { auxRow++; accumulateTiles++; } if (accumulateTiles >= 1 && (b.getPosition(x, auxRow + 1) == color)) { total++; } return total; } // CheckDiagonal1: Function to Check diagonals given a fixed position public static int checkDiagonal1(Board b, Counter color, int x, int y) { int total = 0, accumulateTiles = 0, auxColumn = x, auxRow = y; Counter nextColor = changeColor(color); // Check UpLeft while((auxColumn >= 1) && (auxRow >= 1) && (b.getPosition(auxColumn - 1, auxRow - 1) == nextColor)) { auxColumn--; auxRow--; accumulateTiles++; } if (accumulateTiles >= 1 && (b.getPosition(auxColumn - 1, auxRow - 1) == color)) { total++; } // Check DownRight while((auxColumn <= b.getWidth()) && (auxRow <= b.getHeight()) && (b.getPosition(auxColumn + 1, auxRow + 1) == nextColor)) { auxColumn++; auxRow++; accumulateTiles++; } if (accumulateTiles >= 1 && (b.getPosition(auxColumn + 1, auxRow + 1) == color)) { total++; } return total; } // CheckDiagonal2: Function to Check diagonals given a fixed position public static int checkDiagonal2(Board b, Counter color, int x, int y) { int total = 0, accumulateTitles = 0, auxColumn = x, auxRow = y; Counter nextColor = changeColor(color); // Check Up Right while((auxColumn <= b.getWidth()) && (auxRow >= 1) && (b.getPosition(auxColumn + 1, auxRow - 1) == nextColor)) { auxColumn++; auxRow--; accumulateTitles++; } if (accumulateTitles >= 1 && (b.getPosition(auxColumn + 1, auxRow - 1) == color)) { total++; } // Check Bottom Left while((auxColumn >= 1) && (auxRow <= b.getHeight()) && (b.getPosition(auxColumn - 1, auxRow + 1) == nextColor)) { auxColumn--; auxRow++; accumulateTitles++; } if (accumulateTitles >= 1 && (b.getPosition(auxColumn - 1, auxRow + 1) == color)) { total++; } return total; } public static Counter changeColor(Counter c) { if (c == Counter.WHITE) return Counter.BLACK; else if(c == Counter.BLACK) return Counter.WHITE; else return Counter.EMPTY; } // Checks if there's an empty cell given a column public static int freeRowPosition(int col, Board board) { int row = -1, y = board.getHeight(); boolean empty = false; while ((!empty) && (y >= 1)) { if (board.getPosition(col,y) == Counter.EMPTY) { empty = true; row = y; } else { y } } return row; } // This functions is used for the Undo Function // Which returns the first row occupied (means that is the last movement of the user in that colum) public static int occupiedRowPosition(Board board, int col) { int row, height, y = 1; boolean occupied = false; height = row = board.getHeight(); while (!occupied && y <= height) { if (board.getPosition(col, y) != Counter.EMPTY) occupied = true; row = y; y++; } return row; } public static int menu(Game game, Scanner input) { int option = - 1; boolean valid = false; String optionString = "", lowerCaseStr; while (!valid) { game.getBoard().printBoard(); whoMoves(game); System.out.print ("Please enter a command: "); optionString = input.nextLine().toUpperCase(); lowerCaseStr = optionString.toLowerCase(); String[] words = optionString.split(" "); if (words.length == 1) { if (words[0].equals("UNDO")) { option = 1; } else if (words[0].equals("RESTART")) { option = 2; } else if (words[0].equals("EXIT")) { option = 3; } else if (words[0].equals("HELP")){ option = 7; } else { System.err.println(lowerCaseStr + ": command not understood, please try again"); } } else if (words.length == 2) { if (words[0].equals("PLAY")) { if (words[1].equals("C4")) { option = 4; } else if (words[1].equals("CO")) { option = 5; } else if (words[1].equals("RV")) { option = 12; } else { System.err.println(lowerCaseStr + ": command not understood, please try again"); } } else { System.err.println(lowerCaseStr + ": command not understood, please try again"); } } else if (words.length == 3) { if (words[0].equals("MAKE")) { if (words[1].equals("A")) { if (words[2].equals("MOVE")) { option = 0; } else { System.err.println(lowerCaseStr + ": command not understood, please try again"); } } else { System.err.println(lowerCaseStr + ": command not understood, please try again"); } } else if (words[0].equals("PLAYER")) { if (words[1].equals("WHITE")) { if(words[2].equals("HUMAN")) { option = 8; // WHITE HUMAN } else { option = 9; // WHITE RANDOM } } else if (words[1].equals("BLACK")) { if(words[2].equals("HUMAN")) { option = 10; // BLACK HUMAN } else { option = 11; // BLACK RANDOM } } } else { System.err.println(lowerCaseStr + ": command not understood, please try again"); } } else if (words.length == 4){ if (words[0].equals("PLAY")) { if (words[1].equals("GR")) { try { Integer.parseInt(words[2]); Integer.parseInt(words[3]); if (Integer.parseInt(words[2]) < 1){ setGravityDimX(1); } else{ setGravityDimX(Integer.parseInt(words[2])); } if (Integer.parseInt(words[3]) < 1){ setGravityDimY(1); } else{ setGravityDimY(Integer.parseInt(words[3])); } option = 6; } catch (NumberFormatException e) { System.err.println(lowerCaseStr + ": command not understood, please try again"); } } } } else { System.err.println(lowerCaseStr + ": command not understood, please try again"); } if ((option >= 0) && (option <= 12)) { valid = true; } } return option; } public static void whoMoves(Game game) { if (game.getTurn() == Counter.WHITE) System.out.println("White to move"); else if (game.getTurn() == Counter.BLACK) System.out.println("Black to move"); } public static void moveColumnDown(Board board, int column) { for (int i = board.getHeight(); i > 1; i board.setPosition(column, i, board.getPosition(column , i - 1)); } board.printBoard(); } public static void moveColumnUp(Board board, int column) { for (int i = 1 ; i < board.getHeight(); i++){ board.setPosition(column, i, board.getPosition(column, i + 1)); } } // que funcione el conecta 4. public static boolean fullColumn(int column, Board b) { boolean isFull = true; int row = b.getHeight(); while ((isFull) && (row >= 1)) { if (b.getPosition(column, row) == Counter.EMPTY) isFull = false; row } return isFull; } public static void setGravityDimX(int x) { DIMX_GRAVITY = x; } public static void setGravityDimY(int y){ DIMY_GRAVITY = y; } public static GravityMove applyGravity(Board board, int column, int row, Counter counter){ int distRight, distLeft, distUp, distBottom; distLeft = column - 1; distRight = DIMX_GRAVITY - column; distUp = row-1; distBottom = DIMY_GRAVITY - row; double minDIM = 0; int minDimInt = 0; GravityMove movement = null; minDIM = Math.min(DIMX_GRAVITY, DIMY_GRAVITY); minDimInt = (int) Math.ceil(minDIM/2); if((distLeft == distRight) && (distUp == distBottom)) { movement = displaceCounter(board, column, row, 0, 0, counter); } else if (distLeft == distRight) { if (distUp < distBottom) { movement = displaceCounter(board, column, row, 0, -1, counter); } else if (distBottom < distUp) { movement = displaceCounter(board, column, row, 0, +1, counter); } } else if (distUp == distBottom) { if (distLeft < distRight) { movement = displaceCounter(board, column, row, -1, 0, counter); } else if (distLeft > distRight) { movement = displaceCounter(board, column, row, +1, 0, counter); } } else if ((distUp == distRight) && (distUp < minDimInt)) { movement = displaceCounter(board, column, row, +1, -1, counter); } else if ((distUp == distLeft) && (distUp < minDimInt)) { movement = displaceCounter(board, column, row, -1, -1, counter); } else if ((distBottom == distRight) && (distBottom < minDimInt)) { movement = displaceCounter(board, column, row, +1, +1, counter); } else if ((distBottom == distLeft) && (distBottom < minDimInt)){ movement = displaceCounter(board, column, row, -1, +1, counter); } else if ((distUp < distRight) && (distUp < distLeft) && (distUp < distBottom)) { movement = displaceCounter(board, column, row, 0, -1, counter); } else if ((distRight < distUp) && (distRight < distLeft) && (distRight < distBottom)) { movement = displaceCounter(board, column, row, +1, 0, counter); } else if ((distLeft < distRight) && (distLeft < distUp) && (distLeft < distBottom)) { movement = displaceCounter(board, column, row, -1, 0, counter); } else if ((distBottom < distRight) && (distBottom < distLeft) && (distBottom < distUp)) { movement = displaceCounter(board, column, row, 0, +1, counter); } return movement; } public static GravityMove displaceCounter(Board board, int posCol, int posRow, int movCol, int movRow, Counter counter) { boolean ocuppy = false; int actualRow = posRow, actualColumn = posCol; if ((movCol == 0) && (movRow == 0)) board.setPosition(actualColumn, actualRow, counter); while (!ocuppy){ if (actualColumn > 1 && actualColumn < DIMX_GRAVITY && actualRow > 1 && actualRow < DIMY_GRAVITY) { if (board.getPosition(actualColumn + movCol, actualRow + movRow) != Counter.EMPTY) { ocuppy = true; } else{ actualColumn += movCol; actualRow += movRow; } } else { ocuppy = true; } } return new GravityMove(actualColumn, actualRow, counter); } public static void help() { System.out.println("The available commands are:"); System.out.println(""); System.out.println("MAKE A MOVE: place a counter on the board."); System.out.println("UNDO: undo the last move of the game."); System.out.println("RESTART: restart the game."); System.out.println("PLAY [c4|co|gr] [dimX dimY]: change the type of game."); System.out.println("PLAYER [white|black] [human|random]: change the type of player."); System.out.println("EXIT: exit the application."); System.out.println("HELP: show this help."); } public static void helpInit() { System.out.println("usage: tp.pr3.Main [-g <game>] [-h] [-x <columnNumber>] [-y <rowNumber>]"); System.out.println(" -g,--game <game> Type of game (c4, co, gr, rv). By default, c4."); System.out.println(" -h,--help Displays this help."); System.out.println(" -u,--ui<tipo> Type of interface (console,window)."); System.out.println(" by default console."); System.out.println(" -x,--dimX <columnNumber> Number of columns on the board (Gravity only)."); System.out.println(" By default, 10."); System.out.println(" -y,--dimY <rowNumber> Number of rows on the board (Gravity only). By"); System.out.println(" default, 10."); } //METHODS FOR THE VIEW public static GridBagConstraints configureConstraint(int fill, int gridX, int gridY, double weightX, double weightY) { GridBagConstraints c = new GridBagConstraints(); c.fill = fill; c.gridx = gridX; c.gridy = gridY; c.weightx = weightX; c.weighty = weightY; return c; } public static JPanel createPanel(Color color, int x, int y) { JPanel panel = new JPanel(); panel.setBackground(color); panel.setPreferredSize(new Dimension(x,y)); panel.setVisible(true); return panel; } public static JButton createAuxButton(int w, int h, String name, String fileName, Color c, boolean border) { JButton b = new JButton(); b.setBackground(c); b.setPreferredSize(new Dimension(w, h)); if (fileName != "") b.setIcon(new ImageIcon(fileName)); if (name != "") b.setText(name); if (!border) b.setBorder(null); return b; } }
/*** * Implement pow(x, n). */ public class PowXN{ public double pow(double x, int n) { if (n == 0) return 1.0; //*/
package cspom; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import org.apache.tools.bzip2.CBZip2InputStream; import cspom.compiler.ConstraintCompiler; import cspom.compiler.PredicateParseException; import cspom.constraint.CSPOMConstraint; import cspom.dimacs.CNFParser; import cspom.variable.CSPOMDomain; import cspom.variable.CSPOMVariable; import cspom.xcsp.XCSPParser; /** * * CSPOM is the central class of the Constraint Satisfaction Problem Object * Model. You can create a problem from scratch by instantiating this class and * then using the ctr and var methods. The CSPOM.load() method can be used in * order to create a CSPOM object from an XCSP file. * <p> * The CSPOM class adheres to the following definition : * * A CSP is defined as a pair (X, C), X being a finite set of variables, and C a * finite set of constraints. * * A domain is associated to each variable x in X. Each constraint involves a * finite set of variables (its scope) and defines a set of allowed and * forbidden instantiations of these variables. * * @author Julien Vion * @see CSPOMConstraint * @see CSPOMVariable * */ public final class CSPOM { /** * Version obtained from SVN Info. */ public static final String VERSION; static { final Matcher matcher = Pattern.compile("Rev:\\ (\\d+)").matcher( "$Rev$"); matcher.find(); VERSION = matcher.group(1); } /** * List of variables of the problem, in order. */ private final List<CSPOMVariable> variableList; /** * Map used to easily retrieve a variable according to its name. */ private final Map<String, CSPOMVariable> variableMap; /** * Collection of all constraints of the problem. */ private final Collection<CSPOMConstraint> constraints; /** * The constraint compiler used by this CSPOM instance. */ private ConstraintCompiler constraintCompiler; /** * Creates an empty problem, without any initial variables nor constraints. */ public CSPOM() { variableList = new LinkedList<CSPOMVariable>(); variableMap = new HashMap<String, CSPOMVariable>(); constraints = new ArrayList<CSPOMConstraint>(); } /** * Opens an InputStream according to the given URL. If URL ends with ".gz" * or ".bz2", the stream is inflated accordingly. * * @param url * URL to open * @return An InputStream corresponding to the given URL * @throws IOException * If the InputStream could not be opened */ public static InputStream problemInputStream(final URL url) throws IOException { final String path = url.getPath(); if (path.endsWith(".gz")) { return new GZIPInputStream(url.openStream()); } if (path.endsWith(".bz2")) { final InputStream is = url.openStream(); is.read(); is.read(); return new CBZip2InputStream(is); } return url.openStream(); } /** * Loads a CSPOM from a given XCSP file. * * @param xcspFile * Either a filename or an URI. Filenames ending with .gz or .bz2 * will be inflated accordingly. * @return The loaded CSPOM * @throws CSPParseException * If the given file could not be parsed. * @throws IOException * If the given file could not be read. * @throws DimacsParseException */ public static CSPOM load(final String xcspFile) throws CSPParseException, IOException { final URI uri; try { uri = new URI(xcspFile); } catch (URISyntaxException e) { throw new IOException("Invalid URI", e); } if (uri.getScheme() == null) { return load(new URL("file://" + uri)); } return load(uri.toURL()); } /** * Loads a CSPOM from a given XCSP file. * * @param url * An URL locating the XCSP file. Filenames ending with .gz or * .bz2 will be inflated accordingly. * @return The loaded CSPOM * @throws CSPParseException * If the given file could not be parsed. * @throws IOException * If the given file could not be read. * @throws DimacsParseException */ public static CSPOM load(final URL url) throws CSPParseException, IOException { final CSPOM problem = new CSPOM(); final InputStream problemIS = problemInputStream(url); if (url.getFile().contains(".xml")) { new XCSPParser(problem).parse(problemIS); } else if (url.getFile().contains(".cnf")) { new CNFParser(problem).parse(problemIS); } else { throw new IllegalArgumentException("Unhandled file format"); } return problem; } public void removeConstraint(final CSPOMConstraint c) { for (CSPOMVariable v : c) { v.removeConstraint(c); } constraints.remove(c); } public void removeVariable(final CSPOMVariable v) { if (v.getConstraints().isEmpty()) { variableList.remove(v); variableMap.remove(v.getName()); } else { throw new IllegalArgumentException(v + " is still implied by constraints"); } } /** * @return The variables of this problem. */ public List<CSPOMVariable> getVariables() { return variableList; } /** * Adds a variable to the problem. * * @param variable * The variable to add. It must have an unique name. * @throws DuplicateVariableException * If a variable with the same name already exists. */ public void addVariable(final CSPOMVariable variable) throws DuplicateVariableException { if (variableMap.put(variable.getName(), variable) != null) { throw new DuplicateVariableException(variable.getName()); } variableList.add(variable); } /** * Adds a constraint to the problem. * * @param constraint * The constraint to add. */ public void addConstraint(final CSPOMConstraint constraint) { constraints.add(constraint); } /** * @return The constraints of this problem. */ public Collection<CSPOMConstraint> getConstraints() { return constraints; } /** * Adds a bounded, unnamed variable in the problem. * * @param lb * lower bound * @param ub * upper bound * @return The added variable. */ public CSPOMVariable var(final int lb, final int ub) { final CSPOMVariable variable = new CSPOMVariable(lb, ub); try { addVariable(variable); } catch (DuplicateVariableException e) { throw new IllegalStateException(); } return variable; } /** * Adds a bounded, named variable in the problem. * * @param name * name of the variable * @param lb * lower bound * @param ub * upper bound * @return The added variable. * @throws DuplicateVariableException * if a variable of the same name already exists */ public CSPOMVariable var(final String name, final int lb, final int ub) throws DuplicateVariableException { final CSPOMVariable variable = new CSPOMVariable(name, lb, ub); addVariable(variable); return variable; } /** * Adds functional constraints to the problem. The given predicate will be * parsed and the appropriate constraints added to the problem. The * predicate may be complex and is usually translated to a set of * constraints and auxiliary variables, resulting in the returned * subproblem. Use variable names in the predicate to reference them. These * variables must already be added to the problem. * * @param string * A predicate. * @throws PredicateParseException * If an error was encountered parsing the predicate. * @return The subproblem corresponding to the given predicate */ public CSPOM ctr(final String string) throws PredicateParseException { if (constraintCompiler == null) { constraintCompiler = new ConstraintCompiler(this); } final CSPOM subproblem = constraintCompiler.split(string); merge(subproblem); return subproblem; } /** * @param variableName * A variable name. * @return The variable with the corresponding name. */ public CSPOMVariable getVariable(final String variableName) { return variableMap.get(variableName); } /** * Merges the given subproblem in the current problem. If not already * present, variables are added to the current problem. * * @param problem * A subproblem. */ public void merge(final CSPOM problem) { for (CSPOMVariable v : problem.variableList) { if (!variableMap.containsValue(v)) { try { addVariable(v); } catch (DuplicateVariableException e) { throw new IllegalStateException(); } } } constraints.addAll(problem.constraints); } @Override public String toString() { final StringBuilder stb = new StringBuilder(); for (CSPOMVariable v : variableList) { stb.append(v).append(" = "); final CSPOMDomain<?> d = v.getDomain(); if (d == null) { stb.append('?'); } else { stb.append(d); } stb.append('\n'); } for (CSPOMConstraint c : constraints) { stb.append(c).append('\n'); } return stb.toString(); } /** * Generates the constraint network graph in the GML format. N-ary * constraints are represented as nodes. * * @return a String containing the GML representation of the constraint * network. */ public String toGML() { final StringBuilder stb = new StringBuilder(); stb.append("graph [\n"); stb.append("directed 0\n"); for (CSPOMVariable v : variableList) { stb.append("node [\n"); stb.append("id \"").append(v.getName()).append("\"\n"); stb.append("label \"").append(v.getName()).append("\"\n"); stb.append("]\n"); } int gen = 0; for (CSPOMConstraint c : constraints) { if (c.getArity() > 2) { stb.append("node [\n"); stb.append("id \"cons").append(gen).append("\"\n"); stb.append("label \"").append(c.getDescription()) .append("\"\n"); stb.append("graphics [\n"); stb.append("fill \"#FFAA00\"\n"); stb.append("]\n"); stb.append("]\n"); for (CSPOMVariable v : c) { stb.append("edge [\n"); stb.append("source \"cons").append(gen).append("\"\n"); stb.append("target \"").append(v.getName()).append("\"\n"); stb.append("]\n"); } gen++; } else if (c.getArity() == 2) { stb.append("edge [\n"); stb.append("source \"").append(c.getScope().get(0)).append( "\"\n"); stb.append("target \"").append(c.getScope().get(1)).append( "\"\n"); stb.append("label \"").append(c.getDescription()) .append("\"\n"); stb.append("]\n"); } } stb.append("]\n"); return stb.toString(); } }
// S y s t e m // // This software is released under the terms of the GNU General Public // // to report bugs & suggestions. // package omr.score; import static omr.score.ScoreConstants.*; import omr.score.visitor.Visitor; import omr.sheet.SystemInfo; import omr.util.Dumper; import omr.util.Logger; import omr.util.TreeNode; import java.util.ArrayList; import java.util.List; /** * Class <code>System</code> encapsulates a system in a score. <p>A system * contains two direct children : staves and slurs, each in its dedicated list. * * @author Herv&eacute; Bitteur * @version $Id$ */ public class System extends MusicNode { private static final Logger logger = Logger.getLogger(System.class); /** Specific Child : list of slurs */ private final SlurList slurs; /** Specific Child : list of staves */ private final StaffList staves; /** Parts in this system */ private List<SystemPart> parts = new ArrayList<SystemPart>(); /** Top left corner of the system */ private PagePoint topLeft; /** Actual display origin */ private ScorePoint origin; /** Related info from sheet analysis */ private SystemInfo info; /** System dimensions, expressed in units */ private UnitDimension dimension; /** Id of first measure */ private int firstMeasureId = 0; /** Id of last measure */ private int lastMeasureId = 0; // System // /** * Default constructor (needed by XML binder) */ public System () { this(null, null, null, null); } // System // /** * Create a system with all needed parameters * * @param info the physical information retrieved from the sheet * @param score the containing score * @param topLeft the coordinate, in units, of the upper left point of the * system in its containing score * @param dimension the dimension of the system, expressed in units */ public System (SystemInfo info, Score score, PagePoint topLeft, UnitDimension dimension) { super(score); // Allocate staff and slur (node) lists staves = new StaffList(this); slurs = new SlurList(this); this.info = info; this.topLeft = topLeft; this.dimension = dimension; if (logger.isFineEnabled()) { Dumper.dump(this, "Constructed"); } } // setDimension // /** * Set the system dimension. * * <p>Width is the distance, in units, between left edge and right edge. * * <p>Height is the distance, in units, from top of first staff, down to * bottom of last staff * * @param dimension system dimension, in units */ public void setDimension (UnitDimension dimension) { this.dimension = dimension; } // getDimension // /** * Report the system dimension. * * @return the system dimension, in units * @see #setDimension */ public UnitDimension getDimension () { return dimension; } // setFirstMeasureId // /** * Assign id for first measure * * @param firstMeasureId first measure id */ public void setFirstMeasureId (int firstMeasureId) { this.firstMeasureId = firstMeasureId; } // getFirstMeasureId // /** * Report the id of the first measure in the system, knowing that 0 is the * id of the very first measure of the very first system in the score * * @return the first measure id */ public int getFirstMeasureId () { return firstMeasureId; } // getFirstStaff // /** * Report the first staff in this system * * @return the first staff entity */ public Staff getFirstStaff () { return (Staff) getStaves() .get(0); } // getInfo // /** * Report the physical information retrieved from the sheet for this system * * @return the information entity */ public SystemInfo getInfo () { return info; } // setLastMeasureId // /** * Remember the id of the last measure in this system * * @param lastMeasureId last measure index */ public void setLastMeasureId (int lastMeasureId) { this.lastMeasureId = lastMeasureId; } // getLastMeasureId // /** * Report the id of the last measure in this system * * @return the last measure id */ public int getLastMeasureId () { return lastMeasureId; } // getLastStaff // /** * Report the last staff in this system * * @return the last staff entity */ public Staff getLastStaff () { return (Staff) getStaves() .get(getStaves().size() - 1); } // setOrigin // /** * Assign origin for display * * @param origin display origin for this system */ public void setOrigin (ScorePoint origin) { this.origin = origin; } // getOrigin // /** * Report the origin for this system, in the horizontal score display * * @return the display origin */ public ScorePoint getOrigin () { return origin; } // setParts // /** * Assign the parts for this system * * @param parts the ordered parts */ public void setParts (List<SystemPart> parts) { this.parts = parts; } // setParts // /** * Report the parts for this system * * @return the ordered parts */ public List<SystemPart> getParts () { return parts; } // getRightPosition // /** * Return the actual display position of the right side. * * @return the display abscissa of the right system edge */ public int getRightPosition () { return (origin.x + dimension.width) - 1; } // setSlurs // /** * Set the collection of slurs * * @param slurs the collection of slurs */ public void setSlurs (List<TreeNode> slurs) { final List<TreeNode> list = getSlurs(); if (list != slurs) { list.clear(); list.addAll(slurs); } } // getSlurs // /** * Report the collection of slurs * * @return the slur list, which may be empty but not null */ public List<TreeNode> getSlurs () { return slurs.getChildren(); } // getStaffAt // /** * Report the staff nearest (in ordinate) to a provided point * * @param point the provided point * * @return the nearest staff */ public Staff getStaffAt (PagePoint point) { int minDy = Integer.MAX_VALUE; Staff best = null; for (TreeNode node : getStaves()) { Staff staff = (Staff) node; int midY = staff.getTopLeft().y + (staff.getSize() / 2); int dy = Math.abs(point.y - midY); if (dy < minDy) { minDy = dy; best = staff; } } return best; } // setStaves // /** * Set the collection of staves * * @param staves the collection of staves */ public void setStaves (List<TreeNode> staves) { final List<TreeNode> list = getStaves(); if (list != staves) { list.clear(); list.addAll(staves); } } // getStaves // /** * Report the collection of staves * * @return the staff list */ public List<TreeNode> getStaves () { return staves.getChildren(); } // setTopLeft // /** * Set the coordinates of the top left cormer of the system in the score * * @param topLeft the upper left point, with coordinates in units, in * virtual score page */ public void setTopLeft (PagePoint topLeft) { this.topLeft = topLeft; } // getTopLeft // /** * Report the coordinates of the upper left corner of this system in its * containing score * * @return the top left corner * @see #setTopLeft */ public PagePoint getTopLeft () { return topLeft; } // accept // @Override public boolean accept (Visitor visitor) { return visitor.visit(this); } // addChild // /** * Overrides normal behavior, to deal with the separation of children into * slurs and staves * * @param node the node to insert (either a slur or a staff) */ @Override public void addChild (TreeNode node) { if (node instanceof Staff) { staves.addChild(node); node.setContainer(staves); } else if (node instanceof Slur) { slurs.addChild(node); node.setContainer(slurs); } else if (node instanceof MusicNode) { children.add(node); node.setContainer(this); } else { // Programming error Dumper.dump(node); logger.severe("System node not Staff nor Slur"); } } // scoreToSheet // /** * Compute the point in the sheet that corresponds to a given point in the * score display * * @param scrPt the point in the score display * @param pagPt the corresponding sheet point, or null * @return the page point * * @see #sheetToScore */ public PagePoint scoreToSheet (ScorePoint scrPt, PagePoint pagPt) { if (pagPt == null) { pagPt = new PagePoint(); } pagPt.x = (topLeft.x + scrPt.x) - origin.x; pagPt.y = (topLeft.y + scrPt.y) - origin.y; return pagPt; } // sheetToScore // /** * Compute the score display point that correspond to a given sheet point, * since systems are displayed horizontally in the score display, while they * are located one under the other in a sheet. * * @param pagPt the point in the sheet * @param scrPt the corresponding point in score display, or null * @return the score point * * @see #scoreToSheet */ public ScorePoint sheetToScore (PagePoint pagPt, ScorePoint scrPt) { if (scrPt == null) { scrPt = new ScorePoint(); } scrPt.x = (origin.x + pagPt.x) - topLeft.x; scrPt.y = (origin.y + pagPt.y) - topLeft.y; return scrPt; } // toString // /** * Report a readable description * * @return a string based on upper left corner */ @Override public String toString () { StringBuilder sb = new StringBuilder(); sb.append("{System") .append(" topLeft=[") .append(topLeft.x) .append(",") .append(topLeft.y) .append("]") .append(" dimension=") .append(dimension.width) .append("x") .append(dimension.height) .append("}"); return sb.toString(); } // xIntersect // /** * Check for intersection of a given clip determined by (left, right) with * the system abscissa range. TBD : add some margin on left and right so * that symbols on a system border get correctly drawn. * * @param left min abscissa * @param right max abscissa * * @return true if overlap, false otherwise */ public boolean xIntersect (int left, int right) { if (left > getRightPosition()) { return false; } if (right < origin.x) { return false; } return true; } // xLocate // /** * Return the position of given x, relative to the system. * * @param x the abscissa value of the point (scrPt) * * @return -1 for left, 0 for middle, +1 for right */ public int xLocate (int x) { if (x < origin.x) { return -1; } if (x > getRightPosition()) { return +1; } return 0; } // yLocate // /** * Return the position of given y, relative to the system * * @param y the ordinate value of the point (pagPt) * * @return -1 for above, 0 for middle, +1 for below */ public int yLocate (int y) { if (y < topLeft.y) { return -1; } if (y > (topLeft.y + dimension.height + STAFF_HEIGHT)) { return +1; } return 0; } // SlurList // private static class SlurList extends MusicNode { SlurList (MusicNode container) { super(container); } } // StaffList // private static class StaffList extends MusicNode { StaffList (MusicNode container) { super(container); } } }
package uk.me.steev.java.heating.io.http; import java.io.IOException; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import uk.me.steev.java.heating.controller.Heating; import uk.me.steev.java.heating.controller.HeatingConfiguration; import uk.me.steev.java.heating.controller.HeatingException; import uk.me.steev.java.heating.controller.TemperatureEvent; import uk.me.steev.java.heating.io.boiler.RelayException; import uk.me.steev.java.heating.io.temperature.BluetoothTemperatureSensor; public class AllDetailsAfterProcessServlet extends HeatingServlet { private static final long serialVersionUID = -2479268631077208608L; static final Logger logger = LogManager.getLogger(CurrentTempServlet.class.getName()); public AllDetailsAfterProcessServlet(Heating heating) { super(heating); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); JSONObject json = new JSONObject(); String pathInfo = null; if (null != request.getPathInfo()) pathInfo = request.getPathInfo().replaceFirst("/", ""); if (!(null != pathInfo && "no_wait".equals(pathInfo))) { try { synchronized(heating) { heating.wait(); } Thread.sleep(2000); } catch (InterruptedException ie) { logger.catching(ie); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } Map<String, BluetoothTemperatureSensor> sensors = heating.getSensors(); Map<String, Float> temps = new TreeMap<String, Float>(); for (String s : sensors.keySet()) { temps.put(sensors.get(s).getName(), sensors.get(s).getCurrentTemperature()); } json.put("temps", temps); try { json.put("heating", heating.getBoiler().isHeating()); json.put("preheat", heating.getBoiler().isPreheating()); } catch (RelayException re) { logger.catching(re); } json.put("currentsetpoint", heating.getDesiredTemperature()); List<TemperatureEvent> timesDueOn = heating.getProcessor().getTimesDueOn(); TemperatureEvent next = null; try { if (null != timesDueOn && timesDueOn.size() > 0) { TemperatureEvent te = timesDueOn.get(0); if (te.getStartTime().isAfter(LocalDateTime.now())) { //Not in an event currently json.put("nextsetpoint", te.getTemperature()); json.put("nexteventstart", te.getStartTime().toString()); } else if (timesDueOn.size() >= 2) { next = timesDueOn.get(1); if (te.getEndTime().isEqual(next.getStartTime()) || te.getEndTime().isAfter(next.getStartTime())) { //In an event, next starts immediately after json.put("nextsetpoint", next.getTemperature()); json.put("nexteventstart", next.getStartTime().toString()); } else { //In an event, no event immediately after json.put("nextsetpoint", HeatingConfiguration.getIntegerSetting("heating", "minimum_temperature")); json.put("nexteventstart", te.getEndTime()); } } else { //Only one event and we're in it json.put("nextsetpoint", HeatingConfiguration.getIntegerSetting("heating", "minimum_temperature")); json.put("nexteventstart", te.getEndTime()); } } else { //No events json.put("nextsetpoint", HeatingConfiguration.getIntegerSetting("heating", "minimum_temperature")); } } catch (HeatingException re) { logger.catching(re); } json.put("override", heating.getOverrideDegrees()); json.put("goneoutuntil", null == heating.getGoneOutUntilTime() ? JSONObject.NULL : heating.getGoneOutUntilTime()); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(json.toString(2)); } }
package org.helioviewer.viewmodel.view.jp2view; import java.util.Arrays; import kdu_jni.KduException; import kdu_jni.Kdu_compositor_buf; import kdu_jni.Kdu_coords; import kdu_jni.Kdu_dims; import kdu_jni.Kdu_region_compositor; import org.helioviewer.base.logging.Log; import org.helioviewer.base.math.Interval; import org.helioviewer.viewmodel.changeevent.ChangeEvent; import org.helioviewer.viewmodel.changeevent.NonConstantMetaDataChangedReason; import org.helioviewer.viewmodel.imagedata.ARGBInt32ImageData; import org.helioviewer.viewmodel.imagedata.ColorMask; import org.helioviewer.viewmodel.imagedata.SingleChannelByte8ImageData; import org.helioviewer.viewmodel.metadata.MetaData; import org.helioviewer.viewmodel.metadata.NonConstantMetaData; import org.helioviewer.viewmodel.view.CachedMovieView; import org.helioviewer.viewmodel.view.LinkedMovieManager; import org.helioviewer.viewmodel.view.MovieView; import org.helioviewer.viewmodel.view.MovieView.AnimationMode; import org.helioviewer.viewmodel.view.cache.DateTimeCache; import org.helioviewer.viewmodel.view.jp2view.image.JP2ImageParameter; import org.helioviewer.viewmodel.view.jp2view.image.SubImage; import org.helioviewer.viewmodel.view.jp2view.kakadu.JHV_Kdu_thread_env; import org.helioviewer.viewmodel.view.jp2view.kakadu.KakaduUtils; /** * The J2KRender class handles all of the decompression, buffering, and * filtering of the image data. It essentially just waits for the shared object * in the JP2ImageView to signal it. * * @author caplins * @author Benjamin Wamsler * @author Desmond Amadigwe * @author Markus Langenberg */ class J2KRender implements Runnable { /** * There could be multiple reason that the Render object was signaled. This * enum lists them. */ public enum RenderReasons { NEW_DATA, OTHER, MOVIE_PLAY }; /** The thread that this object runs on. */ private volatile Thread myThread; /** A boolean flag used for stopping the thread. */ private volatile boolean stop; /** A reference to the JP2Image this object is owned by. */ private final JP2Image parentImageRef; /** A reference to the JP2ImageView this object is owned by. */ private final JHVJP2View parentViewRef; /** A reference to the compositor used by this JP2Image. */ private final Kdu_region_compositor compositorRef; /** Used in run method to keep track of the current ImageViewParams */ private JP2ImageParameter currParams = null; private int lastFrame = -1; private final static int NUM_BUFFERS = 1; /** An integer buffer used in the run method. */ private int[] localIntBuffer = new int[0]; private int[][] intBuffer = new int[NUM_BUFFERS][0]; private int currentIntBuffer = 0; /** A byte buffer used in the run method. */ private byte[][] byteBuffer = new byte[NUM_BUFFERS][0]; private int currentByteBuffer = 0; /** Maximum of samples to process per rendering iteration */ private final int MAX_RENDER_SAMPLES = 50000; /** Maximum rendering iterations per layer allowed */ // Is now calculated automatically as num_pix / MAX_RENDER_SAMPLES private final int MAX_RENDER_ITERATIONS = 150; /** It says if the render is going to play a movie instead of a single image */ private boolean movieMode = false; private boolean linkedMovieMode = false; /** * Sets whether the byte and integer buffers should be reused between * frames. * <p> * Normally this avoids garbage collection, but for some cases it must be * deactivated */ private boolean reuseBuffer = true; /** * Gets whether to reuse the buffer * * @return the reuseBuffer */ public boolean isReuseBuffer() { return reuseBuffer; } /** * Sets whether to reuse the buffer * * @param reuseBuffer * the reuseBuffer to set */ public void setReuseBuffer(boolean reuseBuffer) { this.reuseBuffer = reuseBuffer; } private int movieSpeed = 20; private float actualMovieFramerate = 0.0f; private long lastSleepTime = 0; private int lastCompositionLayerRendered = -1; private NextFrameCandidateChooser nextFrameCandidateChooser = new NextFrameCandidateLoopChooser(); private FrameChooser frameChooser = new RelativeFrameChooser(); private boolean differenceMode = false; /** * The constructor. * * @param _parentViewRef */ J2KRender(JHVJP2View _parentViewRef) { if (_parentViewRef == null) throw new NullPointerException(); parentViewRef = _parentViewRef; parentImageRef = parentViewRef.jp2Image; compositorRef = parentImageRef.getCompositorRef(); stop = false; myThread = null; } /** Starts the J2KRender thread. */ void start() { if (myThread != null) stop(); myThread = new Thread(JHVJP2View.renderGroup, this, "J2KRender"); stop = false; myThread.start(); } /** Stops the J2KRender thread. */ void stop() { if (myThread != null && myThread.isAlive()) { try { stop = true; do { myThread.interrupt(); myThread.join(100); } while (myThread.isAlive()); } catch (InterruptedException ex) { ex.printStackTrace(); } catch (NullPointerException e) { } finally { myThread = null; intBuffer = new int[NUM_BUFFERS][0]; byteBuffer = new byte[NUM_BUFFERS][0]; } } } /** Destroys the resources associated with this object */ void abolish() { stop(); } public void setMovieMode(boolean val) { if (movieMode) { myThread.interrupt(); System.gc(); } movieMode = val; if (frameChooser instanceof AbsoluteFrameChooser) { ((AbsoluteFrameChooser) frameChooser).resetStartTime(currParams.compositionLayer); } } public void setLinkedMovieMode(boolean val) { linkedMovieMode = val; } public void setMovieRelativeSpeed(int framesPerSecond) { if (movieMode && lastSleepTime > 1000) { myThread.interrupt(); } movieSpeed = framesPerSecond; frameChooser = new RelativeFrameChooser(); } public void setMovieAbsoluteSpeed(int secondsPerSecond) { if (movieMode && lastSleepTime > 1000) { myThread.interrupt(); } movieSpeed = secondsPerSecond; frameChooser = new AbsoluteFrameChooser(); } public void setAnimationMode(AnimationMode mode) { switch (mode) { case LOOP: nextFrameCandidateChooser = new NextFrameCandidateLoopChooser(); break; case STOP: nextFrameCandidateChooser = new NextFrameCandidateStopChooser(); break; case SWING: nextFrameCandidateChooser = new NextFrameCandidateSwingChooser(); break; } } public float getActualMovieFramerate() { return actualMovieFramerate; } public boolean isMovieMode() { return movieMode; } private void renderLayer(int numLayer) { parentImageRef.getLock().lock(); try { if (JP2Image.numJP2ImagesInUse() == 1) { compositorRef.Set_thread_env(JHV_Kdu_thread_env.getSingletonInstance(), 0); } else { compositorRef.Set_thread_env(null, 0); } compositorRef.Refresh(); compositorRef.Remove_compositing_layer(-1, true); parentImageRef.deactivateColorLookupTable(numLayer); Kdu_dims dimsRef1 = new Kdu_dims(), dimsRef2 = new Kdu_dims(); compositorRef.Add_compositing_layer(numLayer, dimsRef1, dimsRef2); if (lastCompositionLayerRendered != numLayer) { lastCompositionLayerRendered = numLayer; parentImageRef.updateResolutionSet(numLayer); MetaData metaData = parentViewRef.getMetaData(); if (metaData instanceof NonConstantMetaData && ((NonConstantMetaData) metaData).checkForModifications()) { parentViewRef.updateParameter(); currParams = parentViewRef.getImageViewParams(); parentViewRef.addChangedReason(new NonConstantMetaDataChangedReason(parentViewRef, metaData)); } } compositorRef.Set_max_quality_layers(currParams.qualityLayers); compositorRef.Set_scale(false, false, false, currParams.resolution.getZoomPercent()); Kdu_dims requestedBufferedRegion = KakaduUtils.roiToKdu_dims(currParams.subImage); compositorRef.Set_buffer_surface(requestedBufferedRegion, 0); Kdu_dims actualBufferedRegion = new Kdu_dims(); Kdu_compositor_buf compositorBuf = compositorRef.Get_composition_buffer(actualBufferedRegion); Kdu_coords actualOffset = new Kdu_coords(); actualOffset.Assign(actualBufferedRegion.Access_pos()); Kdu_dims newRegion = new Kdu_dims(); if (parentImageRef.getNumComponents() < 3) { currentByteBuffer = (currentByteBuffer + 1) % NUM_BUFFERS; byteBuffer[currentByteBuffer] = new byte[currParams.subImage.getNumPixels()]; } else { currentIntBuffer = (currentIntBuffer + 1) % NUM_BUFFERS; if (differenceMode || currParams.subImage.getNumPixels() != intBuffer[currentIntBuffer].length || (!movieMode && !linkedMovieMode && !J2KRenderGlobalOptions.getDoubleBufferingOption())) { intBuffer[currentIntBuffer] = new int[currParams.subImage.getNumPixels()]; } else if (J2KRenderGlobalOptions.getDoubleBufferingOption()) { Arrays.fill(intBuffer[currentIntBuffer], 0); } } while (!compositorRef.Is_processing_complete()) { compositorRef.Process(MAX_RENDER_SAMPLES, newRegion); Kdu_coords newOffset = newRegion.Access_pos(); Kdu_coords newSize = newRegion.Access_size(); newOffset.Subtract(actualOffset); int newPixels = newSize.Get_x() * newSize.Get_y(); if (newPixels == 0) continue; localIntBuffer = newPixels > localIntBuffer.length ? new int[newPixels << 1] : localIntBuffer; compositorBuf.Get_region(newRegion, localIntBuffer); // Log.debug("Local Int Buffer : " + // Arrays.toString(localIntBuffer)); int srcIdx = 0; int destIdx = newOffset.Get_x() + newOffset.Get_y() * currParams.subImage.width; int newWidth = newSize.Get_x(); int newHeight = newSize.Get_y(); if (parentImageRef.getNumComponents() < 3) { for (int row = 0; row < newHeight; row++, destIdx += currParams.subImage.width, srcIdx += newWidth) { for (int col = 0; col < newWidth; ++col) { byteBuffer[currentByteBuffer][destIdx + col] = (byte) ((localIntBuffer[srcIdx + col]) & 0xFF); } } } else { for (int row = 0; row < newHeight; row++, destIdx += currParams.subImage.width, srcIdx += newWidth) System.arraycopy(localIntBuffer, srcIdx, intBuffer[currentIntBuffer], destIdx, newWidth); } // Log.debug("byteBuffer : " + // Arrays.toString(byteBuffer[currentByteBuffer])); } if (compositorBuf != null) compositorBuf.Native_destroy(); } catch (KduException e) { e.printStackTrace(); } finally { parentImageRef.getLock().unlock(); } } /** * The method that decompresses and renders the image. It pushes it to the * ViewObserver. */ @Override public void run() { int numFrames = 0; lastFrame = -1; long tfrm, tmax = 0; long tnow, tini = System.currentTimeMillis(); while (!stop) { try { parentViewRef.renderRequestedSignal.waitForSignal(); } catch (InterruptedException ex) { continue; } currParams = parentViewRef.getImageViewParams(); nextFrameCandidateChooser.updateRange(); while (!Thread.interrupted() && !stop) { tfrm = System.currentTimeMillis(); int curLayer = currParams.compositionLayer; if (parentViewRef instanceof MovieView) { MovieView parent = (MovieView) parentViewRef; if (parent.getMaximumAccessibleFrameNumber() < curLayer) { try { Thread.sleep(200); } catch (InterruptedException e) { } parentViewRef.renderRequestedSignal.signal(RenderReasons.NEW_DATA); break; } } if (movieMode && parentViewRef instanceof JHVJPXView) { JHVJPXView jpxView = ((JHVJPXView) parentViewRef); LinkedMovieManager movieManager = jpxView.getLinkedMovieManager(); if (movieManager != null && movieManager.isMaster(jpxView)) { movieManager.updateCurrentFrameToMaster(new ChangeEvent()); } } renderLayer(curLayer); int width = currParams.subImage.width; int height = currParams.subImage.height; if (parentImageRef.getNumComponents() < 3) { if (currParams.subImage.getNumPixels() == byteBuffer[currentByteBuffer].length) { SingleChannelByte8ImageData imdata = new SingleChannelByte8ImageData(width, height, byteBuffer[currentByteBuffer], new ColorMask()); SubImage roi = currParams.subImage; parentViewRef.setSubimageData(imdata, currParams.subImage, curLayer, currParams.resolution.getZoomPercent(), false); } else { Log.warn("J2KRender: Params out of sync, skip frame"); } } else { if (currParams.subImage.getNumPixels() == intBuffer[currentIntBuffer].length) { parentViewRef.setSubimageData(new ARGBInt32ImageData(width, height, intBuffer[currentIntBuffer], new ColorMask()), currParams.subImage, curLayer, currParams.resolution.getZoomPercent(), false); } else { Log.warn("J2KRender: Params out of sync, skip frame"); } } if (!movieMode) break; else { currParams = parentViewRef.getImageViewParams(); numFrames += currParams.compositionLayer - lastFrame; lastFrame = currParams.compositionLayer; tmax = frameChooser.moveToNextFrame(); if (lastFrame > currParams.compositionLayer) { lastFrame = -1; } tnow = System.currentTimeMillis(); if ((tnow - tini) >= 1000) { actualMovieFramerate = (numFrames * 1000.0f) / (tnow - tini); tini = tnow; numFrames = 0; } lastSleepTime = tmax - (tnow - tfrm); if (lastSleepTime > 0) { try { Thread.sleep(lastSleepTime); } catch (InterruptedException ex) { break; } } else { Thread.yield(); } } } numFrames += currParams.compositionLayer - lastFrame; lastFrame = currParams.compositionLayer; if (lastFrame > currParams.compositionLayer) { lastFrame = -1; } tnow = System.currentTimeMillis(); if ((tnow - tini) >= 1000) { actualMovieFramerate = (numFrames * 1000.0f) / (tnow - tini); tini = tnow; numFrames = 0; } } byteBuffer = new byte[NUM_BUFFERS][0]; intBuffer = new int[NUM_BUFFERS][0]; } private abstract class NextFrameCandidateChooser { protected Interval<Integer> layers; public NextFrameCandidateChooser() { updateRange(); } public void updateRange() { if (parentImageRef != null) { layers = parentImageRef.getCompositionLayerRange(); } } protected void resetStartTime(int frameNumber) { if (frameChooser instanceof AbsoluteFrameChooser) { ((AbsoluteFrameChooser) frameChooser).resetStartTime(frameNumber); } } public abstract int getNextCandidate(int lastCandidate); } private class NextFrameCandidateLoopChooser extends NextFrameCandidateChooser { @Override public int getNextCandidate(int lastCandidate) { if (++lastCandidate > layers.getEnd()) { System.gc(); resetStartTime(layers.getStart()); return layers.getStart(); } return lastCandidate; } } private class NextFrameCandidateStopChooser extends NextFrameCandidateChooser { @Override public int getNextCandidate(int lastCandidate) { if (++lastCandidate > layers.getEnd()) { movieMode = false; resetStartTime(layers.getStart()); return layers.getStart(); } return lastCandidate; } } private class NextFrameCandidateSwingChooser extends NextFrameCandidateChooser { private int currentDirection = 1; @Override public int getNextCandidate(int lastCandidate) { lastCandidate += currentDirection; if (lastCandidate < layers.getStart() && currentDirection == -1) { currentDirection = 1; resetStartTime(layers.getStart()); return layers.getStart() + 1; } else if (lastCandidate > layers.getEnd() && currentDirection == 1) { currentDirection = -1; resetStartTime(layers.getEnd()); return layers.getEnd() - 1; } return lastCandidate; } } private interface FrameChooser { public long moveToNextFrame(); } private class RelativeFrameChooser implements FrameChooser { @Override public long moveToNextFrame() { currParams.compositionLayer = nextFrameCandidateChooser.getNextCandidate(currParams.compositionLayer); return 1000 / movieSpeed; } } private class AbsoluteFrameChooser implements FrameChooser { private final DateTimeCache dateTimeCache = ((CachedMovieView) parentViewRef).getDateTimeCache(); private long absoluteStartTime = dateTimeCache.getDateTime(currParams.compositionLayer).getMillis(); private long systemStartTime = System.currentTimeMillis(); public void resetStartTime(int frameNumber) { absoluteStartTime = dateTimeCache.getDateTime(frameNumber).getMillis(); systemStartTime = System.currentTimeMillis(); } @Override public long moveToNextFrame() { int lastCandidate, nextCandidate = currParams.compositionLayer; long lastDiff, nextDiff = -Long.MAX_VALUE; do { lastCandidate = nextCandidate; nextCandidate = nextFrameCandidateChooser.getNextCandidate(nextCandidate); lastDiff = nextDiff; nextDiff = Math.abs(dateTimeCache.getDateTime(nextCandidate).getMillis() - absoluteStartTime) - ((System.currentTimeMillis() - systemStartTime) * movieSpeed); } while (nextDiff < 0); if (-lastDiff < nextDiff) { currParams.compositionLayer = lastCandidate; return lastDiff / movieSpeed; } else { currParams.compositionLayer = nextCandidate; return nextDiff / movieSpeed; } } } public void setDifferenceMode(boolean differenceMode) { this.differenceMode = differenceMode; } }
package com.splicemachine.test.nist; import com.splicemachine.test.diff.DiffReport; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.io.*; import java.util.Collection; import java.util.List; import java.util.Map; public class NistTest { private static List<File> testFiles; private static List<String> derbyOutputFilter; private static List<String> spliceOutputFilter; private static DerbyNistRunner derbyRunner; private static SpliceNistRunner spliceRunner; private static boolean justDrop; @BeforeClass public static void beforeClass() throws Exception { // Gather the sql files we want to run as tests String singleScript = System.getProperty("script", null); if (singleScript == null) { testFiles = NistTestUtils.getTestFileList(); } else if (singleScript.equalsIgnoreCase(NistTestUtils.DROP_SQL)) { justDrop = true; } else { testFiles = NistTestUtils.createRunList(singleScript); } // Read in the bug filters for output files derbyOutputFilter = NistTestUtils.readDerbyFilters(); spliceOutputFilter = NistTestUtils.readSpliceFilters(); derbyRunner = new DerbyNistRunner(); spliceRunner = new SpliceNistRunner(); } @Test(timeout=1000*60*6) // Time out after 6 min public void runNistTest() throws Exception { if (justDrop) { NistTestUtils.runDrop(derbyRunner, spliceRunner); return; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); Collection<DiffReport> reports = NistTestUtils.runTests(testFiles, derbyRunner, derbyOutputFilter, spliceRunner, spliceOutputFilter, ps); Map<String,Integer> failedDiffs = DiffReport.reportCollection(reports, ps); String report = baos.toString("UTF-8"); NistTestUtils.createLog(NistTestUtils.getBaseDirectory(), "NistTest.log", null, report); Assert.assertEquals(failedDiffs.size() + " tests had differences: " + failedDiffs + "\n" + report, reports.size(), (reports.size() - failedDiffs.size())); } }
package com.venky.swf.db.model.io; import com.venky.cache.Cache; import com.venky.core.collections.SequenceSet; import com.venky.core.log.SWFLogger; import com.venky.core.log.TimerUtils; import com.venky.core.string.StringUtil; import com.venky.swf.db.Database; import com.venky.swf.db.annotations.column.ui.mimes.MimeType; import com.venky.swf.db.model.Model; import com.venky.swf.db.model.reflection.ModelReflector; import com.venky.swf.integration.FormatHelper; import com.venky.swf.routing.Config; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; public abstract class AbstractModelWriter<M extends Model,T> extends ModelIO<M> implements ModelWriter<M, T>{ protected AbstractModelWriter(Class<M> beanClass) { super(beanClass); } @SuppressWarnings("unchecked") public Class<T> getFormatClass(){ ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass(); return (Class<T>) pt.getActualTypeArguments()[1]; } public MimeType getMimeType(){ return FormatHelper.getMimeType(getFormatClass()); } private List<String> getFields(List<String> includeFields){ return getFields(getReflector(),includeFields); } private static <R extends Model> List<String> getFields(ModelReflector<R> reflector, List<String> includeFields) { List<String> fields = includeFields; if (fields == null){ fields = reflector.getVisibleFields(); } return fields; } public void write(List<M> records, OutputStream os,List<String> fields) throws IOException { Map<Class<? extends Model> , List<String>> mapFields = new HashMap<>(); Set<Class<? extends Model>> parentsWritten = new HashSet<>(); write (records,os,fields,parentsWritten,mapFields); } public void write (List<M> records,OutputStream os, List<String> fields, Set<Class<?extends Model>> parentsAlreadyConsidered, Map<Class<? extends Model>,List<String>> templateFields) throws IOException { write(records,os,fields,parentsAlreadyConsidered,getChildrenToConsider(templateFields),templateFields); } public void write (List<M> records,OutputStream os, List<String> fields, Set<Class<? extends Model>> parentsAlreadyConsidered , Map<Class<? extends Model>,List<Class<? extends Model>>> childrenToBeConsidered, Map<Class<? extends Model>,List<String>> templateFields) throws IOException { FormatHelper<T> helper = FormatHelper.instance(getMimeType(),StringUtil.pluralize(getBeanClass().getSimpleName()),true); for (M record: records){ T childElement = helper.createChildElement(getBeanClass().getSimpleName()); write(record,childElement,fields,parentsAlreadyConsidered, childrenToBeConsidered, templateFields); } os.write(helper.toString().getBytes()); } public void write(M record,T into, List<String> fields){ write(record,into,fields,new HashSet<>(), new HashMap<>()); } private boolean isParentIgnored(Class<? extends Model> parent, Set<String> ignoredParents) { return ignoredParents.contains(parent.getSimpleName()); } private final SWFLogger cat = Config.instance().getLogger(getClass().getName()); public Map<Class<? extends Model> , List<Class<? extends Model>>> getChildrenToConsider(Map<Class<? extends Model>, List<String>> templateFields){ Map<Class<? extends Model>,List<Class<? extends Model>>> considerChildren = new Cache<Class<? extends Model>, List<Class<? extends Model>>>() { @Override protected List<Class<? extends Model>> getValue(Class<? extends Model> aClass) { return new ArrayList<>(); } }; Set<String> modelClassesInTemplate = new HashSet<>(); if (templateFields != null){ for (Class<? extends Model> aClass : templateFields.keySet()) { modelClassesInTemplate.add(aClass.getSimpleName()); } } Stack<Class<? extends Model>> modelClasses = new Stack<>(); modelClasses.push(getBeanClass()); while (!modelClasses.isEmpty()){ Class<? extends Model> aModelClass = modelClasses.pop(); if (considerChildren.containsKey(aModelClass)){ continue; } ModelReflector<? extends Model> ref = ModelReflector.instance(aModelClass); for (Class<? extends Model> childModelClass : ref.getChildModels()){ considerChildren.get(aModelClass).add(childModelClass); if (modelClassesInTemplate.contains(childModelClass.getSimpleName())){ modelClasses.push(childModelClass); } } } return considerChildren; } public void write(M record,T into, List<String> fields, Set<Class<? extends Model>> parentsAlreadyConsidered , Map<Class<? extends Model>,List<String>> templateFields) { //Consider first level children. write(record,into,fields,parentsAlreadyConsidered,getChildrenToConsider(templateFields),templateFields); } public void write(M record,T into, List<String> fields, Set<Class<? extends Model>> parentsAlreadyConsidered , Map<Class<? extends Model>, List<Class<? extends Model>>> considerChildren, Map<Class<? extends Model>, List<String>> templateFields) { Set<String> simplifiedParentsConsidered = new HashSet<>(); parentsAlreadyConsidered.forEach(c->simplifiedParentsConsidered.add(c.getSimpleName())); Map<String,List<String>> simplifiedConsiderChildren = new Cache<String, List<String>>() { @Override protected List<String> getValue(String s) { return new SequenceSet<>(); } }; considerChildren.forEach((m,l)->{ for (Class<? extends Model> child: l){ simplifiedConsiderChildren.get(m.getSimpleName()).add(child.getSimpleName()); } }); Map<String,List<String>> simplifiedTemplateFields = new Cache<String, List<String>>() { @Override protected List<String> getValue(String s) { return new SequenceSet<>(); } }; templateFields.forEach((m,fl)->{ for (String f: fl != null ? fl : ModelReflector.instance(m).getVisibleFields()){ simplifiedTemplateFields.get(m.getSimpleName()).add(f); } }); writeSimplified(record,into,fields,simplifiedParentsConsidered,simplifiedConsiderChildren,simplifiedTemplateFields); } public void writeSimplified(M record,T into, List<String> fields, Set<String> parentsAlreadyConsidered , Map<String, List<String>> considerChildren, Map<String, List<String>> templateFields) { FormatHelper<T> formatHelper = FormatHelper.instance(into); ModelReflector<M> ref = getReflector(); for (String field: getFields(fields)){ Object value = TimerUtils.time(cat,"ref.get", ()-> ref.get(record, field)); if (value == null){ continue; } Method fieldGetter = TimerUtils.time(cat,"getFieldGetter" , () ->ref.getFieldGetter(field)); Method referredModelGetter = TimerUtils.time(cat,"getReferredModelGetterFor" , ()->ref.getReferredModelGetterFor(fieldGetter)); if (referredModelGetter != null){ Class<? extends Model> aParent = ref.getReferredModelClass(referredModelGetter); if (!isParentIgnored(aParent,parentsAlreadyConsidered) || fields != null) { String refElementName = referredModelGetter.getName().substring("get".length()); T refElement = formatHelper.createElementAttribute(refElementName); parentsAlreadyConsidered.add(aParent.getSimpleName()); try { write(aParent, ((Number) value).intValue(), refElement, parentsAlreadyConsidered, considerChildren,templateFields); }finally { parentsAlreadyConsidered.remove(aParent.getSimpleName()); } } }else { String attributeName = TimerUtils.time(cat,"getAttributeName()" , ()->getAttributeName(field)); String sValue = TimerUtils.time(cat, "toStringISO" , () -> Database.getJdbcTypeHelper(getReflector().getPool()).getTypeRef(fieldGetter.getReturnType()).getTypeConverter().toStringISO(value)); if (InputStream.class.isAssignableFrom(fieldGetter.getReturnType())) { formatHelper.setElementAttribute(attributeName,sValue); }else { TimerUtils.time(cat,"setAttribute" , ()-> { formatHelper.setAttribute(attributeName, sValue); return true; }); } } } TimerUtils.time(cat,"Writing all Children Objects",()->{ if (!templateFields.isEmpty()){ parentsAlreadyConsidered.add(ref.getModelClass().getSimpleName()); try { List<Method> childGetters = ref.getChildGetters(); for (Method childGetter : childGetters) { write(formatHelper,record,childGetter,parentsAlreadyConsidered,considerChildren,templateFields); } }finally { parentsAlreadyConsidered.remove(ref.getModelClass().getSimpleName()); } } return true; }); } private <R extends Model> boolean containsChild(Class<R> childModelClass, Collection<String> considerChildren){ return considerChildren != null && considerChildren.contains(childModelClass.getSimpleName()); } private <R extends Model> void write(FormatHelper<T> formatHelper, M record, Method childGetter, Set<String> parentsWritten , Map<String, List<String>> considerChildren, Map<String, List<String>> templateFields){ @SuppressWarnings("unchecked") Class<R> childModelClass = (Class<R>) getReflector().getChildModelClass(childGetter); if (!containsChild(childModelClass,considerChildren.get(getBeanClass().getSimpleName()))){ return; } if (!containsChild(childModelClass,templateFields.keySet())){ return; } ModelWriter<R,T> childWriter = ModelIOFactory.getWriter(childModelClass, getFormatClass()); try { @SuppressWarnings("unchecked") List<R> children = (List<R>)childGetter.invoke(record); List<String> fields = new ArrayList<>(); List<String> f = templateFields.get(childModelClass.getSimpleName()); if (f != null) { fields.addAll(f); } if (fields.isEmpty()){ fields = null; } Map<String,List<String>> newConsiderChilden = new HashMap<>(considerChildren); newConsiderChilden.remove(getBeanClass().getSimpleName()); //Don't print children of parent via children. !! Duplication. for (R child : children) { T childElement = formatHelper.createChildElement(childModelClass.getSimpleName()); childWriter.writeSimplified(child, childElement, fields, parentsWritten, newConsiderChilden, templateFields); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } private <R extends Model> void write(Class<R> referredModelClass, long id, T referredModelElement, Set<String> parentsAlreadyConsidered, Map<String, List<String>> considerChildren, Map<String, List<String>> templateFields){ Class<T> formatClass = getFormatClass(); ModelWriter<R,T> writer = ModelIOFactory.getWriter(referredModelClass,formatClass); R referredModel = Database.getTable(referredModelClass).get(id); if (referredModel == null){ return; } ModelReflector<R> referredModelReflector = ModelReflector.instance(referredModelClass); List<String> parentFieldsToAdd = referredModelReflector.getUniqueFields(); parentFieldsToAdd.removeIf(referredModelReflector::isFieldHidden); parentFieldsToAdd.add("ID"); if (templateFields != null){ List<String> parentFieldsToAddBasedOnTemplate = new SequenceSet<>(); if (templateFields.get(referredModelClass.getSimpleName()) != null) { //Never add parent class with null template. parentFieldsToAddBasedOnTemplate.addAll(getFields(referredModelReflector,templateFields.get(referredModelClass.getSimpleName()))); } if (!parentFieldsToAddBasedOnTemplate.isEmpty()){ parentFieldsToAdd.clear(); parentFieldsToAdd.addAll(parentFieldsToAddBasedOnTemplate); } } //* Which parent's children to include */ List<String> newChildModelsToConsider = new SequenceSet<>(); if (considerChildren != null){ newChildModelsToConsider = considerChildren.getOrDefault(referredModelClass.getSimpleName(),newChildModelsToConsider); } List<Class<? extends Model>> childModels = referredModelReflector.getChildModels(); Map<String, List<String>> newTemplateFields = null; if (templateFields != null){ newTemplateFields = new HashMap<>(templateFields); for (Class<? extends Model> childModelClass : childModels){ boolean keepChildModelClassInTemplate = newChildModelsToConsider.contains(childModelClass.getSimpleName()); if (!keepChildModelClassInTemplate){ newTemplateFields.remove(childModelClass.getSimpleName()); } } } writer.writeSimplified(referredModel , referredModelElement, parentFieldsToAdd, parentsAlreadyConsidered, considerChildren, newTemplateFields); } }
package ome.scifio.img; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import loci.formats.FormatTools; import net.imglib2.exception.ImgLibException; import net.imglib2.img.Img; import net.imglib2.img.ImgPlus; import net.imglib2.img.basictypeaccess.PlanarAccess; import net.imglib2.img.basictypeaccess.array.ArrayDataAccess; import net.imglib2.img.basictypeaccess.array.ByteArray; import net.imglib2.img.basictypeaccess.array.CharArray; import net.imglib2.img.basictypeaccess.array.DoubleArray; import net.imglib2.img.basictypeaccess.array.FloatArray; import net.imglib2.img.basictypeaccess.array.IntArray; import net.imglib2.img.basictypeaccess.array.LongArray; import net.imglib2.img.basictypeaccess.array.ShortArray; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.integer.ByteType; import net.imglib2.type.numeric.integer.IntType; import net.imglib2.type.numeric.integer.ShortType; import net.imglib2.type.numeric.integer.UnsignedByteType; import net.imglib2.type.numeric.integer.UnsignedIntType; import net.imglib2.type.numeric.integer.UnsignedShortType; import net.imglib2.type.numeric.real.DoubleType; import net.imglib2.type.numeric.real.FloatType; /** * Exception indicating something went wrong during I/O. * * @author Curtis Rueden */ public final class ImgIOUtils extends ImgLibException { private static final int BUFFER_SIZE = 256 * 1024; // 256K private ImgIOUtils() { // prevent instantiation of utility class } /** * Downloads the given URL and caches it to a temporary file, which is deleted * upon JVM shutdown. This is useful in conjuction with {@link ImgOpener} to * open a URL as an {@link Img}. * <p> * Data compressed with zip or gzip is supported. In the case of zip, the * first file in the archive is cached. * </p> */ public static String cacheId(final String urlPath) throws ImgIOException { InputStream in = null; OutputStream out = null; try { final URL url = new URL(urlPath); final String path = url.getPath(); final boolean zip = path.endsWith(".zip"); final boolean gz = path.endsWith(".gz"); String filename = path.substring(path.lastIndexOf("/") + 1); // save URL to temporary file ZipInputStream inZip = null; in = url.openStream(); if (zip) { in = inZip = new ZipInputStream(in); final ZipEntry zipEntry = inZip.getNextEntry(); filename = zipEntry.getName(); // use filename in the zip archive } if (gz) { in = new GZIPInputStream(in); filename = filename.substring(0, filename.length() - 3); // strip .gz } final int dot = filename.lastIndexOf("."); final String prefix = dot < 0 ? filename : filename.substring(0, dot); final String suffix = dot < 0 ? "" : "." + filename.substring(dot + 1); final File tmpFile = File.createTempFile(prefix + "-", suffix); tmpFile.deleteOnExit(); out = new FileOutputStream(tmpFile); final byte[] buf = new byte[BUFFER_SIZE]; while (true) { final int r = in.read(buf); if (r < 0) break; // eof out.write(buf, 0, r); } return tmpFile.getAbsolutePath(); } catch (IOException e) { throw new ImgIOException(e); } finally { try { if (in != null) in.close(); } catch (IOException e) { throw new ImgIOException(e); } try { if (out != null) out.close(); } catch (IOException e) { throw new ImgIOException(e); } } } /** Obtains planar access instance backing the given img, if any. */ @SuppressWarnings("unchecked") public static PlanarAccess<ArrayDataAccess<?>> getPlanarAccess( final ImgPlus<?> img) { if (img.getImg() instanceof PlanarAccess) { return (PlanarAccess<ArrayDataAccess<?>>) img.getImg(); } return null; } /** Converts Bio-Formats pixel type to imglib Type object. */ @SuppressWarnings("unchecked") public static <T extends RealType<T>> T makeType(final int pixelType) { final RealType<?> type; switch (pixelType) { case FormatTools.UINT8: type = new UnsignedByteType(); break; case FormatTools.INT8: type = new ByteType(); break; case FormatTools.UINT16: type = new UnsignedShortType(); break; case FormatTools.INT16: type = new ShortType(); break; case FormatTools.UINT32: type = new UnsignedIntType(); break; case FormatTools.INT32: type = new IntType(); break; case FormatTools.FLOAT: type = new FloatType(); break; case FormatTools.DOUBLE: type = new DoubleType(); break; default: type = null; } return (T) type; } /** Converts imglib Type object to Bio-Formats pixel type. */ public static <T extends RealType<T>> int makeType(final T type) { int pixelType = FormatTools.UINT8; if(type instanceof UnsignedByteType) { pixelType = FormatTools.UINT8; } else if(type instanceof ByteType) { pixelType = FormatTools.INT8; } else if(type instanceof UnsignedShortType) { pixelType = FormatTools.UINT16; } else if(type instanceof ShortType) { pixelType = FormatTools.INT16; } else if(type instanceof UnsignedIntType) { pixelType = FormatTools.UINT32; } else if(type instanceof IntType) { pixelType = FormatTools.INT32; } else if(type instanceof FloatType) { pixelType = FormatTools.FLOAT; } else if(type instanceof DoubleType) { pixelType = FormatTools.DOUBLE; } return pixelType; } /** Wraps raw primitive array in imglib Array object. */ public static ArrayDataAccess<?> makeArray(final Object array) { final ArrayDataAccess<?> access; if (array instanceof byte[]) { access = new ByteArray((byte[]) array); } else if (array instanceof char[]) { access = new CharArray((char[]) array); } else if (array instanceof double[]) { access = new DoubleArray((double[]) array); } else if (array instanceof int[]) { access = new IntArray((int[]) array); } else if (array instanceof float[]) { access = new FloatArray((float[]) array); } else if (array instanceof short[]) { access = new ShortArray((short[]) array); } else if (array instanceof long[]) { access = new LongArray((long[]) array); } else access = null; return access; } }
package fr.liglab.adele.cream.runtime.handler.behavior; import fr.liglab.adele.cream.annotations.behavior.Behavior; import fr.liglab.adele.cream.annotations.internal.BehaviorReference; import fr.liglab.adele.cream.runtime.internal.utils.SuccessorStrategy; import org.apache.felix.ipojo.*; import org.apache.felix.ipojo.annotations.Bind; import org.apache.felix.ipojo.annotations.Handler; import org.apache.felix.ipojo.annotations.Unbind; import org.apache.felix.ipojo.architecture.HandlerDescription; import org.apache.felix.ipojo.metadata.Element; import org.apache.felix.ipojo.util.Log; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Dictionary; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Handler(name = BehaviorReference.DEFAULT_BEHAVIOR_TYPE, namespace = BehaviorReference.BEHAVIOR_NAMESPACE) public class BehaviorHandler extends PrimitiveHandler implements InstanceStateListener,InvocationHandler { private final Map<String,RequiredBehavior> myRequiredBehaviorById = new ConcurrentHashMap<>(); @Override public void configure(Element metadata, Dictionary configuration) throws ConfigurationException { getInstanceManager().addInstanceStateListener(this); Element[] behaviorElements = metadata.getElements(BehaviorReference.DEFAULT_BEHAVIOR_TYPE,BehaviorReference.BEHAVIOR_NAMESPACE); for (Element element:behaviorElements){ myRequiredBehaviorById.put(element.getAttribute(BehaviorReference.ID_ATTR_NAME), new RequiredBehavior( element.getAttribute(BehaviorReference.SPEC_ATTR_NAME), element.getAttribute(BehaviorReference.IMPLEM_ATTR_NAME)) ); } } @Override public void stop() { } @Override public void start() { } /** * Issue : behavior must be deactivate before instance become Invalid ... */ @Override public void stateChanged(ComponentInstance instance, int newState) { if (newState == ComponentInstance.VALID){ for (Map.Entry<String,RequiredBehavior> behavior: myRequiredBehaviorById.entrySet()){ behavior.getValue().tryStartBehavior(); } } if (newState == ComponentInstance.INVALID){ for (Map.Entry<String,RequiredBehavior> behavior: myRequiredBehaviorById.entrySet()){ behavior.getValue().tryInvalid(); } } } @Bind(id = "behaviorF",specification = Factory.class,optional = true,proxy = false,aggregate = true,filter = "("+BehaviorReference.BEHAVIOR_TYPE_PROPERTY+"="+BehaviorReference.BEHAVIOR_TYPE+")") public void bindBehaviorFactory(Factory behaviorFactory, Map prop){ for (Map.Entry<String,RequiredBehavior> entry : myRequiredBehaviorById.entrySet()){ if (match(entry.getValue(),prop)){ entry.getValue().setFactory(behaviorFactory); entry.getValue().addManager(); if (getInstanceManager().getState() == ComponentInstance.VALID){ entry.getValue().tryStartBehavior(); } } } } @Unbind(id = "behaviorF") public void unbindBehaviorFactory(Factory behaviorFactory,Map prop){ for (Map.Entry<String,RequiredBehavior> entry : myRequiredBehaviorById.entrySet()){ if (match(entry.getValue(),prop)){ entry.getValue().unRef(); } } } private List<RequiredBehavior> getBehavior(Element metadata){ List<RequiredBehavior> behaviors = new ArrayList<>(); Element[] behaviorsElements = metadata.getElements(BehaviorReference.DEFAULT_BEHAVIOR_TYPE,BehaviorReference.BEHAVIOR_NAMESPACE); if (behaviorsElements == null) { return behaviors; } for (Element behavior : behaviorsElements){ String behaviorSpec = behavior.getAttribute(BehaviorReference.SPEC_ATTR_NAME); String behaviorImplem = behavior.getAttribute(BehaviorReference.IMPLEM_ATTR_NAME); if ((behaviorSpec == null) || (behaviorImplem == null)){ getLogger().log(Log.WARNING, "behavior spec or implem is null"); continue; } RequiredBehavior requiredBehavior = new RequiredBehavior(behaviorSpec,behaviorImplem); behaviors.add(requiredBehavior); } return behaviors; } protected boolean match(RequiredBehavior req, Map prop) { String spec = (String) prop.get(BehaviorReference.SPEC_ATTR_NAME); String impl = (String) prop.get(BehaviorReference.IMPLEM_ATTR_NAME); return req.getSpecName().equalsIgnoreCase(spec) && req.getImplName().equalsIgnoreCase(impl); } @Override public HandlerDescription getDescription() { return new BehaviorHandlerDescription(); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { for (Map.Entry<String,RequiredBehavior> behaviorEntry : myRequiredBehaviorById.entrySet()){ Object returnObj = behaviorEntry.getValue().invoke(proxy,method,args); if (SuccessorStrategy.NO_FOUND_CODE.equals(returnObj)){ continue; } return returnObj; } return SuccessorStrategy.NO_FOUND_CODE; } public class BehaviorHandlerDescription extends HandlerDescription { public BehaviorHandlerDescription(){ super(BehaviorHandler.this); } @Override public Element getHandlerInfo() { Element element = super.getHandlerInfo(); for (Map.Entry<String,RequiredBehavior> entry : myRequiredBehaviorById.entrySet()){ entry.getValue().getBehaviorDescription(element); } return element; } } }
package org.hisp.dhis.android.core.event; import org.hisp.dhis.android.core.D2; import org.hisp.dhis.android.core.common.D2Factory; import org.hisp.dhis.android.core.data.database.AbsStoreTestCase; import org.hisp.dhis.android.core.data.server.RealServerMother; import org.hisp.dhis.android.core.user.User; import org.junit.Before; import java.io.IOException; import java.util.List; import retrofit2.Response; import static com.google.common.truth.Truth.assertThat; public class EventWithLimitCallRealIntegrationShould extends AbsStoreTestCase { private D2 d2; @Before @Override public void setUp() throws IOException { super.setUp(); d2 = D2Factory.create(RealServerMother.url, databaseAdapter()); } //@Test public void download_tracked_entity_instances() throws Exception { d2.logout().call(); Response<User> loginResponse = d2.logIn(RealServerMother.user, RealServerMother.password).call(); assertThat(loginResponse.isSuccessful()).isTrue(); Response metadataResponse = d2.syncMetaData().call(); assertThat(metadataResponse.isSuccessful()).isTrue(); List<Event> events = d2.downloadSingleEvents(20, false).call(); assertThat(events.size()).isEqualTo(20); } }
package org.hisp.dhis.android.core.event; import org.hisp.dhis.android.core.D2; import org.hisp.dhis.android.core.common.D2Factory; import org.hisp.dhis.android.core.data.database.AbsStoreTestCase; import org.hisp.dhis.android.core.data.server.RealServerMother; import org.junit.Before; import org.junit.Test; import java.io.IOException; import static com.google.common.truth.Truth.assertThat; public class EventWithLimitCallRealIntegrationShould extends AbsStoreTestCase { private D2 d2; @Before @Override public void setUp() throws IOException { super.setUp(); d2 = D2Factory.create(RealServerMother.url, databaseAdapter()); } //@Test public void download_tracked_entity_instances() throws Exception { d2.logIn(RealServerMother.user, RealServerMother.password).call(); d2.syncMetaData().call(); d2.downloadSingleEvents(20, false).call(); assertThat(new EventStoreImpl(databaseAdapter()).queryAll().size()).isEqualTo(20); } }
package org.eclipse.birt.data.engine.expression; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.eclipse.birt.data.engine.api.aggregation.IAggregation; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.executor.BaseQuery; import org.eclipse.birt.data.engine.executor.transform.IExpressionProcessor; import org.eclipse.birt.data.engine.executor.transform.ResultSetPopulator; import org.eclipse.birt.data.engine.i18n.ResourceConstants; import org.eclipse.birt.data.engine.impl.aggregation.AggregateTable; import org.eclipse.birt.data.engine.odi.IQuery.GroupSpec; import org.mozilla.javascript.Context; import org.mozilla.javascript.Node; import org.mozilla.javascript.ScriptOrFnNode; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.Token; /** * This class handles the compilation of ROM JavaScript expressions of the * multiple pass level Each expression is compiled to generate a handle, which * is an instance of CompiledExpression or its derived class. The expression * handle is used by the factory to evaluate the expression after the report * query is executed. <br> * ExpressionProcessor compiles the expression into Rhino byte code for faster * evaluation at runtime. * */ class MultiPassExpressionCompiler extends AbstractExpressionCompiler { // the pass level of the expression private int totalPassLevel = 0; // the pass level of aggregate private int passLevel = 0; // the aggregate object list for compile private ArrayList aggrObjList = null; // contain the exprssions that can be calculated private List availableCmpList; // aggregate object that can be calculated private List caculatedAggregateList; private int currentGroupLevel, exprType; // aggregate table private AggregateTable table; private boolean hasAggregate = false; // whether the expression has nested aggregate private boolean hasNesetedAggregate = false; private Scriptable scope; private ResultSetPopulator rsPopulator; private final String ROW_INDICATOR = "row"; private final String TOTAL_OVERALL = "Total.OVERALL"; // this list to save the current group level if there is nested column // expression. it's last element always keep the newest group level. private List currentGroupLevelList = new ArrayList( ); private final static String AGGR_VALUE = "_temp_aggr_value"; private boolean useRsMetaData = true; private BaseQuery baseQuery; /** * ExpressionParseHelper to help user parse common expression. * * @param metaData */ public MultiPassExpressionCompiler( ResultSetPopulator rsPopulator, BaseQuery query, Scriptable scope, List availableAggrObj ) { this.rsPopulator = rsPopulator; this.baseQuery = query; this.scope = scope; this.hasAggregate = false; this.hasNesetedAggregate = false; this.caculatedAggregateList = availableAggrObj; aggrObjList = new ArrayList( ); } /** * * @param exprInfo * @param cx * @return */ public CompiledExpression compileExpression( ExpressionInfo exprInfo, Context cx ) { try { currentGroupLevel = exprInfo.getCurrentGroupLevel( ); exprType = exprInfo.getExprType( ); useRsMetaData = exprInfo.useCustomerChecked( ); CompiledExpression expr = compileExpression( exprInfo.getScriptExpression( ), cx ); return expr; } catch ( Exception e ) { DataException dataException = new DataException( ResourceConstants.INVALID_JS_EXPR, e, exprInfo.getScriptExpression( ).getText( ) ); return new InvalidExpression( dataException ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.data.engine.impl.AbstractExpressionParser#compileDirectColRefExpr(org.mozilla.javascript.Node, * boolean) */ CompiledExpression compileDirectColRefExpr( Node parent, Node refNode, Node grandfather, boolean customerChecked, Context context ) throws DataException { if ( ( refNode.getType( ) == Token.GETPROP || refNode.getType( ) == Token.GETELEM ) && ( !this.getDataSetMode( ) ) ) { String columnBindingName; if ( refNode.getFirstChild( ).getType( ) == Token.NAME && refNode.getLastChild( ).getType( ) == Token.STRING && refNode.getFirstChild( ) .getString( ) .equals( this.ROW_INDICATOR ) ) { { columnBindingName = refNode.getLastChild( ).getString( ); if ( columnBindingName != null && !columnBindingName.equals( "_outer" ) && !columnBindingName.equals( "__rownum" ) && !columnBindingName.equals( "0" ) ) { ScriptExpression expression = (ScriptExpression) this.rsPopulator.getEventHandler( ) .getBaseExpr( columnBindingName ); if ( expression == null ) throw new DataException( ResourceConstants.BAD_DATA_EXPRESSION ); currentGroupLevelList.add( expression.getGroupName( ) ); ScriptOrFnNode tree = parse( expression.getText( ), context ); CompiledExpression expr = null; if ( grandfather != null ) { if ( tree.getFirstChild( ) == tree.getLastChild( ) ) { grandfather.replaceChild( parent, tree.getFirstChild( ) ); expr = processChild( context, false, tree.getFirstChild( ), tree.getFirstChild( ).getFirstChild( ), grandfather ); } else { grandfather.replaceChild( grandfather.getFirstChild( ), tree.getFirstChild( ) ); grandfather.replaceChild( grandfather.getLastChild( ), tree.getLastChild( ) ); expr = this.compileComplexExpr( context, tree, false ); } } else { if ( tree.getFirstChild( ) == tree.getLastChild( ) ) { parent.replaceChild( refNode, tree.getFirstChild( ).getFirstChild( ) ); expr = processChild( context, false, parent, tree.getFirstChild( ).getFirstChild( ), grandfather ); } else { expr = this.compileComplexExpr( context, tree, false ); } } currentGroupLevelList.remove( currentGroupLevelList.size( ) - 1 ); if ( expr != null ) { if ( ( expr instanceof ColumnReferenceExpression ) ) { ( (ColumnReferenceExpression) expr ).setDataType( expression.getDataType( ) ); return expr; } return expr; } } } } } ColumnReferenceExpression expr = super.compileColRefExpr( refNode, customerChecked ); if ( customerChecked && expr != null ) { if ( expr.getColumnName( ) != null && expr.getColumnName( ).trim( ).length( ) > 0 ) checkAvailableCmpColumn( expr.getColumnName( ) ); } return expr; } /* * (non-Javadoc) * * @see org.eclipse.birt.data.engine.impl.AbstractExpressionParser#compileAggregateExpr(org.mozilla.javascript.Context, * org.mozilla.javascript.Node, org.mozilla.javascript.Node) */ AggregateExpression compileAggregateExpr( Context context, Node parent, Node callNode ) throws DataException { assert ( callNode.getType( ) == Token.CALL ); IAggregation aggregation = getAggregationFunction( callNode ); // not an aggregation function being called, then it's considered // a complex expression if ( aggregation == null ) { return null; } passLevel = 0; AggregateExpression aggregateExpression = new AggregateExpression( aggregation ); AggregateObject aggregateObj = new AggregateObject( aggregateExpression ); this.hasAggregate = true; extractArguments( context, aggregateExpression, callNode ); Iterator iter = aggregateExpression.getArguments( ).iterator( ); while ( iter.hasNext( ) ) { CompiledExpression argumentExpr = (CompiledExpression) iter.next( ); // the argument contains the nested aggregate expression if ( argumentExpr instanceof AggregateExpression ) { if ( canBeCalculated( new AggregateObject( (AggregateExpression) argumentExpr ) ) ) passLevel hasNesetedAggregate = true; // throw new DataException( // ResourceConstants.UNSUPPORTED_DIRECT_NESTED_AGGREGATE ); } else if ( argumentExpr instanceof ComplexExpression ) { flatternAggregateExpression( (ComplexExpression) argumentExpr ); } } // get the aggregate current group level currentGroupLevel = getCurrentGroupLevel( aggregateObj, context ); if ( exprType == IExpressionProcessor.GROUP_COLUMN_EXPR || exprType == IExpressionProcessor.FILTER_ON_GROUP_EXPR || exprType == IExpressionProcessor.SORT_ON_GROUP_EXPR ) { aggregateObj.setPassLevel( 1 ); } else aggregateObj.setPassLevel( ++passLevel ); int id = registerAggregate( aggregateObj ); if ( id >= 0 ) replaceAggregateNode( id, parent, callNode ); setTotalPassLevel( passLevel ); return aggregateExpression; } /** * Check the aggregate object on group,if the aggregate object's type is * GROUP_COLUMN_EXPR, its group level must be less than current group level. * if type is FILTER_ON_GROUP_EXPR, its group level must be equals to * current group level. if type is SORT_ON_GROUP_EXPR, its group level must * be less or equal with current group level. * * @param aggregateObj */ private int getCurrentGroupLevel( AggregateObject aggregateObj, Context context ) throws DataException { AggregateExpression expr = aggregateObj.getAggregateExpr( ); IAggregation aggr = expr.getAggregation( ); List argList = expr.getArguments( ); int nFixedArgs = aggr.getParameterDefn( ).length; int groupLevel = currentGroupLevel; // Verify that the expression has the right # of arguments int nArgs = argList.size( ); CompiledExpression groupExpr = null; if ( nArgs > nFixedArgs + 2 || nArgs < nFixedArgs ) { DataException e = new DataException( ResourceConstants.INVALID_AGGR_PARAMETER, expr.getAggregation( ).getName( ) ); throw e; } if ( nArgs == nFixedArgs + 2 ) { groupExpr = (CompiledExpression) argList.get( nArgs - 1 ); } if ( groupExpr != null && !( groupExpr instanceof ConstantExpression ) ) { DataException e = new DataException( ResourceConstants.INVALID_AGGR_GROUP_EXPRESSION, aggr.getName( ) ); throw e; } // evaluate group level Object groupLevelObj; Context cx = Context.enter( ); try { if ( groupExpr != null ) groupLevelObj = groupExpr.evaluate( cx, scope ); else { String currentGroupName = null; if ( this.currentGroupLevelList.size( ) == 0 ) currentGroupName = this.getScriptExpression( ) .getGroupName( ); else currentGroupName = this.currentGroupLevelList.get( this.currentGroupLevelList.size( ) - 1 ) .toString( ); if ( currentGroupName.equals( TOTAL_OVERALL ) ) groupLevelObj = new Integer( 0 ); else groupLevelObj = currentGroupName; } } finally { Context.exit( ); } if ( groupLevelObj == null ) { //do nothing } else if ( groupLevelObj instanceof String ) { int level = AggregationConstantsUtil.getGroupLevel( (String) groupLevelObj, currentGroupLevel, this.baseQuery.getGrouping( ) == null ? 0 : this.baseQuery.getGrouping( ).length, false ); // When the groupLevelObj can be recognized, it will return a // non-negative value.Else return -1. if ( level != -1 ) { groupLevel = level; } else { groupLevel = getGroupIndex( (String) groupLevelObj ); } } else if ( groupLevelObj instanceof Number ) { int offset = ( (Number) groupLevelObj ).intValue( ); if ( offset < 0 ) groupLevel = currentGroupLevel + offset; else groupLevel = offset; } switch ( exprType ) { case IExpressionProcessor.FILTER_ON_GROUP_EXPR : if ( groupLevel != currentGroupLevel ) { DataException e = new DataException( ResourceConstants.INVALID_GROUP_LEVEL, aggr.getName( ) ); throw e; } break; case IExpressionProcessor.SORT_ON_GROUP_EXPR : if ( groupLevel < 0 || groupLevel > currentGroupLevel ) { DataException e = new DataException( ResourceConstants.INVALID_GROUP_LEVEL, aggr.getName( ) ); throw e; } break; default : // TODO gourpLevel>= currentGorupLevel is also invalid if ( groupLevel < 0 ) { DataException e = new DataException( ResourceConstants.INVALID_GROUP_LEVEL, aggr.getName( ) ); throw e; } break; } return groupLevel; } /** * Return the index of group according to the given group text. * * @param groupText * @return The index of group */ private int getGroupIndex( String groupText ) { assert groupText != null; assert baseQuery != null; GroupSpec[] groups = baseQuery.getGrouping( ); for ( int i = 0; i < groups.length; i++ ) { GroupSpec group = groups[i]; if ( groupText.equals( group.getName( ) ) || groupText.equals( group.getKeyColumn( ) ) ) { return i + 1; // Note that group index is 1-based } } return -1; } /** * if the column field is custom field and it is not available, the total * pass level++ * * @param string * @throws DataException */ private void checkAvailableCmpColumn( String rowColumnName ) throws DataException { if ( !useRsMetaData || this.rsPopulator == null ) return; else if ( ( this.rsPopulator.getResultSetMetadata( ) == null || this.rsPopulator.getResultSetMetadata( ) .isCustomField( rowColumnName ) ) && ( this.availableCmpList == null || !this.availableCmpList.contains( rowColumnName ) ) ) { this.passLevel++; } } /** * get the expression total pass level * * @return */ int getExpressionPassLevel( ) { return this.totalPassLevel; } /** * parse the aggregate expression's arguments * * @param context * @param aggregateExpression * @param callNode * @throws DataException */ private void extractArguments( Context context, AggregateExpression aggregateExpression, Node callNode ) throws DataException { Node arg = callNode.getFirstChild( ).getNext( ); while ( arg != null ) { // need to hold on to the next argument because the tree extraction // will cause us to lose the reference otherwise Node nextArg = arg.getNext( ); CompiledExpression expr = processChild( context, true, callNode, arg, null ); if ( !( expr instanceof BytecodeExpression ) ) { aggregateExpression.addArgument( expr ); arg = nextArg; continue; } ScriptOrFnNode tree = new ScriptOrFnNode( Token.SCRIPT ); Node exprNode = new Node( Token.EXPR_RESULT ); exprNode.addChildToFront( arg ); tree.addChildrenToFront( exprNode ); if ( expr instanceof AggregateExpression ) { int registry = getRegisterId( new AggregateObject( (AggregateExpression) expr ) ); if ( registry >= 0 ) replaceAggregateNode( registry, exprNode, arg ); } compileForBytecodeExpr( context, tree, expr ); aggregateExpression.addArgument( expr ); arg = nextArg; } } /** * get the register id form aggregate object list * * @param obj1 * @return */ private int getRegisterId( AggregateObject obj1 ) { if ( this.aggrObjList == null ) return -1; else for ( int i = 0; i < this.aggrObjList.size( ); i++ ) { AggregateObject obj2 = (AggregateObject) this.aggrObjList.get( i ); if ( obj1.equals( obj2 ) ) return obj2.getRegisterId( ); } return -1; } /** * if the aggregate object is available, return true. * * @param aggregateObj * @return */ private boolean canBeCalculated( AggregateObject aggregateObj ) { if ( this.caculatedAggregateList == null ) return false; else { for ( int i = 0; i < this.caculatedAggregateList.size( ); i++ ) { AggregateObject obj = (AggregateObject) caculatedAggregateList.get( i ); if ( obj.equals( aggregateObj ) ) return true; } } return false; } /** * get the aggregate object list with pass level equals 'level'. * * @param level * @return */ List getAggregateList( int level ) { if ( this.aggrObjList == null ) return null; else { List levelList = new ArrayList( ); for ( int i = 0; i < this.aggrObjList.size( ); i++ ) { AggregateObject aggrObj = (AggregateObject) aggrObjList.get( i ); if ( aggrObj.getPassLevel( ) <= level && !aggrObj.isAvailable( ) ) levelList.add( aggrObj ); } return levelList; } } /** * if the agrument contains aggregate expression , return true. TODO * Unsupported direct nested aggregate * * @param expression * @return */ private void flatternAggregateExpression( ComplexExpression complexExpr ) throws DataException { Collection subExprs = complexExpr.getSubExpressions( ); Iterator iter = subExprs.iterator( ); while ( iter.hasNext( ) ) { CompiledExpression childExpr = (CompiledExpression) iter.next( ); if ( childExpr instanceof AggregateExpression ) { if ( canBeCalculated( new AggregateObject( (AggregateExpression) childExpr ) ) ) { passLevel return; } hasNesetedAggregate = true; // throw new DataException( ResourceConstants.UNSUPPORTED_DIRECT_NESTED_AGGREGATE ); } else if ( childExpr instanceof ComplexExpression ) { Collection childSubExprs = ( (ComplexExpression) childExpr ).getSubExpressions( ); Iterator childIter = childSubExprs.iterator( ); while ( childIter.hasNext( ) ) { CompiledExpression childChildExpr = (CompiledExpression) childIter.next( ); if ( childChildExpr instanceof AggregateExpression ) { if ( canBeCalculated( new AggregateObject( (AggregateExpression) childExpr ) ) ) { passLevel return; } } } } } } /** * register the aggregate object to aggrObjList and get the only id. * * @param aggregateObj * @return register id */ private int registerAggregate( AggregateObject aggregateObj ) throws DataException { if ( rsPopulator == null ) return -1; int index = -1; if ( table == null ) table = AggregationTablePopulator.createAggregateTable( baseQuery ); try { if ( aggregateObj.getPassLevel( ) <= 1 ) { index = AggregationTablePopulator.populateAggregationTable( table, aggregateObj, currentGroupLevel, false, false ); if ( aggrObjList == null ) { aggrObjList = new ArrayList( ); } aggregateObj.setRegisterId( index ); aggrObjList.add( aggregateObj ); } } catch ( DataException e ) { throw e; } return index; } /** * get aggregate table * * @return */ AggregateTable getAggregateTable( ) { return this.table; } /** * * @return */ boolean hasNestedAggregate( ) { return this.hasNesetedAggregate; } /** * set total pass level. the total pass level must be the max of passLevel * * @param passLevel */ private void setTotalPassLevel( int passLevel ) { if ( this.totalPassLevel < passLevel ) this.totalPassLevel = passLevel; else this.totalPassLevel = 0; } /** * if the computed column has been calculated, it will be added into * available list. * * @param name */ void addAvailableCmpColumn( String name ) { if ( this.availableCmpList == null ) availableCmpList = new ArrayList( ); availableCmpList.add( name ); } /** * get aggregate status, if has aggregate, return true. or return false * * @return */ public boolean getAggregateStatus( ) { return this.hasAggregate; } /** * replace the aggregate node with AGGR_VALUE <id> * * @param registry * @param aggregateExpression * @param parent * @param aggregateCallNode * @throws DataException */ private void replaceAggregateNode( int registry, Node parent, Node aggregateCallNode ) throws DataException { if ( registry < 0 ) throw new DataException( ResourceConstants.INVALID_CALL_AGGR ); int aggregateId = registry; Node newFirstChild = Node.newString( Token.NAME, AGGR_VALUE ); Node newSecondChild = Node.newNumber( aggregateId ); Node aggregateNode = new Node( Token.GETELEM, newFirstChild, newSecondChild ); parent.replaceChild( aggregateCallNode, aggregateNode ); } }
package org.hibernate.validator.internal.metadata.provider; import static org.hibernate.validator.internal.util.CollectionHelper.newArrayList; import static org.hibernate.validator.internal.util.CollectionHelper.newHashMap; import static org.hibernate.validator.internal.util.CollectionHelper.newHashSet; import static org.hibernate.validator.internal.util.ConcurrentReferenceHashMap.ReferenceType.SOFT; import static org.hibernate.validator.internal.util.logging.Messages.MESSAGES; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.reflect.AccessibleObject; import java.lang.reflect.AnnotatedArrayType; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.AnnotatedParameterizedType; import java.lang.reflect.AnnotatedType; import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.security.AccessController; import java.security.PrivilegedAction; 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.Set; import java.util.stream.Collectors; import javax.validation.GroupSequence; import javax.validation.Valid; import javax.validation.groups.ConvertGroup; import org.hibernate.validator.group.GroupSequenceProvider; import org.hibernate.validator.internal.engine.valueextraction.ArrayElement; import org.hibernate.validator.internal.engine.valueextraction.ValueExtractorManager; import org.hibernate.validator.internal.metadata.aggregated.CascadingMetaDataBuilder; import org.hibernate.validator.internal.metadata.core.AnnotationProcessingOptions; import org.hibernate.validator.internal.metadata.core.AnnotationProcessingOptionsImpl; import org.hibernate.validator.internal.metadata.core.ConstraintHelper; import org.hibernate.validator.internal.metadata.core.MetaConstraint; import org.hibernate.validator.internal.metadata.core.MetaConstraints; import org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl; import org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl.ConstraintType; import org.hibernate.validator.internal.metadata.location.ConstraintLocation; import org.hibernate.validator.internal.metadata.raw.BeanConfiguration; import org.hibernate.validator.internal.metadata.raw.ConfigurationSource; import org.hibernate.validator.internal.metadata.raw.ConstrainedElement; import org.hibernate.validator.internal.metadata.raw.ConstrainedExecutable; import org.hibernate.validator.internal.metadata.raw.ConstrainedField; import org.hibernate.validator.internal.metadata.raw.ConstrainedParameter; import org.hibernate.validator.internal.metadata.raw.ConstrainedType; import org.hibernate.validator.internal.util.CollectionHelper; import org.hibernate.validator.internal.util.ConcurrentReferenceHashMap; import org.hibernate.validator.internal.util.ExecutableHelper; import org.hibernate.validator.internal.util.ReflectionHelper; import org.hibernate.validator.internal.util.TypeResolutionHelper; import org.hibernate.validator.internal.util.logging.Log; import org.hibernate.validator.internal.util.logging.LoggerFactory; import org.hibernate.validator.internal.util.privilegedactions.GetDeclaredConstructors; import org.hibernate.validator.internal.util.privilegedactions.GetDeclaredFields; import org.hibernate.validator.internal.util.privilegedactions.GetDeclaredMethods; import org.hibernate.validator.internal.util.privilegedactions.GetMethods; import org.hibernate.validator.internal.util.privilegedactions.NewInstance; import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider; /** * {@code MetaDataProvider} which reads the metadata from annotations which is the default configuration source. * * @author Gunnar Morling * @author Hardy Ferentschik */ public class AnnotationMetaDataProvider implements MetaDataProvider { private static final Log log = LoggerFactory.make(); /** * The default initial capacity for this cache. */ static final int DEFAULT_INITIAL_CAPACITY = 16; protected final ConstraintHelper constraintHelper; protected final TypeResolutionHelper typeResolutionHelper; protected final ConcurrentReferenceHashMap<Class<?>, BeanConfiguration<?>> configuredBeans; protected final AnnotationProcessingOptions annotationProcessingOptions; protected final ValueExtractorManager valueExtractorManager; public AnnotationMetaDataProvider(ConstraintHelper constraintHelper, TypeResolutionHelper typeResolutionHelper, ValueExtractorManager valueExtractorManager, AnnotationProcessingOptions annotationProcessingOptions) { this.constraintHelper = constraintHelper; this.typeResolutionHelper = typeResolutionHelper; this.valueExtractorManager = valueExtractorManager; this.annotationProcessingOptions = annotationProcessingOptions; this.configuredBeans = new ConcurrentReferenceHashMap<>( DEFAULT_INITIAL_CAPACITY, SOFT, SOFT ); } @Override public AnnotationProcessingOptions getAnnotationProcessingOptions() { return new AnnotationProcessingOptionsImpl(); } @Override public <T> BeanConfiguration<T> getBeanConfiguration(Class<T> beanClass) { @SuppressWarnings("unchecked") BeanConfiguration<T> configuration = (BeanConfiguration<T>) configuredBeans. computeIfAbsent( beanClass, bc -> retrieveBeanConfiguration( beanClass ) ); return configuration; } /** * @param beanClass The bean class for which to retrieve the meta data * * @return Retrieves constraint related meta data from the annotations of the given type. */ private <T> BeanConfiguration<T> retrieveBeanConfiguration(Class<T> beanClass) { Set<ConstrainedElement> constrainedElements = getFieldMetaData( beanClass ); constrainedElements.addAll( getMethodMetaData( beanClass ) ); constrainedElements.addAll( getConstructorMetaData( beanClass ) ); //TODO GM: currently class level constraints are represented by a PropertyMetaData. This //works but seems somewhat unnatural Set<MetaConstraint<?>> classLevelConstraints = getClassLevelConstraints( beanClass ); if ( !classLevelConstraints.isEmpty() ) { ConstrainedType classLevelMetaData = new ConstrainedType( ConfigurationSource.ANNOTATION, beanClass, classLevelConstraints ); constrainedElements.add( classLevelMetaData ); } return new BeanConfiguration<>( ConfigurationSource.ANNOTATION, beanClass, constrainedElements, getDefaultGroupSequence( beanClass ), getDefaultGroupSequenceProvider( beanClass ) ); } private List<Class<?>> getDefaultGroupSequence(Class<?> beanClass) { GroupSequence groupSequenceAnnotation = beanClass.getAnnotation( GroupSequence.class ); return groupSequenceAnnotation != null ? Arrays.asList( groupSequenceAnnotation.value() ) : null; } private <T> DefaultGroupSequenceProvider<? super T> getDefaultGroupSequenceProvider(Class<T> beanClass) { GroupSequenceProvider groupSequenceProviderAnnotation = beanClass.getAnnotation( GroupSequenceProvider.class ); if ( groupSequenceProviderAnnotation != null ) { @SuppressWarnings("unchecked") Class<? extends DefaultGroupSequenceProvider<? super T>> providerClass = (Class<? extends DefaultGroupSequenceProvider<? super T>>) groupSequenceProviderAnnotation.value(); return newGroupSequenceProviderClassInstance( beanClass, providerClass ); } return null; } private <T> DefaultGroupSequenceProvider<? super T> newGroupSequenceProviderClassInstance(Class<T> beanClass, Class<? extends DefaultGroupSequenceProvider<? super T>> providerClass) { Method[] providerMethods = run( GetMethods.action( providerClass ) ); for ( Method method : providerMethods ) { Class<?>[] paramTypes = method.getParameterTypes(); if ( "getValidationGroups".equals( method.getName() ) && !method.isBridge() && paramTypes.length == 1 && paramTypes[0].isAssignableFrom( beanClass ) ) { return run( NewInstance.action( providerClass, "the default group sequence provider" ) ); } } throw log.getWrongDefaultGroupSequenceProviderTypeException( beanClass ); } private Set<MetaConstraint<?>> getClassLevelConstraints(Class<?> clazz) { if ( annotationProcessingOptions.areClassLevelConstraintsIgnoredFor( clazz ) ) { return Collections.emptySet(); } Set<MetaConstraint<?>> classLevelConstraints = newHashSet(); // HV-262 List<ConstraintDescriptorImpl<?>> classMetaData = findClassLevelConstraints( clazz ); ConstraintLocation location = ConstraintLocation.forClass( clazz ); for ( ConstraintDescriptorImpl<?> constraintDescription : classMetaData ) { classLevelConstraints.add( MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraintDescription, location ) ); } return classLevelConstraints; } private Set<ConstrainedElement> getFieldMetaData(Class<?> beanClass) { Set<ConstrainedElement> propertyMetaData = newHashSet(); for ( Field field : run( GetDeclaredFields.action( beanClass ) ) ) { // HV-172 if ( Modifier.isStatic( field.getModifiers() ) || annotationProcessingOptions.areMemberConstraintsIgnoredFor( field ) || field.isSynthetic() ) { continue; } propertyMetaData.add( findPropertyMetaData( field ) ); } return propertyMetaData; } private ConstrainedField findPropertyMetaData(Field field) { Set<MetaConstraint<?>> constraints = convertToMetaConstraints( findConstraints( field, ElementType.FIELD ), field ); CascadingMetaDataBuilder cascadingMetaDataBuilder = findCascadingMetaData( field ); Set<MetaConstraint<?>> typeArgumentsConstraints = findTypeAnnotationConstraints( field ); return new ConstrainedField( ConfigurationSource.ANNOTATION, field, constraints, typeArgumentsConstraints, cascadingMetaDataBuilder ); } private Set<MetaConstraint<?>> convertToMetaConstraints(List<ConstraintDescriptorImpl<?>> constraintDescriptors, Field field) { if ( constraintDescriptors.isEmpty() ) { return Collections.emptySet(); } Set<MetaConstraint<?>> constraints = newHashSet(); ConstraintLocation location = ConstraintLocation.forField( field ); for ( ConstraintDescriptorImpl<?> constraintDescription : constraintDescriptors ) { constraints.add( MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraintDescription, location ) ); } return constraints; } private Set<ConstrainedExecutable> getConstructorMetaData(Class<?> clazz) { Executable[] declaredConstructors = run( GetDeclaredConstructors.action( clazz ) ); return getMetaData( declaredConstructors ); } private Set<ConstrainedExecutable> getMethodMetaData(Class<?> clazz) { Executable[] declaredMethods = run( GetDeclaredMethods.action( clazz ) ); return getMetaData( declaredMethods ); } private Set<ConstrainedExecutable> getMetaData(Executable[] executableElements) { Set<ConstrainedExecutable> executableMetaData = newHashSet(); for ( Executable executable : executableElements ) { // HV-172; ignoring synthetic methods (inserted by the compiler), as they can't have any constraints // anyway and possibly hide the actual method with the same signature in the built meta model if ( Modifier.isStatic( executable.getModifiers() ) || executable.isSynthetic() ) { continue; } executableMetaData.add( findExecutableMetaData( executable ) ); } return executableMetaData; } /** * Finds all constraint annotations defined for the given method or constructor. * * @param executable The executable element to check for constraints annotations. * * @return A meta data object describing the constraints specified for the * given element. */ private ConstrainedExecutable findExecutableMetaData(Executable executable) { List<ConstrainedParameter> parameterConstraints = getParameterMetaData( executable ); Map<ConstraintType, List<ConstraintDescriptorImpl<?>>> executableConstraints = findConstraints( executable, ExecutableHelper.getElementType( executable ) ) .stream() .collect( Collectors.groupingBy( ConstraintDescriptorImpl::getConstraintType ) ); Set<MetaConstraint<?>> crossParameterConstraints; if ( annotationProcessingOptions.areCrossParameterConstraintsIgnoredFor( executable ) ) { crossParameterConstraints = Collections.emptySet(); } else { crossParameterConstraints = convertToMetaConstraints( executableConstraints.get( ConstraintType.CROSS_PARAMETER ), executable ); } Set<MetaConstraint<?>> returnValueConstraints; Set<MetaConstraint<?>> typeArgumentsConstraints; CascadingMetaDataBuilder cascadingMetaDataBuilder; if ( annotationProcessingOptions.areReturnValueConstraintsIgnoredFor( executable ) ) { returnValueConstraints = Collections.emptySet(); typeArgumentsConstraints = Collections.emptySet(); cascadingMetaDataBuilder = CascadingMetaDataBuilder.nonCascading(); } else { AnnotatedType annotatedReturnType = executable.getAnnotatedReturnType(); typeArgumentsConstraints = findTypeAnnotationConstraints( executable, annotatedReturnType ); returnValueConstraints = convertToMetaConstraints( executableConstraints.get( ConstraintType.GENERIC ), executable ); cascadingMetaDataBuilder = findCascadingMetaData( executable, annotatedReturnType ); } return new ConstrainedExecutable( ConfigurationSource.ANNOTATION, executable, parameterConstraints, crossParameterConstraints, returnValueConstraints, typeArgumentsConstraints, cascadingMetaDataBuilder ); } private Set<MetaConstraint<?>> convertToMetaConstraints(List<ConstraintDescriptorImpl<?>> constraintsDescriptors, Executable executable) { if ( constraintsDescriptors == null ) { return Collections.emptySet(); } Set<MetaConstraint<?>> constraints = newHashSet(); ConstraintLocation returnValueLocation = ConstraintLocation.forReturnValue( executable ); ConstraintLocation crossParameterLocation = ConstraintLocation.forCrossParameter( executable ); for ( ConstraintDescriptorImpl<?> constraintDescriptor : constraintsDescriptors ) { ConstraintLocation location = constraintDescriptor.getConstraintType() == ConstraintType.GENERIC ? returnValueLocation : crossParameterLocation; constraints.add( MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraintDescriptor, location ) ); } return constraints; } /** * Retrieves constraint related meta data for the parameters of the given * executable. * * @param executable The executable of interest. * @param parameters The parameters of the executable. * * @return A list with parameter meta data for the given executable. */ private List<ConstrainedParameter> getParameterMetaData(Executable executable) { if ( executable.getParameterCount() == 0 ) { return Collections.emptyList(); } Parameter[] parameters = executable.getParameters(); List<ConstrainedParameter> metaData = new ArrayList<>( parameters.length ); int i = 0; for ( Parameter parameter : parameters ) { Annotation[] parameterAnnotations; try { parameterAnnotations = parameter.getAnnotations(); } catch (ArrayIndexOutOfBoundsException ex) { log.warn( MESSAGES.constraintOnConstructorOfNonStaticInnerClass(), ex ); parameterAnnotations = new Annotation[0]; } Set<MetaConstraint<?>> parameterConstraints = newHashSet(); if ( annotationProcessingOptions.areParameterConstraintsIgnoredFor( executable, i ) ) { Type type = ReflectionHelper.typeOf( executable, i ); metaData.add( new ConstrainedParameter( ConfigurationSource.ANNOTATION, executable, type, i, parameterConstraints, Collections.emptySet(), CascadingMetaDataBuilder.nonCascading() ) ); i++; continue; } ConstraintLocation location = ConstraintLocation.forParameter( executable, i ); for ( Annotation parameterAnnotation : parameterAnnotations ) { // collect constraints if this annotation is a constraint annotation List<ConstraintDescriptorImpl<?>> constraints = findConstraintAnnotations( executable, parameterAnnotation, ElementType.PARAMETER ); for ( ConstraintDescriptorImpl<?> constraintDescriptorImpl : constraints ) { parameterConstraints.add( MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraintDescriptorImpl, location ) ); } } AnnotatedType parameterAnnotatedType = parameter.getAnnotatedType(); Set<MetaConstraint<?>> typeArgumentsConstraints = findTypeAnnotationConstraintsForExecutableParameter( executable, i, parameterAnnotatedType ); CascadingMetaDataBuilder cascadingMetaData = findCascadingMetaData( executable, parameters, i, parameterAnnotatedType ); metaData.add( new ConstrainedParameter( ConfigurationSource.ANNOTATION, executable, ReflectionHelper.typeOf( executable, i ), i, parameterConstraints, typeArgumentsConstraints, cascadingMetaData ) ); i++; } return metaData; } /** * Finds all constraint annotations defined for the given member and returns them in a list of * constraint descriptors. * * @param member The member to check for constraints annotations. * @param type The element type the constraint/annotation is placed on. * * @return A list of constraint descriptors for all constraint specified for the given member. */ private List<ConstraintDescriptorImpl<?>> findConstraints(Member member, ElementType type) { List<ConstraintDescriptorImpl<?>> metaData = newArrayList(); for ( Annotation annotation : ( (AccessibleObject) member ).getDeclaredAnnotations() ) { metaData.addAll( findConstraintAnnotations( member, annotation, type ) ); } return metaData; } /** * Finds all constraint annotations defined for the given class and returns them in a list of * constraint descriptors. * * @param beanClass The class to check for constraints annotations. * * @return A list of constraint descriptors for all constraint specified on the given class. */ private List<ConstraintDescriptorImpl<?>> findClassLevelConstraints(Class<?> beanClass) { List<ConstraintDescriptorImpl<?>> metaData = newArrayList(); for ( Annotation annotation : beanClass.getDeclaredAnnotations() ) { metaData.addAll( findConstraintAnnotations( null, annotation, ElementType.TYPE ) ); } return metaData; } /** * Examines the given annotation to see whether it is a single- or multi-valued constraint annotation. * * @param member The member to check for constraints annotations * @param annotation The annotation to examine * @param type the element type on which the annotation/constraint is placed on * @param <A> the annotation type * * @return A list of constraint descriptors or the empty list in case {@code annotation} is neither a * single nor multi-valued annotation. */ protected <A extends Annotation> List<ConstraintDescriptorImpl<?>> findConstraintAnnotations(Member member, A annotation, ElementType type) { // HV-1049 and HV-1311 - Ignore annotations from the JDK (jdk.internal.* and java.*); They cannot be constraint // "jdk.internal" and "java". if ( constraintHelper.isJdkAnnotation( annotation.annotationType() ) ) { return Collections.emptyList(); } List<Annotation> constraints = newArrayList(); Class<? extends Annotation> annotationType = annotation.annotationType(); if ( constraintHelper.isConstraintAnnotation( annotationType ) ) { constraints.add( annotation ); } else if ( constraintHelper.isMultiValueConstraint( annotationType ) ) { constraints.addAll( constraintHelper.getConstraintsFromMultiValueConstraint( annotation ) ); } return constraints.stream() .map( c -> buildConstraintDescriptor( member, c, type ) ) .collect( Collectors.toList() ); } private Map<Class<?>, Class<?>> getGroupConversions(AnnotatedElement annotatedElement) { return getGroupConversions( annotatedElement.getAnnotation( ConvertGroup.class ), annotatedElement.getAnnotation( ConvertGroup.List.class ) ); } private Map<Class<?>, Class<?>> getGroupConversions(ConvertGroup groupConversion, ConvertGroup.List groupConversionList) { Map<Class<?>, Class<?>> groupConversions = newHashMap(); if ( groupConversion != null ) { groupConversions.put( groupConversion.from(), groupConversion.to() ); } if ( groupConversionList != null ) { for ( ConvertGroup conversion : groupConversionList.value() ) { if ( groupConversions.containsKey( conversion.from() ) ) { throw log.getMultipleGroupConversionsForSameSourceException( conversion.from(), CollectionHelper.<Class<?>>asSet( groupConversions.get( conversion.from() ), conversion.to() ) ); } groupConversions.put( conversion.from(), conversion.to() ); } } return groupConversions; } private <A extends Annotation> ConstraintDescriptorImpl<A> buildConstraintDescriptor(Member member, A annotation, ElementType type) { return new ConstraintDescriptorImpl<>( constraintHelper, member, annotation, type ); } /** * Runs the given privileged action, using a privileged block if required. * <p> * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ private <T> T run(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); } /** * Finds type arguments constraints for fields. */ protected Set<MetaConstraint<?>> findTypeAnnotationConstraints(Field field) { return findTypeArgumentsConstraints( field, new TypeArgumentFieldLocation( field ), field.getAnnotatedType() ); } /** * Finds type arguments constraints for method return values. */ protected Set<MetaConstraint<?>> findTypeAnnotationConstraints(Executable executable, AnnotatedType annotatedReturnType) { return findTypeArgumentsConstraints( executable, new TypeArgumentReturnValueLocation( executable ), annotatedReturnType ); } private CascadingMetaDataBuilder findCascadingMetaData(Executable executable, Parameter[] parameters, int i, AnnotatedType parameterAnnotatedType) { Parameter parameter = parameters[i]; TypeVariable<?>[] typeParameters = parameter.getType().getTypeParameters(); Map<TypeVariable<?>, CascadingMetaDataBuilder> containerElementTypesCascadingMetaData = getTypeParametersCascadingMetadata( parameterAnnotatedType, typeParameters ); try { return getCascadingMetaData( ReflectionHelper.typeOf( parameter.getDeclaringExecutable(), i ), parameter, containerElementTypesCascadingMetaData ); } catch (ArrayIndexOutOfBoundsException ex) { log.warn( MESSAGES.constraintOnConstructorOfNonStaticInnerClass(), ex ); return CascadingMetaDataBuilder.nonCascading(); } } private CascadingMetaDataBuilder findCascadingMetaData(Field field) { TypeVariable<?>[] typeParameters = field.getType().getTypeParameters(); AnnotatedType annotatedType = field.getAnnotatedType(); Map<TypeVariable<?>, CascadingMetaDataBuilder> containerElementTypesCascadingMetaData = getTypeParametersCascadingMetadata( annotatedType, typeParameters ); return getCascadingMetaData( ReflectionHelper.typeOf( field ), field, containerElementTypesCascadingMetaData ); } private CascadingMetaDataBuilder findCascadingMetaData(Executable executable, AnnotatedType annotatedReturnType) { TypeVariable<?>[] typeParameters; if ( executable instanceof Method ) { typeParameters = ( (Method) executable ).getReturnType().getTypeParameters(); } else { typeParameters = ( (Constructor<?>) executable ).getDeclaringClass().getTypeParameters(); } Map<TypeVariable<?>, CascadingMetaDataBuilder> containerElementTypesCascadingMetaData = getTypeParametersCascadingMetadata( annotatedReturnType, typeParameters ); return getCascadingMetaData( ReflectionHelper.typeOf( executable ), executable, containerElementTypesCascadingMetaData ); } private Map<TypeVariable<?>, CascadingMetaDataBuilder> getTypeParametersCascadingMetadata(AnnotatedType annotatedType, TypeVariable<?>[] typeParameters) { if ( annotatedType instanceof AnnotatedArrayType ) { return getTypeParametersCascadingMetaDataForArrayType( (AnnotatedArrayType) annotatedType ); } else if ( annotatedType instanceof AnnotatedParameterizedType ) { return getTypeParametersCascadingMetaDataForParameterizedType( (AnnotatedParameterizedType) annotatedType, typeParameters ); } else { return Collections.emptyMap(); } } private Map<TypeVariable<?>, CascadingMetaDataBuilder> getTypeParametersCascadingMetaDataForParameterizedType( AnnotatedParameterizedType annotatedParameterizedType, TypeVariable<?>[] typeParameters) { Map<TypeVariable<?>, CascadingMetaDataBuilder> typeParametersCascadingMetadata = CollectionHelper.newHashMap( typeParameters.length ); AnnotatedType[] annotatedTypeArguments = annotatedParameterizedType.getAnnotatedActualTypeArguments(); int i = 0; for ( AnnotatedType annotatedTypeArgument : annotatedTypeArguments ) { Map<TypeVariable<?>, CascadingMetaDataBuilder> nestedTypeParametersCascadingMetadata = getTypeParametersCascadingMetaDataForAnnotatedType( annotatedTypeArgument ); typeParametersCascadingMetadata.put( typeParameters[i], new CascadingMetaDataBuilder( annotatedParameterizedType.getType(), typeParameters[i], annotatedTypeArgument.isAnnotationPresent( Valid.class ), nestedTypeParametersCascadingMetadata, getGroupConversions( annotatedTypeArgument ) ) ); i++; } return typeParametersCascadingMetadata; } private Map<TypeVariable<?>, CascadingMetaDataBuilder> getTypeParametersCascadingMetaDataForArrayType(AnnotatedArrayType annotatedArrayType) { // HV-1428 Container element support is disabled for arrays return Collections.emptyMap(); // Map<TypeVariable<?>, CascadingTypeParameter> typeParametersCascadingMetadata = CollectionHelper.newHashMap( 1 ); // AnnotatedType containerElementAnnotatedType = annotatedArrayType.getAnnotatedGenericComponentType(); // Map<TypeVariable<?>, CascadingTypeParameter> nestedTypeParametersCascadingMetadata = getTypeParametersCascadingMetaDataForAnnotatedType( // containerElementAnnotatedType ); // TypeVariable<?> arrayElement = new ArrayElement( annotatedArrayType ); // typeParametersCascadingMetadata.put( arrayElement, new CascadingTypeParameter( annotatedArrayType.getType(), // arrayElement, // annotatedArrayType.isAnnotationPresent( Valid.class ), // nestedTypeParametersCascadingMetadata, // getGroupConversions( annotatedArrayType ) ) ); // return typeParametersCascadingMetadata; } private Map<TypeVariable<?>, CascadingMetaDataBuilder> getTypeParametersCascadingMetaDataForAnnotatedType(AnnotatedType annotatedType) { if ( annotatedType instanceof AnnotatedArrayType ) { return getTypeParametersCascadingMetaDataForArrayType( (AnnotatedArrayType) annotatedType ); } else if ( annotatedType instanceof AnnotatedParameterizedType ) { return getTypeParametersCascadingMetaDataForParameterizedType( (AnnotatedParameterizedType) annotatedType, ReflectionHelper.getClassFromType( annotatedType.getType() ).getTypeParameters() ); } else { return Collections.emptyMap(); } } /** * Finds type arguments constraints for parameters. * * @param executable the executable * @param i the parameter index * * @return a set of type arguments constraints, or an empty set if no constrained type arguments are found */ protected Set<MetaConstraint<?>> findTypeAnnotationConstraintsForExecutableParameter(Executable executable, int i, AnnotatedType parameterAnnotatedType) { try { return findTypeArgumentsConstraints( executable, new TypeArgumentExecutableParameterLocation( executable, i ), parameterAnnotatedType ); } catch (ArrayIndexOutOfBoundsException ex) { log.warn( MESSAGES.constraintOnConstructorOfNonStaticInnerClass(), ex ); return Collections.emptySet(); } } private Set<MetaConstraint<?>> findTypeArgumentsConstraints(Member member, TypeArgumentLocation location, AnnotatedType annotatedType) { // HV-1428 Container element support is disabled for arrays if ( !(annotatedType instanceof AnnotatedParameterizedType) ) { return Collections.emptySet(); } Set<MetaConstraint<?>> typeArgumentConstraints = new HashSet<>(); // if we have an array, we need to unwrap the array first if ( annotatedType instanceof AnnotatedArrayType ) { AnnotatedArrayType annotatedArrayType = (AnnotatedArrayType) annotatedType; Type validatedType = annotatedArrayType.getAnnotatedGenericComponentType().getType(); TypeVariable<?> arrayElementTypeArgument = new ArrayElement( annotatedArrayType ); typeArgumentConstraints.addAll( findTypeUseConstraints( member, annotatedArrayType, arrayElementTypeArgument, location, validatedType ) ); typeArgumentConstraints.addAll( findTypeArgumentsConstraints( member, new NestedTypeArgumentLocation( location, arrayElementTypeArgument, validatedType ), annotatedArrayType.getAnnotatedGenericComponentType() ) ); } else if ( annotatedType instanceof AnnotatedParameterizedType ) { AnnotatedParameterizedType annotatedParameterizedType = (AnnotatedParameterizedType) annotatedType; int i = 0; for ( TypeVariable<?> typeVariable : ReflectionHelper.getClassFromType( annotatedType.getType() ).getTypeParameters() ) { AnnotatedType annotatedTypeParameter = annotatedParameterizedType.getAnnotatedActualTypeArguments()[i]; // HV-925 // We need to determine the validated type used for constraint validator resolution. // Iterables and maps need special treatment at this point, since the validated type is the type of the // specified type parameter. In the other cases the validated type is the parameterized type, eg Optional<String>. // In the latter case a value unwrapping has to occur Type validatedType = annotatedTypeParameter.getType(); typeArgumentConstraints.addAll( findTypeUseConstraints( member, annotatedTypeParameter, typeVariable, location, validatedType ) ); if ( validatedType instanceof ParameterizedType ) { typeArgumentConstraints.addAll( findTypeArgumentsConstraints( member, new NestedTypeArgumentLocation( location, typeVariable, validatedType ), annotatedTypeParameter ) ); } i++; } } return typeArgumentConstraints.isEmpty() ? Collections.emptySet() : typeArgumentConstraints; } /** * Finds type use annotation constraints defined on the type argument. */ private Set<MetaConstraint<?>> findTypeUseConstraints(Member member, AnnotatedType typeArgument, TypeVariable<?> typeVariable, TypeArgumentLocation location, Type type) { Set<MetaConstraint<?>> constraints = Arrays.stream( typeArgument.getAnnotations() ) .flatMap( a -> findConstraintAnnotations( member, a, ElementType.TYPE_USE ).stream() ) .map( d -> createTypeArgumentMetaConstraint( d, location, typeVariable, type ) ) .collect( Collectors.toSet() ); return constraints; } /** * Creates a {@code MetaConstraint} for a type argument constraint. */ private <A extends Annotation> MetaConstraint<?> createTypeArgumentMetaConstraint(ConstraintDescriptorImpl<A> descriptor, TypeArgumentLocation location, TypeVariable<?> typeVariable, Type type) { ConstraintLocation constraintLocation = ConstraintLocation.forTypeArgument( location.toConstraintLocation(), typeVariable, type ); return MetaConstraints.create( typeResolutionHelper, valueExtractorManager, descriptor, constraintLocation ); } private CascadingMetaDataBuilder getCascadingMetaData(Type type, AnnotatedElement annotatedElement, Map<TypeVariable<?>, CascadingMetaDataBuilder> containerElementTypesCascadingMetaData) { return CascadingMetaDataBuilder.annotatedObject( type, annotatedElement.isAnnotationPresent( Valid.class ), containerElementTypesCascadingMetaData, getGroupConversions( annotatedElement ) ); } /** * The location of a type argument before it is really considered a constraint location. * <p> * It avoids initializing a constraint location if we did not find any constraints. This is especially useful in * a Java 9 environment as {@link ConstraintLocation#forProperty(Member) tries to make the {@code Member} accessible * which might not be possible (for instance for {@code java.util} classes). */ private interface TypeArgumentLocation { ConstraintLocation toConstraintLocation(); } private static class TypeArgumentExecutableParameterLocation implements TypeArgumentLocation { private final Executable executable; private final int index; private TypeArgumentExecutableParameterLocation(Executable executable, int index) { this.executable = executable; this.index = index; } @Override public ConstraintLocation toConstraintLocation() { return ConstraintLocation.forParameter( executable, index ); } } private static class TypeArgumentFieldLocation implements TypeArgumentLocation { private final Field field; private TypeArgumentFieldLocation(Field field) { this.field = field; } @Override public ConstraintLocation toConstraintLocation() { return ConstraintLocation.forField( field ); } } private static class TypeArgumentReturnValueLocation implements TypeArgumentLocation { private final Executable executable; private TypeArgumentReturnValueLocation(Executable executable) { this.executable = executable; } @Override public ConstraintLocation toConstraintLocation() { return ConstraintLocation.forReturnValue( executable ); } } private static class NestedTypeArgumentLocation implements TypeArgumentLocation { private final TypeArgumentLocation parentLocation; private final TypeVariable<?> typeParameter; private final Type typeOfAnnotatedElement; private NestedTypeArgumentLocation(TypeArgumentLocation parentLocation, TypeVariable<?> typeParameter, Type typeOfAnnotatedElement) { this.parentLocation = parentLocation; this.typeParameter = typeParameter; this.typeOfAnnotatedElement = typeOfAnnotatedElement; } @Override public ConstraintLocation toConstraintLocation() { return ConstraintLocation.forTypeArgument( parentLocation.toConstraintLocation(), typeParameter, typeOfAnnotatedElement ); } } }
package org.jboss.weld.environment.servlet.test.el; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.runner.RunWith; import static org.jboss.weld.environment.servlet.test.util.JettyDeployments.JETTY_ENV; /** * @author Ales Justin */ @RunWith(Arquillian.class) public class JsfTest extends JsfTestBase { @Deployment(testable = false) public static WebArchive deployment() { return JsfTestBase.deployment().addAsWebInfResource(JETTY_ENV, "jetty-env.xml"); } }
package com.intuso.housemate.extension.android.widget; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.widget.RemoteViews; import android.widget.Toast; import com.google.common.collect.HashBiMap; import com.google.common.collect.Sets; import com.intuso.housemate.api.comms.ApplicationInstanceStatus; import com.intuso.housemate.api.comms.ApplicationStatus; import com.intuso.housemate.api.comms.ServerConnectionStatus; import com.intuso.housemate.api.comms.access.ApplicationDetails; import com.intuso.housemate.api.object.HousemateObject; import com.intuso.housemate.api.object.realclient.RealClient; import com.intuso.housemate.api.object.root.RootListener; import com.intuso.housemate.extension.android.widget.handler.WidgetHandler; import com.intuso.housemate.object.proxy.LoadManager; import com.intuso.housemate.object.proxy.ProxyRoot; import com.intuso.housemate.object.proxy.simple.ProxyClientHelper; import com.intuso.housemate.platform.android.app.HousemateService; import com.intuso.housemate.platform.android.app.object.AndroidProxyRoot; public class WidgetService extends HousemateService { public static enum Status { NO_NETWORK, NOT_CONNECTED, NOT_ALLOWED, NOT_LOADED, LOADED } public final static String NETWORK_AVAILABLE_ACTION = "networkAvailable"; public final static String NETWORK_AVAILABLE = "networkAvailable"; private final static String DELETE_WIDGETS_ACTION = "deleteWidgets"; private final static String PERFORM_COMMAND_ACTION = "performCommand"; private final static String WIDGET_ID = "widgetId"; private final static String ACTION = "action"; private final static String PROPERTY_PREFIX = "android.widget."; private final static String PROPERTY_VALUE_DELIMITER = "___"; public final static ApplicationDetails APPLICATION_DETAILS = new ApplicationDetails(WidgetService.class.getName(), "Android Widgets", "Android Widgets"); private final Binder binder = new Binder(); private final HashBiMap<Integer, WidgetHandler<?>> widgetHandlers = HashBiMap.create(); private ProxyClientHelper<AndroidProxyRoot> clientHelper; private AppWidgetManager appWidgetManager; private Status status = Status.NOT_CONNECTED; private boolean networkAvailable = true; public static void deleteWidgets(Context context, int[] widgetIds) { Intent intent = new Intent(context, WidgetService.class); intent.setAction(DELETE_WIDGETS_ACTION); intent.putExtra(WIDGET_ID, widgetIds); context.startService(intent); } public synchronized PendingIntent makePendingIntent(WidgetHandler widgetHandler, String action) { int widgetId = widgetHandlers.inverse().get(widgetHandler); Intent intent = new Intent(getApplicationContext(), WidgetService.class); intent.setAction(PERFORM_COMMAND_ACTION); intent.putExtra(WIDGET_ID, widgetId); intent.putExtra(ACTION, action); return PendingIntent.getService(getApplicationContext(), widgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT); } public AndroidProxyRoot getRoot() { return clientHelper.getRoot(); } @Override public void onCreate() { super.onCreate(); appWidgetManager = AppWidgetManager.getInstance(getApplicationContext()); clientHelper = ProxyClientHelper.newClientHelper(getLog(), new AndroidProxyRoot(getLog(), getListenersFactory(), getProperties(), getRouter()), getRouter()) .applicationDetails(APPLICATION_DETAILS) .component(WidgetService.class.getName()) .load(ProxyRoot.REAL_CLIENTS_ID, HousemateObject.EVERYTHING, RealClient.DEVICES_ID) .callback(new LoadManager.Callback() { @Override public void failed(HousemateObject.TreeLoadInfo path) { updateStatus(); } @Override public void allLoaded() { updateStatus(); } }); clientHelper.getRoot().addObjectListener(new RootListener<AndroidProxyRoot>() { @Override public void serverConnectionStatusChanged(AndroidProxyRoot root, ServerConnectionStatus serverConnectionStatus) { updateStatus(); } @Override public void applicationStatusChanged(AndroidProxyRoot root, ApplicationStatus applicationStatus) { updateStatus(); } @Override public void applicationInstanceStatusChanged(AndroidProxyRoot root, ApplicationInstanceStatus applicationInstanceStatus) { updateStatus(); } @Override public void newApplicationInstance(AndroidProxyRoot root, String instanceId) { // do nothing } @Override public void newServerInstance(AndroidProxyRoot root, String serverId) { // do nothing } }); clientHelper.start(); for(String key : Sets.newHashSet(getProperties().keySet())) { if (key.startsWith(PROPERTY_PREFIX)) { String encodedWidget = getProperties().get(key); getLog().d("Loading widget from " + encodedWidget); WidgetHandler<?> widgetHandler = decodePropertyValue(encodedWidget); if(widgetHandler != null) { getLog().d("Decoded widget to a " + widgetHandler.getClass().getName()); addWidgetHandler(Integer.parseInt(key.substring(PROPERTY_PREFIX.length())), widgetHandler); } else { getLog().d("Decoding widget config failed, removing property"); getProperties().remove(key); } } } } private void updateStatus() { Status oldStatus = status; if(!networkAvailable) status = Status.NO_NETWORK; else if(getRouter().getServerConnectionStatus() != ServerConnectionStatus.ConnectedToServer && getRouter().getServerConnectionStatus() != ServerConnectionStatus.DisconnectedTemporarily) status = Status.NOT_CONNECTED; else if(getRoot().getApplicationInstanceStatus() != ApplicationInstanceStatus.Allowed) status = Status.NOT_ALLOWED; else if(getRoot().getRealClients() == null) status = Status.NOT_LOADED; else status = Status.LOADED; if(oldStatus != status) for(WidgetHandler<?> widgetHandler : widgetHandlers.values()) widgetHandler.setServiceStatus(status); } @Override public void onDestroy() { if(clientHelper != null) { clientHelper.stop(); clientHelper = null; } super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return binder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); if(intent != null && DELETE_WIDGETS_ACTION.equals(intent.getAction())) { for(int widgetId : intent.getIntArrayExtra(WIDGET_ID)) { getProperties().remove(PROPERTY_PREFIX + widgetId); widgetHandlers.remove(widgetId); } } else if(intent != null && PERFORM_COMMAND_ACTION.equals(intent.getAction())) { if(status == Status.LOADED) { int widgetId = intent.getIntExtra(WIDGET_ID, -1); WidgetHandler widgetHandler = widgetHandlers.get(widgetId); if (widgetHandler == null) Toast.makeText(getApplicationContext(), "Unknown widget, please recreate it", Toast.LENGTH_SHORT).show(); else if(widgetHandler.getStatus() != WidgetHandler.Status.READY) Toast.makeText(getApplicationContext(), "Device/feature is not loaded. Please retry later", Toast.LENGTH_SHORT).show(); else widgetHandler.handleAction(intent.getStringExtra(ACTION)); } else Toast.makeText(getApplicationContext(), "Not currently connected to server. Please retry later", Toast.LENGTH_SHORT).show(); } else if(intent != null && NETWORK_AVAILABLE_ACTION.equals(intent.getAction())) { if(intent.getExtras().containsKey(NETWORK_AVAILABLE)) { getLog().d("Received network available update: " + intent.getBooleanExtra(NETWORK_AVAILABLE, true)); networkAvailable = intent.getBooleanExtra(NETWORK_AVAILABLE, true); updateStatus(); } } return START_STICKY; } private void addNewWidgetHandler(int widgetId, WidgetHandler<?> widgetHandler) { getProperties().set(PROPERTY_PREFIX + widgetId, encodePropertyValue(widgetHandler)); addWidgetHandler(widgetId, widgetHandler); } private void addWidgetHandler(int widgetId, WidgetHandler<?> widgetHandler) { widgetHandlers.put(widgetId, widgetHandler); widgetHandler.setServiceStatus(status); } public void updateAppWidget(WidgetHandler<?> widgetHandler, RemoteViews views) { appWidgetManager.updateAppWidget(widgetHandlers.inverse().get(widgetHandler), views); } private String encodePropertyValue(WidgetHandler<?> widgetHandler) { return widgetHandler.getClientId() + PROPERTY_VALUE_DELIMITER + widgetHandler.getDeviceId() + PROPERTY_VALUE_DELIMITER + widgetHandler.getFeatureId(); } private WidgetHandler<?> decodePropertyValue(String value) { String[] parts = value.split(PROPERTY_VALUE_DELIMITER); if(parts.length != 3) return null; return WidgetHandler.createFeatureWidget(this, parts[0], parts[1], parts[2]); } public class Binder extends android.os.Binder { public void addWidget(int widgetId, String clientId, String deviceId, String featureId) { addNewWidgetHandler(widgetId, WidgetHandler.createFeatureWidget(WidgetService.this, clientId, deviceId, featureId)); } } }
package org.eclipse.persistence.expressions; import java.security.AccessController; import java.security.PrivilegedActionException; import java.util.*; import java.io.*; import org.eclipse.persistence.internal.expressions.*; import org.eclipse.persistence.internal.helper.*; import org.eclipse.persistence.exceptions.*; import org.eclipse.persistence.internal.helper.ClassConstants; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.internal.security.PrivilegedNewInstanceFromClass; /** * <p> * <b>Purpose</b>: ADVANCED: The expression operator is used internally to define SQL operations and functions. * It is possible for an advanced user to define their own operators. */ public class ExpressionOperator implements Serializable { /** Required for serialization compatibility. */ static final long serialVersionUID = -7066100204792043980L; protected int selector; protected String[] databaseStrings; protected boolean isPrefix = false; protected boolean isRepeating = false; protected Class nodeClass; protected int type; protected int[] argumentIndices = null; protected static Map allOperators = initializeOperators(); protected static Map platformOperatorNames = initializePlatformOperatorNames(); protected String[] javaStrings; /** Allow operator to disable binding. */ protected boolean isBindingSupported = true; /** Operator types */ public static final int LogicalOperator = 1; public static final int ComparisonOperator = 2; public static final int AggregateOperator = 3; public static final int OrderOperator = 4; public static final int FunctionOperator = 5; /** Logical operators */ public static final int And = 1; public static final int Or = 2; public static final int Not = 3; /** Comparison operators */ public static final int Equal = 4; public static final int NotEqual = 5; public static final int EqualOuterJoin = 6; public static final int LessThan = 7; public static final int LessThanEqual = 8; public static final int GreaterThan = 9; public static final int GreaterThanEqual = 10; public static final int Like = 11; public static final int NotLike = 12; public static final int In = 13; public static final int InSubQuery = 129; public static final int NotIn = 14; public static final int NotInSubQuery = 130; public static final int Between = 15; public static final int NotBetween = 16; public static final int IsNull = 17; public static final int NotNull = 18; public static final int Exists = 86; public static final int NotExists = 88; public static final int LikeEscape = 89; public static final int NotLikeEscape = 134; public static final int Decode = 105; public static final int Case = 117; public static final int NullIf = 131; public static final int Coalesce = 132; public static final int CaseCondition = 136; /** Aggregate operators */ public static final int Count = 19; public static final int Sum = 20; public static final int Average = 21; public static final int Maximum = 22; public static final int Minimum = 23; public static final int StandardDeviation = 24; public static final int Variance = 25; public static final int Distinct = 87; /** Ordering operators */ public static final int Ascending = 26; public static final int Descending = 27; /** Function operators */ // General public static final int ToUpperCase = 28; public static final int ToLowerCase = 29; public static final int Chr = 30; public static final int Concat = 31; public static final int HexToRaw = 32; public static final int Initcap = 33; public static final int Instring = 34; public static final int Soundex = 35; public static final int LeftPad = 36; public static final int LeftTrim = 37; public static final int Replace = 38; public static final int RightPad = 39; public static final int RightTrim = 40; public static final int Substring = 41; public static final int ToNumber = 42; public static final int Translate = 43; public static final int Trim = 44; public static final int Ascii = 45; public static final int Length = 46; public static final int CharIndex = 96; public static final int CharLength = 97; public static final int Difference = 98; public static final int Reverse = 99; public static final int Replicate = 100; public static final int Right = 101; public static final int Locate = 112; public static final int Locate2 = 113; public static final int ToChar = 114; public static final int ToCharWithFormat = 115; public static final int RightTrim2 = 116; public static final int Any = 118; public static final int Some = 119; public static final int All = 120; public static final int Trim2 = 121; public static final int LeftTrim2 = 122; public static final int SubstringSingleArg = 133; // Date public static final int AddMonths = 47; public static final int DateToString = 48; public static final int LastDay = 49; public static final int MonthsBetween = 50; public static final int NextDay = 51; public static final int RoundDate = 52; public static final int ToDate = 53; public static final int Today = 54; public static final int AddDate = 90; public static final int DateName = 92; public static final int DatePart = 93; public static final int DateDifference = 94; public static final int TruncateDate = 102; public static final int NewTime = 103; public static final int Nvl = 104; public static final int CurrentDate = 123; public static final int CurrentTime = 128; // Math public static final int Ceil = 55; public static final int Cos = 56; public static final int Cosh = 57; public static final int Abs = 58; public static final int Acos = 59; public static final int Asin = 60; public static final int Atan = 61; public static final int Exp = 62; public static final int Sqrt = 63; public static final int Floor = 64; public static final int Ln = 65; public static final int Log = 66; public static final int Mod = 67; public static final int Power = 68; public static final int Round = 69; public static final int Sign = 70; public static final int Sin = 71; public static final int Sinh = 72; public static final int Tan = 73; public static final int Tanh = 74; public static final int Trunc = 75; public static final int Greatest = 76; public static final int Least = 77; public static final int Add = 78; public static final int Subtract = 79; public static final int Divide = 80; public static final int Multiply = 81; public static final int Atan2 = 91; public static final int Cot = 95; public static final int Negate = 135; // Object-relational public static final int Deref = 82; public static final int Ref = 83; public static final int RefToHex = 84; public static final int Value = 85; //XML Specific public static final int Extract = 106; public static final int ExtractValue = 107; public static final int ExistsNode = 108; public static final int GetStringVal = 109; public static final int GetNumberVal = 110; public static final int IsFragment = 111; // Spatial public static final int SDO_WITHIN_DISTANCE = 124; public static final int SDO_RELATE = 125; public static final int SDO_FILTER = 126; public static final int SDO_NN = 127; /** * ADVANCED: * Create a new operator. */ public ExpressionOperator() { this.type = FunctionOperator; // For bug 2780072 provide default behavior to make this class more useable. setNodeClass(ClassConstants.FunctionExpression_Class); } /** * ADVANCED: * Create a new operator with the given name(s) and strings to print. */ public ExpressionOperator(int selector, Vector newDatabaseStrings) { this.type = FunctionOperator; // For bug 2780072 provide default behavior to make this class more useable. setNodeClass(ClassConstants.FunctionExpression_Class); this.selector = selector; this.printsAs(newDatabaseStrings); } /** * PUBLIC: * Return if binding is compatible with this operator. */ public boolean isBindingSupported() { return isBindingSupported; } /** * PUBLIC: * Set if binding is compatible with this operator. * Some databases do not allow binding, or require casting with certain operators. */ public void setIsBindingSupported(boolean isBindingSupported) { this.isBindingSupported = isBindingSupported; } /** * INTERNAL: * Return if the operator is equal to the other. */ public boolean equals(Object object) { if (this == object) { return true; } if ((object == null) || (getClass() != object.getClass())) { return false; } ExpressionOperator operator = (ExpressionOperator) object; if (getSelector() == 0) { return Arrays.equals(getDatabaseStrings(), operator.getDatabaseStrings()); } else { return getSelector() == operator.getSelector(); } } /** * INTERNAL: * Return the hash-code based on the unique selector. */ public int hashCode() { return getSelector(); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator abs() { return simpleFunction(Abs, "ABS"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator acos() { return simpleFunction(Acos, "ACOS"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator addDate() { ExpressionOperator exOperator = simpleThreeArgumentFunction(AddDate, "DATEADD"); int[] indices = new int[3]; indices[0] = 1; indices[1] = 2; indices[2] = 0; exOperator.setArgumentIndices(indices); return exOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator addMonths() { return simpleTwoArgumentFunction(AddMonths, "ADD_MONTHS"); } /** * ADVANCED: * Add an operator to the global list of operators. */ public static void addOperator(ExpressionOperator exOperator) { allOperators.put(Integer.valueOf(exOperator.getSelector()), exOperator); } /** * INTERNAL: * Create the AND operator. */ public static ExpressionOperator and() { return simpleLogical(And, "AND", "and"); } /** * INTERNAL: * Apply this to an object in memory. * Throw an error if the function is not supported. */ public Object applyFunction(Object source, Vector arguments) { if (source instanceof String) { if (this.selector == ToUpperCase) { return ((String)source).toUpperCase(); } else if (this.selector == ToLowerCase) { return ((String)source).toLowerCase(); } else if ((this.selector == Concat) && (arguments.size() == 1) && (arguments.elementAt(0) instanceof String)) { return ((String)source).concat((String)arguments.elementAt(0)); } else if ((this.selector == Substring) && (arguments.size() == 2) && (arguments.elementAt(0) instanceof Number) && (arguments.elementAt(1) instanceof Number)) { // assume the first parameter to be 1-based first index of the substring, the second - substring length. int beginIndexInclusive = ((Number)arguments.elementAt(0)).intValue() - 1; int endIndexExclusive = beginIndexInclusive + ((Number)arguments.elementAt(1)).intValue(); return ((String)source).substring(beginIndexInclusive, endIndexExclusive); } else if ((this.selector == SubstringSingleArg) && (arguments.size() == 1) && (arguments.elementAt(0) instanceof Number)) { int beginIndexInclusive = ((Number)arguments.elementAt(0)).intValue() - 1; int endIndexExclusive = ((String)source).length(); return ((String)source).substring(beginIndexInclusive, endIndexExclusive); } else if (this.selector == ToNumber) { return new java.math.BigDecimal((String)source); } else if (this.selector == Trim) { return ((String)source).trim(); } else if (this.selector == Length) { return Integer.valueOf(((String)source).length()); } } else if (source instanceof Number) { if (this.selector == Ceil) { return Double.valueOf(Math.ceil(((Number)source).doubleValue())); } else if (this.selector == Cos) { return Double.valueOf(Math.cos(((Number)source).doubleValue())); } else if (this.selector == Abs) { return Double.valueOf(Math.abs(((Number)source).doubleValue())); } else if (this.selector == Acos) { return Double.valueOf(Math.acos(((Number)source).doubleValue())); } else if (this.selector == Asin) { return Double.valueOf(Math.asin(((Number)source).doubleValue())); } else if (this.selector == Atan) { return Double.valueOf(Math.atan(((Number)source).doubleValue())); } else if (this.selector == Exp) { return Double.valueOf(Math.exp(((Number)source).doubleValue())); } else if (this.selector == Sqrt) { return Double.valueOf(Math.sqrt(((Number)source).doubleValue())); } else if (this.selector == Floor) { return Double.valueOf(Math.floor(((Number)source).doubleValue())); } else if (this.selector == Log) { return Double.valueOf(Math.log(((Number)source).doubleValue())); } else if ((this.selector == Power) && (arguments.size() == 1) && (arguments.elementAt(0) instanceof Number)) { return Double.valueOf(Math.pow(((Number)source).doubleValue(), (((Number)arguments.elementAt(0)).doubleValue()))); } else if (this.selector == Round) { return Double.valueOf(Math.round(((Number)source).doubleValue())); } else if (this.selector == Sin) { return Double.valueOf(Math.sin(((Number)source).doubleValue())); } else if (this.selector == Tan) { return Double.valueOf(Math.tan(((Number)source).doubleValue())); } else if ((this.selector == Greatest) && (arguments.size() == 1) && (arguments.elementAt(0) instanceof Number)) { return Double.valueOf(Math.max(((Number)source).doubleValue(), (((Number)arguments.elementAt(0)).doubleValue()))); } else if ((this.selector == Least) && (arguments.size() == 1) && (arguments.elementAt(0) instanceof Number)) { return Double.valueOf(Math.min(((Number)source).doubleValue(), (((Number)arguments.elementAt(0)).doubleValue()))); } else if ((this.selector == Add) && (arguments.size() == 1) && (arguments.elementAt(0) instanceof Number)) { return Double.valueOf(((Number)source).doubleValue() + (((Number)arguments.elementAt(0)).doubleValue())); } else if ((this.selector == Subtract) && (arguments.size() == 1) && (arguments.elementAt(0) instanceof Number)) { return Double.valueOf(((Number)source).doubleValue() - (((Number)arguments.elementAt(0)).doubleValue())); } else if ((this.selector == Divide) && (arguments.size() == 1) && (arguments.elementAt(0) instanceof Number)) { return Double.valueOf(((Number)source).doubleValue() / (((Number)arguments.elementAt(0)).doubleValue())); } else if ((this.selector == Multiply) && (arguments.size() == 1) && (arguments.elementAt(0) instanceof Number)) { return Double.valueOf(((Number)source).doubleValue() * (((Number)arguments.elementAt(0)).doubleValue())); } } throw QueryException.cannotConformExpression(); } /** * INTERNAL: * Create the ASCENDING operator. */ public static ExpressionOperator ascending() { return simpleOrdering(Ascending, "ASC", "ascending"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator ascii() { return simpleFunction(Ascii, "ASCII"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator asin() { return simpleFunction(Asin, "ASIN"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator atan() { return simpleFunction(Atan, "ATAN"); } /** * INTERNAL: * Create the AVERAGE operator. */ public static ExpressionOperator average() { return simpleAggregate(Average, "AVG", "average"); } /** * ADVANCED: * Tell the operator to be postfix, i.e. its strings start printing after * those of its first argument. */ public void bePostfix() { isPrefix = false; } /** * ADVANCED: * Tell the operator to be pretfix, i.e. its strings start printing before * those of its first argument. */ public void bePrefix() { isPrefix = true; } /** * INTERNAL: * Make this a repeating argument. Currently unused. */ public void beRepeating() { isRepeating = true; } /** * INTERNAL: * Create the BETWEEN Operator */ public static ExpressionOperator between() { ExpressionOperator result = new ExpressionOperator(); result.setSelector(Between); result.setType(ComparisonOperator); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement("("); v.addElement(" BETWEEN "); v.addElement(" AND "); v.addElement(")"); result.printsAs(v); result.bePrefix(); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } /** * INTERNAL: * Build operator. * Note: This operator works differently from other operators. * @see Expression#caseStatement(Map, String) */ public static ExpressionOperator caseStatement() { ListExpressionOperator exOperator = new ListExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(Case); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.ArgumentListFunctionExpression_Class); exOperator.setIsBindingSupported(false); exOperator.setStartString("CASE "); exOperator.setSeparators(new String[]{" WHEN ", " THEN "}); exOperator.setTerminationStrings(new String[]{" ELSE ", " END"}); return exOperator; } /** * INTERNAL: * Build operator. * Note: This operator works differently from other operators. * @see Expression#caseStatement(Map, String) */ public static ExpressionOperator caseConditionStatement() { ListExpressionOperator exOperator = new ListExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(CaseCondition); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.ArgumentListFunctionExpression_Class); exOperator.setIsBindingSupported(false); exOperator.setStartStrings(new String[]{"CASE WHEN ", " THEN "}); exOperator.setSeparators(new String[]{" WHEN ", " THEN "}); exOperator.setTerminationStrings(new String[]{" ELSE ", " END "}); return exOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator ceil() { return simpleFunction(Ceil, "CEIL"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator charIndex() { return simpleTwoArgumentFunction(CharIndex, "CHARINDEX"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator charLength() { return simpleFunction(CharLength, "CHAR_LENGTH"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator chr() { return simpleFunction(Chr, "CHR"); } /** * INTERNAL: * Build operator. * Note: This operator works differently from other operators. * @see Expression#caseStatement(Map, String) */ public static ExpressionOperator coalesce() { ListExpressionOperator exOperator = new ListExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(Coalesce); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.ArgumentListFunctionExpression_Class); exOperator.setStartString("COALESCE("); exOperator.setSeparator(","); exOperator.setTerminationString(" )"); return exOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator concat() { ExpressionOperator operator = simpleMath(Concat, "+"); operator.setIsBindingSupported(false); return operator; } /** * INTERNAL: * Compare between in memory. */ public boolean conformBetween(Object left, Object right) { Object start = ((Vector)right).elementAt(0); Object end = ((Vector)right).elementAt(1); if ((left == null) || (start == null) || (end == null)) { return false; } if ((left instanceof Number) && (start instanceof Number) && (end instanceof Number)) { return ((((Number)left).doubleValue()) >= (((Number)start).doubleValue())) && ((((Number)left).doubleValue()) <= (((Number)end).doubleValue())); } else if ((left instanceof String) && (start instanceof String) && (end instanceof String)) { return ((((String)left).compareTo(((String)start)) > 0) || (((String)left).compareTo(((String)start)) == 0)) && ((((String)left).compareTo(((String)end)) < 0) || (((String)left).compareTo(((String)end)) == 0)); } else if ((left instanceof java.util.Date) && (start instanceof java.util.Date) && (end instanceof java.util.Date)) { return (((java.util.Date)left).after(((java.util.Date)start)) || ((java.util.Date)left).equals((start))) && (((java.util.Date)left).before(((java.util.Date)end)) || ((java.util.Date)left).equals((end))); } else if ((left instanceof java.util.Calendar) && (start instanceof java.util.Calendar) && (end instanceof java.util.Calendar)) { return (((java.util.Calendar)left).after(start) || ((java.util.Calendar)left).equals((start))) && (((java.util.Calendar)left).before(end) || ((java.util.Calendar)left).equals((end))); } throw QueryException.cannotConformExpression(); } /** * INTERNAL: * Compare like in memory. * This only works for % not _. * @author Christian Weeks aka ChristianLink */ public boolean conformLike(Object left, Object right) { if ((right == null) && (left == null)) { return true; } if (!(right instanceof String) || !(left instanceof String)) { throw QueryException.cannotConformExpression(); } String likeString = (String)right; if (likeString.indexOf("_") != -1) { throw QueryException.cannotConformExpression(); } String value = (String)left; if (likeString.indexOf("%") == -1) { // No % symbols return left.equals(right); } boolean strictStart = !likeString.startsWith("%"); boolean strictEnd = !likeString.endsWith("%"); StringTokenizer tokens = new StringTokenizer(likeString, "%"); int lastPosition = 0; String lastToken = null; if (strictStart) { lastToken = tokens.nextToken(); if (!value.startsWith(lastToken)) { return false; } } while (tokens.hasMoreTokens()) { lastToken = tokens.nextToken(); lastPosition = value.indexOf(lastToken, lastPosition); if (lastPosition < 0) { return false; } } if (strictEnd) { return value.endsWith(lastToken); } return true; } public void copyTo(ExpressionOperator operator){ operator.selector = selector; operator.isPrefix = isPrefix; operator.isRepeating = isRepeating; operator.nodeClass = nodeClass; operator.type = type; operator.databaseStrings = databaseStrings == null ? null : Helper.copyStringArray(databaseStrings); operator.argumentIndices = argumentIndices == null ? null : Helper.copyIntArray(argumentIndices); operator.javaStrings = javaStrings == null ? null : Helper.copyStringArray(javaStrings); operator.isBindingSupported = isBindingSupported; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator cos() { return simpleFunction(Cos, "COS"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator cosh() { return simpleFunction(Cosh, "COSH"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator cot() { return simpleFunction(Cot, "COT"); } /** * INTERNAL: * Create the COUNT operator. */ public static ExpressionOperator count() { return simpleAggregate(Count, "COUNT", "count"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator dateDifference() { return simpleThreeArgumentFunction(DateDifference, "DATEDIFF"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator dateName() { return simpleTwoArgumentFunction(DateName, "DATENAME"); } /** * INTERNAL: * Oracle equivalent to DATENAME is TO_CHAR. */ public static ExpressionOperator oracleDateName() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(DateName); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(3); v.addElement("TO_CHAR("); v.addElement(", '"); v.addElement("')"); exOperator.printsAs(v); exOperator.bePrefix(); int[] indices = { 1, 0 }; exOperator.setArgumentIndices(indices); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator datePart() { return simpleTwoArgumentFunction(DatePart, "DATEPART"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator dateToString() { return simpleFunction(DateToString, "TO_CHAR"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator toChar() { return simpleFunction(ToChar, "TO_CHAR"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator toCharWithFormat() { return simpleTwoArgumentFunction(ToCharWithFormat, "TO_CHAR"); } /** * INTERNAL: * Build operator. * Note: This operator works differently from other operators. * @see Expression#decode(Map, String) */ public static ExpressionOperator decode() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setSelector(Decode); exOperator.setNodeClass(FunctionExpression.class); exOperator.setType(FunctionOperator); exOperator.bePrefix(); return exOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator deref() { return simpleFunction(Deref, "DEREF"); } /** * INTERNAL: * Create the DESCENDING operator. */ public static ExpressionOperator descending() { return simpleOrdering(Descending, "DESC", "descending"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator difference() { return simpleTwoArgumentFunction(Difference, "DIFFERENCE"); } /** * INTERNAL: * Create the DISTINCT operator. */ public static ExpressionOperator distinct() { return simpleFunction(Distinct, "DISTINCT", "distinct"); } /** * INTERNAL: * Compare the values in memory. * Used for in-memory querying, all operators are not support. */ public boolean doesRelationConform(Object left, Object right) { // Big ugly case statement follows. // Java is really verbose, the Smalltalk equivalent to this... left perform: self selector with: right // Note, compareTo for String returns a number <= -1 if the String is less than. We assumed that // it would return -1. The same thing for strings that are greater than (ie it returns >= 1). PWK // Equals if (this.selector == Equal) { if ((left == null) && (right == null)) { return true; } else if ((left == null) || (right == null)) { return false; } if (((left instanceof Number) && (right instanceof Number)) && (left.getClass() != right.getClass())) { return ((Number)left).doubleValue() == ((Number)right).doubleValue(); } return left.equals(right); } else if (this.selector == NotEqual) { if ((left == null) && (right == null)) { return false; } else if ((left == null) || (right == null)) { return true; } return !left.equals(right); } else if (this.selector == IsNull) { return (left == null); } if (this.selector == NotNull) { return (left != null); } // Less thans, greater thans else if (this.selector == LessThan) {// You have got to love polymorphism in Java, NOT!!! if ((left == null) || (right == null)) { return false; } if ((left instanceof Number) && (right instanceof Number)) { return (((Number)left).doubleValue()) < (((Number)right).doubleValue()); } else if ((left instanceof String) && (right instanceof String)) { return ((String)left).compareTo(((String)right)) < 0; } else if ((left instanceof java.util.Date) && (right instanceof java.util.Date)) { return ((java.util.Date)left).before(((java.util.Date)right)); } else if ((left instanceof java.util.Calendar) && (right instanceof java.util.Calendar)) { return ((java.util.Calendar)left).before(right); } } else if (this.selector == LessThanEqual) { if ((left == null) && (right == null)) { return true; } else if ((left == null) || (right == null)) { return false; } if ((left instanceof Number) && (right instanceof Number)) { return (((Number)left).doubleValue()) <= (((Number)right).doubleValue()); } else if ((left instanceof String) && (right instanceof String)) { int compareValue = ((String)left).compareTo(((String)right)); return (compareValue < 0) || (compareValue == 0); } else if ((left instanceof java.util.Date) && (right instanceof java.util.Date)) { return ((java.util.Date)left).equals((right)) || ((java.util.Date)left).before(((java.util.Date)right)); } else if ((left instanceof java.util.Calendar) && (right instanceof java.util.Calendar)) { return ((java.util.Calendar)left).equals((right)) || ((java.util.Calendar)left).before(right); } } else if (this.selector == GreaterThan) { if ((left == null) || (right == null)) { return false; } if ((left instanceof Number) && (right instanceof Number)) { return (((Number)left).doubleValue()) > (((Number)right).doubleValue()); } else if ((left instanceof String) && (right instanceof String)) { int compareValue = ((String)left).compareTo(((String)right)); return (compareValue > 0); } else if ((left instanceof java.util.Date) && (right instanceof java.util.Date)) { return ((java.util.Date)left).after(((java.util.Date)right)); } else if ((left instanceof java.util.Calendar) && (right instanceof java.util.Calendar)) { return ((java.util.Calendar)left).after(right); } } else if (this.selector == GreaterThanEqual) { if ((left == null) && (right == null)) { return true; } else if ((left == null) || (right == null)) { return false; } if ((left instanceof Number) && (right instanceof Number)) { return (((Number)left).doubleValue()) >= (((Number)right).doubleValue()); } else if ((left instanceof String) && (right instanceof String)) { int compareValue = ((String)left).compareTo(((String)right)); return (compareValue > 0) || (compareValue == 0); } else if ((left instanceof java.util.Date) && (right instanceof java.util.Date)) { return ((java.util.Date)left).equals((right)) || ((java.util.Date)left).after(((java.util.Date)right)); } else if ((left instanceof java.util.Calendar) && (right instanceof java.util.Calendar)) { return ((java.util.Calendar)left).equals((right)) || ((java.util.Calendar)left).after(right); } } // Between else if ((this.selector == Between) && (right instanceof Vector) && (((Vector)right).size() == 2)) { return conformBetween(left, right); } else if ((this.selector == NotBetween) && (right instanceof Vector) && (((Vector)right).size() == 2)) { return !conformBetween(left, right); } else if ((this.selector == In) && (right instanceof Collection)) { return ((Collection)right).contains(left); } else if ((this.selector == NotIn) && (right instanceof Collection)) { return !((Collection)right).contains(left); } // Like //conformLike(left, right); else if (((this.selector == Like) || (this.selector == NotLike)) && (right instanceof Vector) && (((Vector)right).size() == 1)) { Boolean doesLikeConform = JavaPlatform.conformLike(left, ((Vector)right).get(0)); if (doesLikeConform != null) { if (doesLikeConform.booleanValue()) { return this.selector == Like;// Negate for NotLike } else { return this.selector != Like;// Negate for NotLike } } } throw QueryException.cannotConformExpression(); } /** * INTERNAL: * Initialize the outer join operator * Note: This is merely a shell which is incomplete, and * so will be replaced by the platform's operator when we * go to print. We need to create this here so that the expression * class is correct, normally it assumes functions for unknown operators. */ public static ExpressionOperator equalOuterJoin() { return simpleRelation(EqualOuterJoin, "=*"); } /** * INTERNAL: * Create the EXISTS operator. */ public static ExpressionOperator exists() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(Exists); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(2); v.addElement("EXISTS" + " "); v.addElement(" "); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator exp() { return simpleFunction(Exp, "EXP"); } /** * INTERNAL: * Create an expression for this operator, using the given base. */ public Expression expressionFor(Expression base) { return expressionForArguments(base, org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(0)); } /** * INTERNAL: * Create an expression for this operator, using the given base and a single argument. */ public Expression expressionFor(Expression base, Object value) { return newExpressionForArgument(base, value); } /** * INTERNAL: * Create an expression for this operator, using the given base and a single argument. * Base is used last in the expression */ public Expression expressionForWithBaseLast(Expression base, Object value) { return newExpressionForArgumentWithBaseLast(base, value); } /** * INTERNAL: * Create an expression for this operator, using the given base and arguments. */ public Expression expressionForArguments(Expression base, Vector arguments) { return newExpressionForArguments(base, arguments); } /** * INTERNAL: * Create the extract expression operator */ public static ExpressionOperator extract() { ExpressionOperator result = new ExpressionOperator(); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement("extract("); v.addElement(","); v.addElement(")"); result.printsAs(v); result.bePrefix(); result.setSelector(Extract); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } /** * INTERNAL: * Create the extractValue expression operator */ public static ExpressionOperator extractValue() { ExpressionOperator result = new ExpressionOperator(); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement("extractValue("); v.addElement(","); v.addElement(")"); result.printsAs(v); result.bePrefix(); result.setSelector(ExtractValue); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } /** * INTERNAL: * Create the existsNode expression operator */ public static ExpressionOperator existsNode() { ExpressionOperator result = new ExpressionOperator(); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement("existsNode("); v.addElement(","); v.addElement(")"); result.printsAs(v); result.bePrefix(); result.setSelector(ExistsNode); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } public static ExpressionOperator getStringVal() { ExpressionOperator result = new ExpressionOperator(); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement(".getStringVal()"); result.printsAs(v); result.bePostfix(); result.setSelector(GetStringVal); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } public static ExpressionOperator getNumberVal() { ExpressionOperator result = new ExpressionOperator(); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement(".getNumberVal()"); result.printsAs(v); result.bePostfix(); result.setSelector(GetNumberVal); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } public static ExpressionOperator isFragment() { ExpressionOperator result = new ExpressionOperator(); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement(".isFragment()"); result.printsAs(v); result.bePostfix(); result.setSelector(IsFragment); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator floor() { return simpleFunction(Floor, "FLOOR"); } /** * ADVANCED: * Return the hashtable of all operators. */ public static Map getAllOperators() { return allOperators; } /** * INTERNAL: */ public String[] getDatabaseStrings() { return databaseStrings; } /** * INTERNAL: */ public String[] getJavaStrings() { return javaStrings; } /** * INTERNAL: */ public Class getNodeClass() { return nodeClass; } /** * INTERNAL: * Lookup the operator with the given name. */ public static ExpressionOperator getOperator(Integer selector) { return (ExpressionOperator)getAllOperators().get(selector); } /** * INTERNAL: * Return the selector id. */ public int getSelector() { return selector; } /** * ADVANCED: * Return the type of function. * This must be one of the static function types defined in this class. */ public int getType() { return this.type; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator greatest() { return simpleTwoArgumentFunction(Greatest, "GREATEST"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator hexToRaw() { return simpleFunction(HexToRaw, "HEXTORAW"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator ifNull() { return simpleTwoArgumentFunction(Nvl, "NVL"); } /** * INTERNAL: * Create the IN operator. */ public static ExpressionOperator in() { return simpleRelation(In, "IN"); } /** * INTERNAL: * Create the IN operator taking a subquery. * Note, the subquery itself comes with parenethesis, so the IN operator * should not add any parenethesis. */ public static ExpressionOperator inSubQuery() { ExpressionOperator result = new ExpressionOperator(); result.setType(ExpressionOperator.FunctionOperator); result.setSelector(InSubQuery); Vector v = new Vector(1); v.addElement(" IN "); result.printsAs(v); result.bePostfix(); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator initcap() { return simpleFunction(Initcap, "INITCAP"); } /** * INTERNAL: */ protected static void initializeAggregateFunctionOperators() { addOperator(count()); addOperator(sum()); addOperator(average()); addOperator(minimum()); addOperator(maximum()); addOperator(distinct()); } /** * INTERNAL: */ protected static void initializeFunctionOperators() { addOperator(notOperator()); addOperator(ascending()); addOperator(descending()); addOperator(any()); addOperator(some()); addOperator(all()); addOperator(in()); addOperator(inSubQuery()); addOperator(notIn()); addOperator(notInSubQuery()); addOperator(coalesce()); addOperator(caseStatement()); addOperator(caseConditionStatement()); } /** * INTERNAL: */ protected static void initializeLogicalOperators() { addOperator(and()); addOperator(or()); addOperator(isNull()); addOperator(notNull()); } /** * INTERNAL: */ public static Map initializeOperators() { resetOperators(); initializeFunctionOperators(); initializeRelationOperators(); initializeLogicalOperators(); initializeAggregateFunctionOperators(); return allOperators; } /** * INTERNAL: * Initialize a mapping to the platform operator names for usage with exceptions. */ public static String getPlatformOperatorName(int operator) { String name = (String)getPlatformOperatorNames().get(Integer.valueOf(operator)); if (name == null) { name = String.valueOf(operator); } return name; } /** * INTERNAL: * Initialize a mapping to the platform operator names for usage with exceptions. */ public static Map getPlatformOperatorNames() { return platformOperatorNames; } /** * INTERNAL: * Initialize a mapping to the platform operator names for usage with exceptions. */ public static Map initializePlatformOperatorNames() { Map platformOperatorNames = new HashMap(); platformOperatorNames.put(Integer.valueOf(ToUpperCase), "ToUpperCase"); platformOperatorNames.put(Integer.valueOf(ToLowerCase), "ToLowerCase"); platformOperatorNames.put(Integer.valueOf(Chr), "Chr"); platformOperatorNames.put(Integer.valueOf(Concat), "Concat"); platformOperatorNames.put(Integer.valueOf(Coalesce), "Coalesce"); platformOperatorNames.put(Integer.valueOf(Case), "Case"); platformOperatorNames.put(Integer.valueOf(CaseCondition), "Case(codition)"); platformOperatorNames.put(Integer.valueOf(HexToRaw), "HexToRaw"); platformOperatorNames.put(Integer.valueOf(Initcap), "Initcap"); platformOperatorNames.put(Integer.valueOf(Instring), "Instring"); platformOperatorNames.put(Integer.valueOf(Soundex), "Soundex"); platformOperatorNames.put(Integer.valueOf(LeftPad), "LeftPad"); platformOperatorNames.put(Integer.valueOf(LeftTrim), "LeftTrim"); platformOperatorNames.put(Integer.valueOf(RightPad), "RightPad"); platformOperatorNames.put(Integer.valueOf(RightTrim), "RightTrim"); platformOperatorNames.put(Integer.valueOf(Substring), "Substring"); platformOperatorNames.put(Integer.valueOf(SubstringSingleArg), "Substring"); platformOperatorNames.put(Integer.valueOf(Translate), "Translate"); platformOperatorNames.put(Integer.valueOf(Ascii), "Ascii"); platformOperatorNames.put(Integer.valueOf(Length), "Length"); platformOperatorNames.put(Integer.valueOf(CharIndex), "CharIndex"); platformOperatorNames.put(Integer.valueOf(CharLength), "CharLength"); platformOperatorNames.put(Integer.valueOf(Difference), "Difference"); platformOperatorNames.put(Integer.valueOf(Reverse), "Reverse"); platformOperatorNames.put(Integer.valueOf(Replicate), "Replicate"); platformOperatorNames.put(Integer.valueOf(Right), "Right"); platformOperatorNames.put(Integer.valueOf(Locate), "Locate"); platformOperatorNames.put(Integer.valueOf(Locate2), "Locate"); platformOperatorNames.put(Integer.valueOf(ToNumber), "ToNumber"); platformOperatorNames.put(Integer.valueOf(ToChar), "ToChar"); platformOperatorNames.put(Integer.valueOf(ToCharWithFormat), "ToChar"); platformOperatorNames.put(Integer.valueOf(AddMonths), "AddMonths"); platformOperatorNames.put(Integer.valueOf(DateToString), "DateToString"); platformOperatorNames.put(Integer.valueOf(MonthsBetween), "MonthsBetween"); platformOperatorNames.put(Integer.valueOf(NextDay), "NextDay"); platformOperatorNames.put(Integer.valueOf(RoundDate), "RoundDate"); platformOperatorNames.put(Integer.valueOf(AddDate), "AddDate"); platformOperatorNames.put(Integer.valueOf(DateName), "DateName"); platformOperatorNames.put(Integer.valueOf(DatePart), "DatePart"); platformOperatorNames.put(Integer.valueOf(DateDifference), "DateDifference"); platformOperatorNames.put(Integer.valueOf(TruncateDate), "TruncateDate"); platformOperatorNames.put(Integer.valueOf(NewTime), "NewTime"); platformOperatorNames.put(Integer.valueOf(Nvl), "Nvl"); platformOperatorNames.put(Integer.valueOf(NewTime), "NewTime"); platformOperatorNames.put(Integer.valueOf(Ceil), "Ceil"); platformOperatorNames.put(Integer.valueOf(Cos), "Cos"); platformOperatorNames.put(Integer.valueOf(Cosh), "Cosh"); platformOperatorNames.put(Integer.valueOf(Abs), "Abs"); platformOperatorNames.put(Integer.valueOf(Acos), "Acos"); platformOperatorNames.put(Integer.valueOf(Asin), "Asin"); platformOperatorNames.put(Integer.valueOf(Atan), "Atan"); platformOperatorNames.put(Integer.valueOf(Exp), "Exp"); platformOperatorNames.put(Integer.valueOf(Sqrt), "Sqrt"); platformOperatorNames.put(Integer.valueOf(Floor), "Floor"); platformOperatorNames.put(Integer.valueOf(Ln), "Ln"); platformOperatorNames.put(Integer.valueOf(Log), "Log"); platformOperatorNames.put(Integer.valueOf(Mod), "Mod"); platformOperatorNames.put(Integer.valueOf(Power), "Power"); platformOperatorNames.put(Integer.valueOf(Round), "Round"); platformOperatorNames.put(Integer.valueOf(Sign), "Sign"); platformOperatorNames.put(Integer.valueOf(Sin), "Sin"); platformOperatorNames.put(Integer.valueOf(Sinh), "Sinh"); platformOperatorNames.put(Integer.valueOf(Tan), "Tan"); platformOperatorNames.put(Integer.valueOf(Tanh), "Tanh"); platformOperatorNames.put(Integer.valueOf(Trunc), "Trunc"); platformOperatorNames.put(Integer.valueOf(Greatest), "Greatest"); platformOperatorNames.put(Integer.valueOf(Least), "Least"); platformOperatorNames.put(Integer.valueOf(Add), "Add"); platformOperatorNames.put(Integer.valueOf(Subtract), "Subtract"); platformOperatorNames.put(Integer.valueOf(Divide), "Divide"); platformOperatorNames.put(Integer.valueOf(Multiply), "Multiply"); platformOperatorNames.put(Integer.valueOf(Atan2), "Atan2"); platformOperatorNames.put(Integer.valueOf(Cot), "Cot"); platformOperatorNames.put(Integer.valueOf(Deref), "Deref"); platformOperatorNames.put(Integer.valueOf(Ref), "Ref"); platformOperatorNames.put(Integer.valueOf(RefToHex), "RefToHex"); platformOperatorNames.put(Integer.valueOf(Value), "Value"); platformOperatorNames.put(Integer.valueOf(Extract), "Extract"); platformOperatorNames.put(Integer.valueOf(ExtractValue), "ExtractValue"); platformOperatorNames.put(Integer.valueOf(ExistsNode), "ExistsNode"); platformOperatorNames.put(Integer.valueOf(GetStringVal), "GetStringVal"); platformOperatorNames.put(Integer.valueOf(GetNumberVal), "GetNumberVal"); platformOperatorNames.put(Integer.valueOf(IsFragment), "IsFragment"); platformOperatorNames.put(Integer.valueOf(SDO_WITHIN_DISTANCE), "MDSYS.SDO_WITHIN_DISTANCE"); platformOperatorNames.put(Integer.valueOf(SDO_RELATE), "MDSYS.SDO_RELATE"); platformOperatorNames.put(Integer.valueOf(SDO_FILTER), "MDSYS.SDO_FILTER"); platformOperatorNames.put(Integer.valueOf(SDO_NN), "MDSYS.SDO_NN"); platformOperatorNames.put(Integer.valueOf(NullIf), "NullIf"); return platformOperatorNames; } /** * INTERNAL: */ protected static void initializeRelationOperators() { addOperator(simpleRelation(Equal, "=", "equal")); addOperator(simpleRelation(NotEqual, "<>", "notEqual")); addOperator(simpleRelation(LessThan, "<", "lessThan")); addOperator(simpleRelation(LessThanEqual, "<=", "lessThanEqual")); addOperator(simpleRelation(GreaterThan, ">", "greaterThan")); addOperator(simpleRelation(GreaterThanEqual, ">=", "greaterThanEqual")); addOperator(like()); addOperator(likeEscape()); addOperator(notLike()); addOperator(notLikeEscape()); addOperator(between()); addOperator(exists()); addOperator(notExists()); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator instring() { return simpleTwoArgumentFunction(Instring, "INSTR"); } /** * Aggregate functions are function in the select such as COUNT. */ public boolean isAggregateOperator() { return getType() == AggregateOperator; } /** * Comparison functions are functions such as = and >. */ public boolean isComparisonOperator() { return getType() == ComparisonOperator; } /** * INTERNAL: * If we have all the required information, this operator is complete * and can be used as is. Otherwise we will need to look up a platform- * specific operator. */ public boolean isComplete() { return (databaseStrings != null) && (databaseStrings.length != 0); } /** * General functions are any normal function such as UPPER. */ public boolean isFunctionOperator() { return getType() == FunctionOperator; } /** * Logical functions are functions such as and and or. */ public boolean isLogicalOperator() { return getType() == LogicalOperator; } /** * INTERNAL: * Create the ISNULL operator. */ public static ExpressionOperator isNull() { ExpressionOperator result = new ExpressionOperator(); result.setType(ComparisonOperator); result.setSelector(IsNull); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement("("); v.addElement(" IS NULL)"); result.printsAs(v); result.bePrefix(); result.printsJavaAs(".isNull()"); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } /** * Order functions are used in the order by such as ASC. */ public boolean isOrderOperator() { return getType() == OrderOperator; } /** * ADVANCED: * Return true if this is a prefix operator. */ public boolean isPrefix() { return isPrefix; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator lastDay() { return simpleFunction(LastDay, "LAST_DAY"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator least() { return simpleTwoArgumentFunction(Least, "LEAST"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator leftPad() { return simpleThreeArgumentFunction(LeftPad, "LPAD"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator leftTrim() { return simpleFunction(LeftTrim, "LTRIM"); } /** * INTERNAL: * Build leftTrim operator that takes one parameter. */ public static ExpressionOperator leftTrim2() { return simpleTwoArgumentFunction(LeftTrim2, "LTRIM"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator length() { return simpleFunction(Length, "LENGTH"); } /** * INTERNAL: * Create the LIKE operator. */ public static ExpressionOperator like() { ExpressionOperator result = new ExpressionOperator(); result.setSelector(Like); result.setType(FunctionOperator); Vector v = NonSynchronizedVector.newInstance(3); v.add(""); v.add(" LIKE "); v.add(""); result.printsAs(v); result.bePrefix(); result.setNodeClass(ClassConstants.FunctionExpression_Class); v = NonSynchronizedVector.newInstance(2); v.add(".like("); v.add(")"); result.printsJavaAs(v); return result; } /** * INTERNAL: * Create the LIKE operator with ESCAPE. */ public static ExpressionOperator likeEscape() { ExpressionOperator result = new ExpressionOperator(); result.setSelector(LikeEscape); result.setType(FunctionOperator); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement(""); v.addElement(" LIKE "); v.addElement(" ESCAPE "); v.addElement(""); result.printsAs(v); result.bePrefix(); result.setNodeClass(ClassConstants.FunctionExpression_Class); result.setIsBindingSupported(false); return result; } /** * INTERNAL: * Create the LIKE operator with ESCAPE. */ public static ExpressionOperator notLikeEscape() { ExpressionOperator result = new ExpressionOperator(); result.setSelector(NotLikeEscape); result.setType(FunctionOperator); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement(""); v.addElement(" NOT LIKE "); v.addElement(" ESCAPE "); v.addElement(""); result.printsAs(v); result.bePrefix(); result.setNodeClass(ClassConstants.FunctionExpression_Class); result.setIsBindingSupported(false); return result; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator ln() { return simpleFunction(Ln, "LN"); } /** * INTERNAL: * Build locate operator i.e. LOCATE("ob", t0.F_NAME) */ public static ExpressionOperator locate() { ExpressionOperator expOperator = simpleTwoArgumentFunction(Locate, "LOCATE"); int[] argumentIndices = new int[2]; argumentIndices[0] = 1; argumentIndices[1] = 0; expOperator.setArgumentIndices(argumentIndices); expOperator.setIsBindingSupported(false); return expOperator; } /** * INTERNAL: * Build locate operator with 3 params i.e. LOCATE("coffee", t0.DESCRIP, 4). * Last parameter is a start at. */ public static ExpressionOperator locate2() { ExpressionOperator expOperator = simpleThreeArgumentFunction(Locate2, "LOCATE"); int[] argumentIndices = new int[3]; argumentIndices[0] = 1; argumentIndices[1] = 0; argumentIndices[2] = 2; expOperator.setArgumentIndices(argumentIndices); expOperator.setIsBindingSupported(false); return expOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator log() { return simpleFunction(Log, "LOG"); } /** * INTERNAL: * Create the MAXIMUM operator. */ public static ExpressionOperator maximum() { return simpleAggregate(Maximum, "MAX", "maximum"); } /** * INTERNAL: * Create the MINIMUM operator. */ public static ExpressionOperator minimum() { return simpleAggregate(Minimum, "MIN", "minimum"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator mod() { ExpressionOperator operator = simpleTwoArgumentFunction(Mod, "MOD"); operator.setIsBindingSupported(false); return operator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator monthsBetween() { return simpleTwoArgumentFunction(MonthsBetween, "MONTHS_BETWEEN"); } /** * INTERNAL: * Create a new expression. Optimized for the single argument case. */ public Expression newExpressionForArgument(Expression base, Object singleArgument) { if (singleArgument == null) { if (this.selector == Equal) { return base.isNull(); } else if (this.selector == NotEqual) { return base.notNull(); } } Expression node = createNode(); node.create(base, singleArgument, this); return node; } /** * INTERNAL: * Instantiate an instance of the operator's node class. */ protected Expression createNode() { // PERF: Avoid reflection for common cases. if (this.nodeClass == ClassConstants.ArgumentListFunctionExpression_Class){ return new ArgumentListFunctionExpression(); } else if (this.nodeClass == ClassConstants.FunctionExpression_Class) { return new FunctionExpression(); } else if (this.nodeClass == ClassConstants.RelationExpression_Class) { return new RelationExpression(); } else if (this.nodeClass == ClassConstants.LogicalExpression_Class) { return new LogicalExpression(); } try { Expression node = null; if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){ try { node = (Expression)AccessController.doPrivileged(new PrivilegedNewInstanceFromClass(getNodeClass())); } catch (PrivilegedActionException exception) { return null; } } else { node = (Expression)PrivilegedAccessHelper.newInstanceFromClass(getNodeClass()); } return node; } catch (InstantiationException exception) { throw new InternalError(exception.toString()); } catch (IllegalAccessException exception) { throw new InternalError(exception.toString()); } } /** * INTERNAL: * Create a new expression. Optimized for the single argument case with base last */ public Expression newExpressionForArgumentWithBaseLast(Expression base, Object singleArgument) { if (singleArgument == null) { if (this.selector == Equal) { return base.isNull(); } else if (this.selector == NotEqual) { return base.notNull(); } } Expression node = createNode(); node.createWithBaseLast(base, singleArgument, this); return node; } /** * INTERNAL: * The general case. */ public Expression newExpressionForArguments(Expression base, Vector arguments) { if ((arguments.size() == 1) && (arguments.get(0) == null)) { if (this.selector == Equal) { return base.isNull(); } else if (this.selector == NotEqual) { return base.notNull(); } } Expression node = createNode(); node.create(base, arguments, this); return node; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator negate() { return simpleFunction(Negate, "-"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator newTime() { return simpleThreeArgumentFunction(NewTime, "NEW_TIME"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator nextDay() { return simpleTwoArgumentFunction(NextDay, "NEXT_DAY"); } /** * INTERNAL: * Create the NOT EXISTS operator. */ public static ExpressionOperator notExists() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(NotExists); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(2); v.addElement("NOT EXISTS" + " "); v.addElement(" "); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Create the NOTIN operator. */ public static ExpressionOperator notIn() { return simpleRelation(NotIn, "NOT IN"); } /** * INTERNAL: * Create the NOTIN operator taking a subQuery. * Note, the subquery itself comes with parenethesis, so the IN operator * should not add any parenethesis. */ public static ExpressionOperator notInSubQuery() { ExpressionOperator result = new ExpressionOperator(); result.setType(ExpressionOperator.FunctionOperator); result.setSelector(NotInSubQuery); Vector v = new Vector(1); v.addElement(" NOT IN "); result.printsAs(v); result.bePostfix(); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } /** * INTERNAL: * Create the NOTLIKE operator. */ public static ExpressionOperator notLike() { ExpressionOperator result = new ExpressionOperator(); result.setSelector(NotLike); result.setType(FunctionOperator); Vector v = NonSynchronizedVector.newInstance(); v.add(""); v.add(" NOT LIKE "); v.add(""); result.printsAs(v); result.bePrefix(); result.setNodeClass(ClassConstants.FunctionExpression_Class); v = NonSynchronizedVector.newInstance(2); v.add(".notLike("); v.add(")"); result.printsJavaAs(v); return result; } /** * INTERNAL: * Create the NOTNULL operator. */ public static ExpressionOperator notNull() { ExpressionOperator result = new ExpressionOperator(); result.setType(ComparisonOperator); result.setSelector(NotNull); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement("("); v.addElement(" IS NOT NULL)"); result.printsAs(v); result.bePrefix(); result.printsJavaAs(".notNull()"); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } /** * INTERNAL: * Create the NOT operator. */ public static ExpressionOperator notOperator() { ExpressionOperator result = new ExpressionOperator(); result.setSelector(Not); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(); v.addElement("NOT ("); v.addElement(")"); result.printsAs(v); result.bePrefix(); result.printsJavaAs(".not()"); result.setNodeClass(ClassConstants.FunctionExpression_Class); return result; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator nullIf() { return simpleTwoArgumentFunction(NullIf, "NULLIF"); } /** * INTERNAL: * Create the OR operator. */ public static ExpressionOperator or() { return simpleLogical(Or, "OR", "or"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator power() { return simpleTwoArgumentFunction(Power, "POWER"); } /** * INTERNAL: Print the collection onto the SQL stream. */ public void printCollection(Vector items, ExpressionSQLPrinter printer) { // Certain functions don't allow binding on some platforms. if (printer.getPlatform().isDynamicSQLRequiredForFunctions() && !isBindingSupported()) { printer.getCall().setUsesBinding(false); } int dbStringIndex = 0; try { if (isPrefix()) { printer.getWriter().write(getDatabaseStrings()[0]); dbStringIndex = 1; } else { dbStringIndex = 0; } } catch (IOException e) { e.printStackTrace(); } if (argumentIndices == null) { argumentIndices = new int[items.size()]; for (int i = 0; i < argumentIndices.length; i++){ argumentIndices[i] = i; } } for (final int index : argumentIndices) { Expression item = (Expression)items.elementAt(index); if ((this.selector == Ref) || ((this.selector == Deref) && (item.isObjectExpression()))) { DatabaseTable alias = ((ObjectExpression)item).aliasForTable(((ObjectExpression)item).getDescriptor().getTables().firstElement()); printer.printString(alias.getNameDelimited(printer.getPlatform())); } else if ((this.selector == Count) && (item.isExpressionBuilder())) { printer.printString("*"); } else { item.printSQL(printer); } if (dbStringIndex < getDatabaseStrings().length) { printer.printString(getDatabaseStrings()[dbStringIndex++]); } } } /** * INTERNAL: Print the collection onto the SQL stream. */ public void printJavaCollection(Vector items, ExpressionJavaPrinter printer) { int javaStringIndex = 0; for (int i = 0; i < items.size(); i++) { Expression item = (Expression)items.elementAt(i); item.printJava(printer); if (javaStringIndex < getJavaStrings().length) { printer.printString(getJavaStrings()[javaStringIndex++]); } } } /** * INTERNAL: * For performance, special case printing two children, since it's by far the most common */ public void printDuo(Expression first, Expression second, ExpressionSQLPrinter printer) { // Certain functions don't allow binding on some platforms. if (printer.getPlatform().isDynamicSQLRequiredForFunctions() && !isBindingSupported()) { printer.getCall().setUsesBinding(false); } int dbStringIndex; if (isPrefix()) { printer.printString(getDatabaseStrings()[0]); dbStringIndex = 1; } else { dbStringIndex = 0; } first.printSQL(printer); if (dbStringIndex < getDatabaseStrings().length) { printer.printString(getDatabaseStrings()[dbStringIndex++]); } if (second != null) { second.printSQL(printer); if (dbStringIndex < getDatabaseStrings().length) { printer.printString(getDatabaseStrings()[dbStringIndex++]); } } } /** * INTERNAL: * For performance, special case printing two children, since it's by far the most common */ public void printJavaDuo(Expression first, Expression second, ExpressionJavaPrinter printer) { int javaStringIndex = 0; first.printJava(printer); if (javaStringIndex < getJavaStrings().length) { printer.printString(getJavaStrings()[javaStringIndex++]); } if (second != null) { second.printJava(printer); if (javaStringIndex < getJavaStrings().length) { printer.printString(getJavaStrings()[javaStringIndex]); } } } /** * ADVANCED: * Set the single string for this operator. */ public void printsAs(String s) { Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(1); v.addElement(s); printsAs(v); } /** * ADVANCED: * Set the strings for this operator. */ public void printsAs(Vector dbStrings) { this.databaseStrings = new String[dbStrings.size()]; for (int i = 0; i < dbStrings.size(); i++) { getDatabaseStrings()[i] = (String)dbStrings.elementAt(i); } } /** * ADVANCED: * Set the single string for this operator. */ public void printsJavaAs(String s) { Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(1); v.addElement(s); printsJavaAs(v); } /** * ADVANCED: * Set the strings for this operator. */ public void printsJavaAs(Vector dbStrings) { this.javaStrings = new String[dbStrings.size()]; for (int i = 0; i < dbStrings.size(); i++) { getJavaStrings()[i] = (String)dbStrings.elementAt(i); } } /** * INTERNAL: * Build operator. */ public static ExpressionOperator ref() { return simpleFunction(Ref, "REF"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator refToHex() { return simpleFunction(RefToHex, "REFTOHEX"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator replace() { ExpressionOperator operator = simpleThreeArgumentFunction(Replace, "REPLACE"); operator.setIsBindingSupported(false); return operator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator replicate() { return simpleTwoArgumentFunction(Replicate, "REPLICATE"); } /** * INTERNAL: * Reset all the operators. */ public static void resetOperators() { allOperators = new HashMap(); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator reverse() { return simpleFunction(Reverse, "REVERSE"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator right() { return simpleTwoArgumentFunction(Right, "RIGHT"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator rightPad() { return simpleThreeArgumentFunction(RightPad, "RPAD"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator rightTrim() { return simpleFunction(RightTrim, "RTRIM"); } /** * INTERNAL: * Build rightTrim operator that takes one parameter. * @bug 2916893 rightTrim(substring) broken. */ public static ExpressionOperator rightTrim2() { return simpleTwoArgumentFunction(RightTrim2, "RTRIM"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator round() { return simpleTwoArgumentFunction(Round, "ROUND"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator roundDate() { return simpleTwoArgumentFunction(RoundDate, "ROUND"); } /** * ADVANCED: Set the array of indexes to use when building the SQL function. * * The index of the array is the position in the printout, from left to right, starting with zero. * The value of the array entry is the number of the argument to print at that particular output position. * So each argument can be used zero, one or many times. */ public void setArgumentIndices(int[] indices) { argumentIndices = indices; } /** * ADVANCED: * Set the node class for this operator. For user-defined functions this is * set automatically but can be changed. * <p>A list of Operator types, an example, and the node class used follows. * <p>LogicalOperator AND LogicalExpression * <p>ComparisonOperator <> RelationExpression * <p>AggregateOperator COUNT FunctionExpression * <p>OrderOperator ASCENDING " * <p>FunctionOperator RTRIM " * <p>Node classes given belong to org.eclipse.persistence.internal.expressions. */ public void setNodeClass(Class nodeClass) { this.nodeClass = nodeClass; } /** * INTERNAL: * Set the selector id. */ public void setSelector(int selector) { this.selector = selector; } /** * ADVANCED: * Set the type of function. * This must be one of the static function types defined in this class. */ public void setType(int type) { this.type = type; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator sign() { return simpleFunction(Sign, "SIGN"); } /** * INTERNAL: * Create an operator for a simple aggregate given a Java name and a single * String for the database (parentheses will be added automatically). */ public static ExpressionOperator simpleAggregate(int selector, String databaseName, String javaName) { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(AggregateOperator); exOperator.setSelector(selector); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(2); v.addElement(databaseName + "("); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.printsJavaAs("." + javaName + "()"); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Create an operator for a simple function given a Java name and a single * String for the database (parentheses will be added automatically). */ public static ExpressionOperator simpleFunction(int selector, String databaseName) { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(selector); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(2); v.addElement(databaseName + "("); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Create an operator for a simple function call without parentheses */ public static ExpressionOperator simpleFunctionNoParentheses(int selector, String databaseName) { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(selector); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(1); v.addElement(databaseName); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Create an operator for a simple function given a Java name and a single * String for the database (parentheses will be added automatically). */ public static ExpressionOperator simpleFunction(int selector, String databaseName, String javaName) { ExpressionOperator exOperator = simpleFunction(selector, databaseName); exOperator.printsJavaAs("." + javaName + "()"); return exOperator; } /** * INTERNAL: * Create an operator for a simple logical given a Java name and a single * String for the database (parentheses will be added automatically). */ public static ExpressionOperator simpleLogical(int selector, String databaseName, String javaName) { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(LogicalOperator); exOperator.setSelector(selector); exOperator.printsAs(" " + databaseName + " "); exOperator.bePostfix(); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(2); v.addElement("." + javaName + "("); v.addElement(")"); exOperator.printsJavaAs(v); exOperator.setNodeClass(ClassConstants.LogicalExpression_Class); return exOperator; } /** * INTERNAL: * Create an operator for a simple math operatin, i.e. +, -, *, / */ public static ExpressionOperator simpleMath(int selector, String databaseName) { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setIsBindingSupported(false); exOperator.setType(FunctionOperator); exOperator.setSelector(selector); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(3); v.addElement("("); v.addElement(" " + databaseName + " "); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Create an operator for a simple ordering given a Java name and a single * String for the database (parentheses will be added automatically). */ public static ExpressionOperator simpleOrdering(int selector, String databaseName, String javaName) { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(OrderOperator); exOperator.setSelector(selector); exOperator.printsAs(" " + databaseName); exOperator.bePostfix(); exOperator.printsJavaAs("." + javaName + "()"); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Create an operator for a simple relation given a Java name and a single * String for the database (parentheses will be added automatically). */ public static ExpressionOperator simpleRelation(int selector, String databaseName) { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(ComparisonOperator); exOperator.setSelector(selector); exOperator.printsAs(" " + databaseName + " "); exOperator.bePostfix(); exOperator.setNodeClass(ClassConstants.RelationExpression_Class); return exOperator; } /** * INTERNAL: * Create an operator for a simple relation given a Java name and a single * String for the database (parentheses will be added automatically). */ public static ExpressionOperator simpleRelation(int selector, String databaseName, String javaName) { ExpressionOperator exOperator = simpleRelation(selector, databaseName); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(2); v.addElement("." + javaName + "("); v.addElement(")"); exOperator.printsJavaAs(v); return exOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator simpleThreeArgumentFunction(int selector, String dbString) { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(selector); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(4); v.addElement(dbString + "("); v.addElement(", "); v.addElement(", "); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator simpleTwoArgumentFunction(int selector, String dbString) { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(selector); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(5); v.addElement(dbString + "("); v.addElement(", "); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * e.g.: ... "Bob" CONCAT "Smith" ... * Parentheses will not be addded. [RMB - March 5 2000] */ public static ExpressionOperator simpleLogicalNoParens(int selector, String dbString) { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(selector); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(5); v.addElement(""); v.addElement(" " + dbString + " "); v.addElement(""); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator sin() { return simpleFunction(Sin, "SIN"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator sinh() { return simpleFunction(Sinh, "SINH"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator soundex() { return simpleFunction(Soundex, "SOUNDEX"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator sqrt() { return simpleFunction(Sqrt, "SQRT"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator standardDeviation() { return simpleAggregate(StandardDeviation, "STDDEV", "standardDeviation"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator substring() { ExpressionOperator operator = simpleThreeArgumentFunction(Substring, "SUBSTR"); operator.setIsBindingSupported(false); return operator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator substringSingleArg() { return simpleTwoArgumentFunction(SubstringSingleArg, "SUBSTR"); } /** * INTERNAL: * Create the SUM operator. */ public static ExpressionOperator sum() { return simpleAggregate(Sum, "SUM", "sum"); } /** * INTERNAL: * Function, to add months to a date. */ public static ExpressionOperator sybaseAddMonthsOperator() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(AddMonths); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(3); v.addElement("DATEADD(month, "); v.addElement(", "); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); int[] indices = { 1, 0 }; exOperator.setArgumentIndices(indices); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator sybaseAtan2Operator() { return ExpressionOperator.simpleTwoArgumentFunction(Atan2, "ATN2"); } /** * INTERNAL: * Build instring operator */ public static ExpressionOperator sybaseInStringOperator() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(Instring); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(3); v.addElement("CHARINDEX("); v.addElement(", "); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); int[] indices = { 1, 0 }; exOperator.setArgumentIndices(indices); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build Sybase equivalent to TO_NUMBER. */ public static ExpressionOperator sybaseToNumberOperator() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(ToNumber); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(2); v.addElement("CONVERT(NUMERIC, "); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build Sybase equivalent to TO_CHAR. */ public static ExpressionOperator sybaseToDateToStringOperator() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(DateToString); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(2); v.addElement("CONVERT(CHAR, "); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build Sybase equivalent to TO_DATE. */ public static ExpressionOperator sybaseToDateOperator() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(ToDate); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(2); v.addElement("CONVERT(DATETIME, "); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build Sybase equivalent to TO_CHAR. */ public static ExpressionOperator sybaseToCharOperator() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(ToChar); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(2); v.addElement("CONVERT(CHAR, "); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build Sybase equivalent to TO_CHAR. */ public static ExpressionOperator sybaseToCharWithFormatOperator() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(ToCharWithFormat); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(3); v.addElement("CONVERT(CHAR, "); v.addElement(","); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build the Sybase equivalent to Locate */ public static ExpressionOperator sybaseLocateOperator() { ExpressionOperator result = simpleTwoArgumentFunction(ExpressionOperator.Locate, "CHARINDEX"); int[] argumentIndices = new int[2]; argumentIndices[0] = 1; argumentIndices[1] = 0; result.setArgumentIndices(argumentIndices); return result; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator tan() { return simpleFunction(Tan, "TAN"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator tanh() { return simpleFunction(Tanh, "TANH"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator toDate() { return simpleFunction(ToDate, "TO_DATE"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator today() { return currentTimeStamp(); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator currentTimeStamp() { return simpleFunctionNoParentheses(Today, "CURRENT_TIMESTAMP"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator currentDate() { return simpleFunctionNoParentheses(CurrentDate, "CURRENT_DATE"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator currentTime() { return simpleFunctionNoParentheses(CurrentTime, "CURRENT_TIME"); } /** * INTERNAL: * Create the toLowerCase operator. */ public static ExpressionOperator toLowerCase() { return simpleFunction(ToLowerCase, "LOWER", "toLowerCase"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator toNumber() { return simpleFunction(ToNumber, "TO_NUMBER"); } /** * Print a debug representation of this operator. */ public String toString() { if ((getDatabaseStrings() == null) || (getDatabaseStrings().length == 0)) { //CR#... Print a useful name for the missing platform operator. return "platform operator - " + getPlatformOperatorName(this.selector); } else { return "operator " + Arrays.asList(getDatabaseStrings()); } } /** * INTERNAL: * Create the TOUPPERCASE operator. */ public static ExpressionOperator toUpperCase() { return simpleFunction(ToUpperCase, "UPPER", "toUpperCase"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator translate() { ExpressionOperator operator = simpleThreeArgumentFunction(Translate, "TRANSLATE"); operator.setIsBindingSupported(false); return operator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator trim() { return simpleFunction(Trim, "TRIM"); } /** * INTERNAL: * Build Trim operator. */ public static ExpressionOperator trim2() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(Trim2); Vector v = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(5); v.addElement("TRIM("); v.addElement(" FROM "); v.addElement(")"); exOperator.printsAs(v); exOperator.bePrefix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Build operator. */ public static ExpressionOperator trunc() { return simpleTwoArgumentFunction(Trunc, "TRUNC"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator truncateDate() { return simpleTwoArgumentFunction(TruncateDate, "TRUNC"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator value() { return simpleFunction(Value, "VALUE"); } /** * INTERNAL: * Build operator. */ public static ExpressionOperator variance() { return simpleAggregate(Variance, "VARIANCE", "variance"); } /** * INTERNAL: * Create the ANY operator. */ public static ExpressionOperator any() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(Any); exOperator.printsAs("ANY"); exOperator.bePostfix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Create the SOME operator. */ public static ExpressionOperator some() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(Some); exOperator.printsAs("SOME"); exOperator.bePostfix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Create the ALL operator. */ public static ExpressionOperator all() { ExpressionOperator exOperator = new ExpressionOperator(); exOperator.setType(FunctionOperator); exOperator.setSelector(All); exOperator.printsAs("ALL"); exOperator.bePostfix(); exOperator.setNodeClass(ClassConstants.FunctionExpression_Class); return exOperator; } /** * INTERNAL: * Indicates whether operator has selector Any or Some */ public boolean isAny() { return selector == ExpressionOperator.Any || selector == ExpressionOperator.Some; } /** * INTERNAL: * Indicates whether operator has selector All */ public boolean isAll() { return selector == ExpressionOperator.All; } /** * INTERNAL: * Indicates whether operator has selector Any, Some or All */ public boolean isAnyOrAll() { return isAny() || isAll(); } }
package GUI; import java.awt.Cursor; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import javax.swing.JPanel; import logic.ViasBoyaca; public class PanelAcciones extends JPanel implements ActionListener{ private PanelCrearCiudad panelCrearCiudad; private PanelCrearVia panelCrearVia; private PanelBorrar panelBorrar; private PanelCrear panelCrear; private PanelRecorrido panelRecorrido; private JPanel panelDerecha; private JPanel panelIzquierda; private PanelMapa panelMapa; private boolean[] presionado; private BorrarCiudad borrarCiudad; private BorrarVia borrarVia; private VentanaPrincipal principal; public PanelAcciones(VentanaPrincipal ven) { this.principal = ven; setPreferredSize(new Dimension((ven.getWidth()),200)); setLayout(new GridLayout(1, 3)); panelCrear = new PanelCrear(ven, this); panelCrear.setBounds(0, 0, panelCrear.getWidth(), panelCrear.getHeight()); panelCrearCiudad = new PanelCrearCiudad(ven,this); panelCrearCiudad.setVisible(false); panelCrearCiudad.setBounds(0, 0, panelCrearCiudad.getWidth(), panelCrearCiudad.getHeight()); panelCrearVia = new PanelCrearVia(ven, this); panelCrearVia.setVisible(false); panelCrearVia.setBounds(0, 0, panelCrearVia.getWidth(), panelCrearVia.getHeight()); panelDerecha = new JPanel(); panelDerecha.setPreferredSize(this.getPreferredSize()); panelDerecha.add(panelCrear); panelDerecha.add(panelCrearCiudad); panelDerecha.add(panelCrearVia); panelBorrar = new PanelBorrar(ven, this); panelBorrar.setBounds(0, 0, panelBorrar.getWidth(), panelBorrar.getHeight()); borrarCiudad = new BorrarCiudad(ven, this); borrarCiudad.setVisible(false); borrarCiudad.setBounds(0, 0, borrarCiudad.getWidth(), borrarCiudad.getHeight()); borrarVia = new BorrarVia(ven, this); borrarVia.setVisible(false); borrarCiudad.setBounds(0, 0, borrarCiudad.getWidth(), borrarCiudad.getHeight()); panelRecorrido = new PanelRecorrido(ven,this); panelIzquierda = new JPanel(); panelIzquierda.setPreferredSize(this.getPreferredSize()); panelIzquierda.add(panelBorrar); panelIzquierda.add(borrarCiudad); panelIzquierda.add(borrarVia); presionado = new boolean[2]; add(panelDerecha); add(panelRecorrido); add(panelIzquierda); } public PanelMapa getPanelMapa() { return panelMapa; } public void setPanelMapa(PanelMapa panelMapa) { this.panelMapa = panelMapa; } public boolean validarNombre() { return panelCrearCiudad.validarNombre(); } public PanelCrearCiudad getPanelCrearCiudad() { return panelCrearCiudad; } public void setPanelCrearCiudad(PanelCrearCiudad panelCrearCiudad) { this.panelCrearCiudad = panelCrearCiudad; } public PanelCrearVia getPanelCrearVia() { return panelCrearVia; } public void setPanelCrearVia(PanelCrearVia panelCrearVia) { this.panelCrearVia = panelCrearVia; } public boolean[] getPresionado() { return presionado; } public void setPresionado(boolean[] presionado) { this.presionado = presionado; } public void ActualizarCiudadesRecorrido(){ panelRecorrido.actualizarCiudades(principal.getBoyaca().getCiudades()); } @Override public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); switch (comando) { case PanelCrear.BTN_CREAR_CIUDAD: panelCrear.setVisible(false); panelCrearVia.setVisible(false); panelCrearCiudad.setVisible(true); panelMapa.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); presionado[0] = true; JOptionPane.showMessageDialog(panelMapa, " Para crear una ciudad " + "o municipio \n primero tendra que " + "llenar el formulario \n y luego dar " + "clic en el boton aceptar \n finalmente " + "tendra que posicionar el mouse\n en el lugar " + "deseado y dar clic.","Crear Ciudad", JOptionPane.INFORMATION_MESSAGE); break; case PanelCrear.BTN_CREAR_VIA: panelCrear.setVisible(false); panelCrearCiudad.setVisible(false); panelCrearVia.setVisible(true); panelMapa.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); presionado[1] = true; JOptionPane.showMessageDialog(panelMapa, "Para crear una via " + "primero tendra que seleccionar 2 ciudades \n" + "y llenar el formulario luego dar clic en el boton aceptar \n" + "y finalmente se creara la via.", "Crear Via", JOptionPane.INFORMATION_MESSAGE); break; case PanelCrearCiudad.BTN_ACEPTAR: panelCrearCiudad.datos(); break; case PanelCrearCiudad.BTN_VOLVER: panelCrear.setVisible(true); panelMapa.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); presionado[0] = false; break; case PanelCrearVia.BTN_VOLVER: panelCrear.setVisible(true); panelMapa.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); presionado[1] = false; break; case VentanaPrincipal.COMANDO_ABOUT: principal.ShowAbout(); break; case PanelBorrar.BTN_BORRAR_CIUDAD: borrarCiudad.actualizarCiudades(principal.getBoyaca().getCiudades()); panelBorrar.setVisible(false); borrarCiudad.setVisible(true); break; case PanelCrearVia.BTN_CREAR_VIA: panelMapa.crearVia(); panelMapa.limpiarCiudades(); panelCrearVia.limpiarCampos(); break; case BorrarCiudad.BTN_VOLVER: borrarCiudad.setVisible(false); panelBorrar.setVisible(true); break; case BorrarCiudad.BTN_ACEPTAR: borrarCiudad.eliminarCiudad(principal.getBoyaca().getCiudades()); borrarCiudad.actualizarCiudades(principal.getBoyaca().getCiudades()); panelRecorrido.actualizarCiudades(principal.getBoyaca().getCiudades()); panelMapa.repaint(); break; case PanelBorrar.BTN_BORRAR_VIA: borrarVia.actualizarVias(principal.getBoyaca().getVias()); panelBorrar.setVisible(false); borrarVia.setVisible(true); break; case BorrarVia.BTN_VOLVER: borrarVia.setVisible(false); panelBorrar.setVisible(true); break; case BorrarVia.BTN_ACEPTAR: borrarVia.eliminarVia(principal.getBoyaca().getVias()); borrarVia.actualizarVias(principal.getBoyaca().getVias()); panelMapa.repaint(); break; default: break; } } }
package org.innovateuk.ifs.testdata.builders; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import org.apache.commons.lang3.tuple.Pair; import org.innovateuk.ifs.BaseBuilder; import org.innovateuk.ifs.affiliation.transactional.AffiliationService; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.application.mapper.IneligibleOutcomeMapper; import org.innovateuk.ifs.application.repository.ApplicationRepository; import org.innovateuk.ifs.application.repository.FormInputResponseRepository; import org.innovateuk.ifs.application.transactional.*; import org.innovateuk.ifs.assessment.repository.AssessmentInviteRepository; import org.innovateuk.ifs.assessment.repository.AssessmentParticipantRepository; import org.innovateuk.ifs.assessment.repository.AssessmentRepository; import org.innovateuk.ifs.assessment.transactional.AssessmentInviteService; import org.innovateuk.ifs.assessment.transactional.AssessmentService; import org.innovateuk.ifs.assessment.transactional.AssessorFormInputResponseService; import org.innovateuk.ifs.assessment.transactional.AssessorService; import org.innovateuk.ifs.assessment.workflow.configuration.AssessmentWorkflowHandler; import org.innovateuk.ifs.category.repository.CategoryRepository; import org.innovateuk.ifs.category.repository.InnovationAreaRepository; import org.innovateuk.ifs.category.repository.InnovationSectorRepository; import org.innovateuk.ifs.category.repository.ResearchCategoryRepository; import org.innovateuk.ifs.competition.domain.Competition; import org.innovateuk.ifs.competition.repository.*; import org.innovateuk.ifs.competition.transactional.CompetitionApplicationConfigService; import org.innovateuk.ifs.competition.transactional.CompetitionAssessmentConfigService; import org.innovateuk.ifs.competition.transactional.CompetitionService; import org.innovateuk.ifs.competition.transactional.MilestoneService; import org.innovateuk.ifs.competitionsetup.repository.CompetitionDocumentConfigRepository; import org.innovateuk.ifs.competitionsetup.transactional.CompetitionSetupFinanceService; import org.innovateuk.ifs.competitionsetup.transactional.CompetitionSetupService; import org.innovateuk.ifs.file.repository.FileEntryRepository; import org.innovateuk.ifs.finance.repository.ApplicationFinanceRepository; import org.innovateuk.ifs.finance.resource.cost.FinanceRowItem; import org.innovateuk.ifs.finance.resource.cost.FinanceRowType; import org.innovateuk.ifs.finance.transactional.ApplicationFinanceRowService; import org.innovateuk.ifs.finance.transactional.ApplicationFinanceService; import org.innovateuk.ifs.finance.transactional.GrantClaimMaximumService; import org.innovateuk.ifs.finance.transactional.ProjectFinanceService; import org.innovateuk.ifs.form.repository.FormInputRepository; import org.innovateuk.ifs.form.repository.QuestionRepository; import org.innovateuk.ifs.form.repository.SectionRepository; import org.innovateuk.ifs.form.resource.FormInputResource; import org.innovateuk.ifs.form.resource.QuestionResource; import org.innovateuk.ifs.form.transactional.FormInputService; import org.innovateuk.ifs.form.transactional.QuestionService; import org.innovateuk.ifs.form.transactional.SectionService; import org.innovateuk.ifs.fundingdecision.transactional.ApplicationFundingService; import org.innovateuk.ifs.interview.repository.InterviewInviteRepository; import org.innovateuk.ifs.interview.transactional.InterviewAllocationService; import org.innovateuk.ifs.interview.transactional.InterviewAssignmentService; import org.innovateuk.ifs.interview.transactional.InterviewInviteService; import org.innovateuk.ifs.invite.repository.ApplicationInviteRepository; import org.innovateuk.ifs.invite.transactional.*; import org.innovateuk.ifs.organisation.domain.Organisation; import org.innovateuk.ifs.organisation.repository.OrganisationRepository; import org.innovateuk.ifs.organisation.resource.OrganisationResource; import org.innovateuk.ifs.organisation.transactional.OrganisationInitialCreationService; import org.innovateuk.ifs.organisation.transactional.OrganisationService; import org.innovateuk.ifs.organisation.transactional.OrganisationTypeService; import org.innovateuk.ifs.procurement.milestone.transactional.ApplicationProcurementMilestoneService; import org.innovateuk.ifs.profile.repository.ProfileRepository; import org.innovateuk.ifs.profile.transactional.ProfileService; import org.innovateuk.ifs.project.bankdetails.transactional.BankDetailsService; import org.innovateuk.ifs.project.core.repository.PartnerOrganisationRepository; import org.innovateuk.ifs.project.core.repository.ProjectRepository; import org.innovateuk.ifs.project.core.repository.ProjectUserRepository; import org.innovateuk.ifs.project.core.transactional.ProjectService; import org.innovateuk.ifs.project.documents.mapper.ProjectDocumentsMapper; import org.innovateuk.ifs.project.documents.repository.ProjectDocumentRepository; import org.innovateuk.ifs.project.documents.transactional.DocumentsService; import org.innovateuk.ifs.project.financechecks.service.FinanceCheckService; import org.innovateuk.ifs.project.grantofferletter.transactional.GrantOfferLetterService; import org.innovateuk.ifs.project.monitoringofficer.transactional.LegacyMonitoringOfficerService; import org.innovateuk.ifs.project.projectdetails.transactional.ProjectDetailsService; import org.innovateuk.ifs.project.spendprofile.transactional.SpendProfileService; import org.innovateuk.ifs.project.state.transactional.ProjectStateService; import org.innovateuk.ifs.publiccontent.repository.ContentEventRepository; import org.innovateuk.ifs.publiccontent.repository.ContentGroupRepository; import org.innovateuk.ifs.publiccontent.repository.PublicContentRepository; import org.innovateuk.ifs.publiccontent.transactional.ContentGroupService; import org.innovateuk.ifs.publiccontent.transactional.PublicContentService; import org.innovateuk.ifs.question.transactional.QuestionSetupCompetitionService; import org.innovateuk.ifs.question.transactional.template.QuestionSetupAddAndRemoveService; import org.innovateuk.ifs.review.repository.ReviewInviteRepository; import org.innovateuk.ifs.review.transactional.ReviewInviteService; import org.innovateuk.ifs.review.transactional.ReviewService; import org.innovateuk.ifs.supporter.transactional.SupporterAssignmentService; import org.innovateuk.ifs.testdata.services.TestService; import org.innovateuk.ifs.token.repository.TokenRepository; import org.innovateuk.ifs.token.transactional.TokenService; import org.innovateuk.ifs.user.domain.ProcessRole; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.repository.ProcessRoleRepository; import org.innovateuk.ifs.user.repository.RoleProfileStatusRepository; import org.innovateuk.ifs.user.repository.UserRepository; import org.innovateuk.ifs.user.resource.ProcessRoleResource; import org.innovateuk.ifs.user.resource.ProcessRoleType; import org.innovateuk.ifs.user.resource.Role; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.transactional.*; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Supplier; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.innovateuk.ifs.commons.BaseIntegrationTest.setLoggedInUser; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.user.resource.Role.*; import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst; /** * Base Builder for persistent data builders. Wraps each build step in a transaction. Provides a location for * service lookup. */ public abstract class BaseDataBuilder<T, S> extends BaseBuilder<T, S> { public static final String IFS_SYSTEM_MAINTENANCE_USER_EMAIL = "[email protected]"; public static final String IFS_SYSTEM_REGISTRAR_USER_EMAIL = "[email protected]"; protected ServiceLocator serviceLocator; protected String compAdminEmail; protected String projectFinanceEmail; protected BaseUserService baseUserService; protected UserService userService; protected CompetitionService competitionService; protected CompetitionTypeRepository competitionTypeRepository; protected CategoryRepository categoryRepository; protected InnovationAreaRepository innovationAreaRepository; protected InnovationSectorRepository innovationSectorRepository; protected ResearchCategoryRepository researchCategoryRepository; protected CompetitionSetupService competitionSetupService; protected GrantClaimMaximumService grantClaimMaximumService; protected QuestionSetupService questionSetupService; protected QuestionSetupCompetitionService questionSetupCompetitionService; protected QuestionSetupAddAndRemoveService questionSetupAddAndRemoveService; protected PublicContentService publicContentService; protected CompetitionSetupFinanceService competitionSetupFinanceService; protected PublicContentRepository publicContentRepository; protected ContentGroupRepository contentGroupRepository; protected ContentGroupService contentGroupService; protected ContentEventRepository contentEventRepository; protected OrganisationService organisationService; protected OrganisationInitialCreationService organisationInitialCreationService; protected OrganisationTypeService organisationTypeService; protected UserRepository userRepository; protected ProfileRepository profileRepository; protected RegistrationService registrationService; protected OrganisationRepository organisationRepository; protected TokenRepository tokenRepository; protected TokenService tokenService; protected ApplicationInviteService applicationInviteService; protected AcceptApplicationInviteService acceptApplicationInviteService; protected ApplicationKtaInviteService ktaInviteService; protected MilestoneService milestoneService; protected ApplicationService applicationService; protected ApplicationNotificationService applicationNotificationService; protected QuestionService questionService; protected QuestionStatusService questionStatusService; protected TestQuestionService testQuestionService; protected FormInputService formInputService; protected FormInputResponseService formInputResponseService; protected FormInputResponseRepository formInputResponseRepository; protected ApplicationRepository applicationRepository; protected ApplicationFundingService applicationFundingService; protected ProjectService projectService; protected ProjectStateService projectStateService; protected ProjectDetailsService projectDetailsService; protected LegacyMonitoringOfficerService monitoringOfficerService; protected ApplicationFinanceRowService financeRowCostsService; protected SectionService sectionService; protected SectionStatusService sectionStatusService; protected UsersRolesService usersRolesService; protected ApplicationInviteRepository applicationInviteRepository; protected AssessmentInviteRepository assessmentInviteRepository; protected CompetitionRepository competitionRepository; protected CompetitionFunderRepository competitionFunderRepository; protected AssessorService assessorService; protected AssessmentParticipantRepository assessmentParticipantRepository; protected AssessmentInviteService assessmentInviteService; protected TestService testService; protected AssessmentRepository assessmentRepository; protected AssessmentService assessmentService; protected AssessmentWorkflowHandler assessmentWorkflowHandler; protected ReviewInviteRepository reviewInviteRepository; protected ReviewInviteService reviewInviteService; protected ReviewService reviewService; protected InterviewInviteRepository interviewInviteRepository; protected InterviewInviteService interviewInviteService; protected InterviewAssignmentService interviewAssignmentService; protected InterviewAllocationService interviewAllocationService; protected ProcessRoleRepository processRoleRepository; protected SectionRepository sectionRepository; protected QuestionRepository questionRepository; protected FormInputRepository formInputRepository; protected FileEntryRepository fileEntryRepository; protected ProjectDocumentRepository projectDocumentRepository; protected DocumentsService documentsService; protected ProjectRepository projectRepository; protected CompetitionDocumentConfigRepository competitionDocumentConfigRepository; protected PartnerOrganisationRepository partnerOrganisationRepository; protected ApplicationFinanceRepository applicationFinanceRepository; protected ProjectUserRepository projectUserRepository; protected BankDetailsService bankDetailsService; protected SpendProfileService spendProfileService; protected ProjectFinanceService projectFinanceService; protected FinanceCheckService financeCheckService; protected RejectionReasonService rejectionReasonService; protected ProfileService profileService; protected AffiliationService affiliationService; protected ApplicationInnovationAreaService applicationInnovationAreaService; protected AssessorFormInputResponseService assessorFormInputResponseService; protected IneligibleOutcomeMapper ineligibleOutcomeMapper; protected ProjectDocumentsMapper projectDocumentsMapper; protected ApplicationResearchCategoryService applicationResearchCategoryService; protected ApplicationFinanceService financeService; protected GrantOfferLetterService grantOfferLetterService; protected RoleProfileStatusService roleProfileStatusService; protected RoleProfileStatusRepository roleProfileStatusRepository; protected CompetitionOrganisationConfigRepository competitionOrganisationConfigRepository; protected CompetitionAssessmentConfigService competitionAssessmentConfigService; protected InviteUserService inviteUserService; protected SupporterAssignmentService supporterAssignmentService; protected ApplicationProcurementMilestoneService applicationProcurementMilestoneService; protected CompetitionApplicationConfigService competitionApplicationConfigService; protected MilestoneRepository milestoneRepository; protected AssessmentPeriodRepository assessmentPeriodRepository; private static Cache<Long, List<QuestionResource>> questionsByCompetitionId = CacheBuilder.newBuilder().build(); private static Cache<Long, List<FormInputResource>> formInputsByQuestionId = CacheBuilder.newBuilder().build(); private static Cache<String, UserResource> usersByEmailAddress = CacheBuilder.newBuilder().build(); private static Cache<String, UserResource> usersByEmailAddressInternal = CacheBuilder.newBuilder().build(); private static Cache<Long, UserResource> usersById = CacheBuilder.newBuilder().build(); private static Cache<Pair<Long, String>, ProcessRoleResource> applicantsByApplicationIdAndEmail = CacheBuilder.newBuilder().build(); private static Cache<Long, ProcessRoleResource> leadApplicantsByApplicationId = CacheBuilder.newBuilder().build(); private static Cache<String, OrganisationResource> organisationsByName = CacheBuilder.newBuilder().build(); public BaseDataBuilder(List<BiConsumer<Integer, T>> newActions, ServiceLocator serviceLocator) { super(newActions); this.serviceLocator = serviceLocator; userService = serviceLocator.getBean(UserService.class); competitionService = serviceLocator.getBean(CompetitionService.class); competitionTypeRepository = serviceLocator.getBean(CompetitionTypeRepository.class); categoryRepository = serviceLocator.getBean(CategoryRepository.class); competitionSetupService = serviceLocator.getBean(CompetitionSetupService.class); grantClaimMaximumService = serviceLocator.getBean(GrantClaimMaximumService.class); organisationService = serviceLocator.getBean(OrganisationService.class); organisationInitialCreationService = serviceLocator.getBean(OrganisationInitialCreationService.class); organisationTypeService = serviceLocator.getBean(OrganisationTypeService.class); userRepository = serviceLocator.getBean(UserRepository.class); registrationService = serviceLocator.getBean(RegistrationService.class); organisationRepository = serviceLocator.getBean(OrganisationRepository.class); tokenRepository = serviceLocator.getBean(TokenRepository.class); tokenService = serviceLocator.getBean(TokenService.class); applicationInviteService = serviceLocator.getBean(ApplicationInviteService.class); acceptApplicationInviteService = serviceLocator.getBean(AcceptApplicationInviteService.class); ktaInviteService = serviceLocator.getBean(ApplicationKtaInviteService.class); milestoneService = serviceLocator.getBean(MilestoneService.class); applicationService = serviceLocator.getBean(ApplicationService.class); applicationNotificationService = serviceLocator.getBean(ApplicationNotificationService.class); questionService = serviceLocator.getBean(QuestionService.class); questionStatusService = serviceLocator.getBean(QuestionStatusService.class); testQuestionService = serviceLocator.getBean(TestQuestionService.class); formInputService = serviceLocator.getBean(FormInputService.class); formInputResponseService = serviceLocator.getBean(FormInputResponseService.class); formInputResponseRepository = serviceLocator.getBean(FormInputResponseRepository.class); applicationRepository = serviceLocator.getBean(ApplicationRepository.class); applicationFundingService = serviceLocator.getBean(ApplicationFundingService.class); projectService = serviceLocator.getBean(ProjectService.class); projectStateService = serviceLocator.getBean(ProjectStateService.class); projectDetailsService = serviceLocator.getBean(ProjectDetailsService.class); monitoringOfficerService = serviceLocator.getBean(LegacyMonitoringOfficerService.class); financeRowCostsService = serviceLocator.getBean(ApplicationFinanceRowService.class); financeService = serviceLocator.getBean(ApplicationFinanceService.class); sectionService = serviceLocator.getBean(SectionService.class); sectionStatusService = serviceLocator.getBean(SectionStatusService.class); usersRolesService = serviceLocator.getBean(UsersRolesService.class); applicationInviteRepository = serviceLocator.getBean(ApplicationInviteRepository.class); assessmentInviteRepository = serviceLocator.getBean(AssessmentInviteRepository.class); competitionRepository = serviceLocator.getBean(CompetitionRepository.class); assessorService = serviceLocator.getBean(AssessorService.class); assessmentParticipantRepository = serviceLocator.getBean(AssessmentParticipantRepository.class); assessmentInviteService = serviceLocator.getBean(AssessmentInviteService.class); testService = serviceLocator.getBean(TestService.class); assessmentRepository = serviceLocator.getBean(AssessmentRepository.class); assessmentService = serviceLocator.getBean(AssessmentService.class); assessmentWorkflowHandler = serviceLocator.getBean(AssessmentWorkflowHandler.class); reviewInviteRepository = serviceLocator.getBean(ReviewInviteRepository.class); reviewInviteService = serviceLocator.getBean(ReviewInviteService.class); reviewService = serviceLocator.getBean(ReviewService.class); interviewInviteRepository = serviceLocator.getBean(InterviewInviteRepository.class); interviewInviteService = serviceLocator.getBean(InterviewInviteService.class); interviewAssignmentService = serviceLocator.getBean(InterviewAssignmentService.class); interviewAllocationService = serviceLocator.getBean(InterviewAllocationService.class); processRoleRepository = serviceLocator.getBean(ProcessRoleRepository.class); sectionRepository = serviceLocator.getBean(SectionRepository.class); questionRepository = serviceLocator.getBean(QuestionRepository.class); questionSetupService = serviceLocator.getBean(QuestionSetupService.class); questionSetupCompetitionService = serviceLocator.getBean(QuestionSetupCompetitionService.class); questionSetupAddAndRemoveService = serviceLocator.getBean(QuestionSetupAddAndRemoveService.class); formInputRepository = serviceLocator.getBean(FormInputRepository.class); fileEntryRepository = serviceLocator.getBean(FileEntryRepository.class); documentsService = serviceLocator.getBean(DocumentsService.class); projectDocumentRepository = serviceLocator.getBean(ProjectDocumentRepository.class); projectRepository = serviceLocator.getBean(ProjectRepository.class); competitionDocumentConfigRepository = serviceLocator.getBean(CompetitionDocumentConfigRepository.class); partnerOrganisationRepository = serviceLocator.getBean(PartnerOrganisationRepository.class); applicationFinanceRepository = serviceLocator.getBean(ApplicationFinanceRepository.class); projectUserRepository = serviceLocator.getBean(ProjectUserRepository.class); bankDetailsService = serviceLocator.getBean(BankDetailsService.class); spendProfileService = serviceLocator.getBean(SpendProfileService.class); financeCheckService = serviceLocator.getBean(FinanceCheckService.class); competitionFunderRepository = serviceLocator.getBean(CompetitionFunderRepository.class); innovationAreaRepository = serviceLocator.getBean(InnovationAreaRepository.class); innovationSectorRepository = serviceLocator.getBean(InnovationSectorRepository.class); researchCategoryRepository = serviceLocator.getBean(ResearchCategoryRepository.class); rejectionReasonService = serviceLocator.getBean(RejectionReasonService.class); profileService = serviceLocator.getBean(ProfileService.class); affiliationService = serviceLocator.getBean(AffiliationService.class); baseUserService = serviceLocator.getBean(BaseUserService.class); profileRepository = serviceLocator.getBean(ProfileRepository.class); publicContentService = serviceLocator.getBean(PublicContentService.class); competitionSetupFinanceService = serviceLocator.getBean(CompetitionSetupFinanceService.class); publicContentRepository = serviceLocator.getBean(PublicContentRepository.class); contentEventRepository = serviceLocator.getBean(ContentEventRepository.class); contentGroupRepository = serviceLocator.getBean(ContentGroupRepository.class); contentGroupService = serviceLocator.getBean(ContentGroupService.class); assessorFormInputResponseService = serviceLocator.getBean(AssessorFormInputResponseService.class); applicationInnovationAreaService = serviceLocator.getBean(ApplicationInnovationAreaService.class); ineligibleOutcomeMapper = serviceLocator.getBean(IneligibleOutcomeMapper.class); projectDocumentsMapper = serviceLocator.getBean(ProjectDocumentsMapper.class); applicationResearchCategoryService = serviceLocator.getBean(ApplicationResearchCategoryService.class); grantOfferLetterService = serviceLocator.getBean(GrantOfferLetterService.class); roleProfileStatusService = serviceLocator.getBean(RoleProfileStatusService.class); roleProfileStatusRepository = serviceLocator.getBean((RoleProfileStatusRepository.class)); compAdminEmail = serviceLocator.getCompAdminEmail(); projectFinanceEmail = serviceLocator.getProjectFinanceEmail(); competitionOrganisationConfigRepository = serviceLocator.getBean((CompetitionOrganisationConfigRepository.class)); competitionAssessmentConfigService = serviceLocator.getBean(CompetitionAssessmentConfigService.class); projectFinanceService = serviceLocator.getBean(ProjectFinanceService.class); inviteUserService = serviceLocator.getBean(InviteUserService.class); supporterAssignmentService = serviceLocator.getBean(SupporterAssignmentService.class); applicationProcurementMilestoneService = serviceLocator.getBean(ApplicationProcurementMilestoneService.class); competitionApplicationConfigService = serviceLocator.getBean(CompetitionApplicationConfigService.class); milestoneRepository = serviceLocator.getBean(MilestoneRepository.class); assessmentPeriodRepository = serviceLocator.getBean(AssessmentPeriodRepository.class); } protected UserResource compAdmin() { return retrieveUserByEmailInternal(compAdminEmail, COMP_ADMIN); } protected UserResource systemRegistrar() { return retrieveUserByEmailInternal(IFS_SYSTEM_REGISTRAR_USER_EMAIL, SYSTEM_REGISTRATION_USER); } protected UserResource projectFinanceUser() { return retrieveUserByEmail(projectFinanceEmail); } protected UserResource ifsAdmin() { return retrieveUserByEmailInternal("[email protected]", IFS_ADMINISTRATOR); } protected UserResource retrieveUserByEmail(String emailAddress) { return fromCache(emailAddress, usersByEmailAddress, () -> doAs(systemRegistrar(), () -> userService.findByEmail(emailAddress).getSuccess())); } protected UserResource retrieveUserById(Long id) { return fromCache(id, usersById, () -> doAs(systemRegistrar(), () -> baseUserService.getUserById(id).getSuccess())); } protected ProcessRoleResource retrieveApplicantByEmail(String emailAddress, Long applicationId) { return fromCache(Pair.of(applicationId, emailAddress), applicantsByApplicationIdAndEmail, () -> { UserResource user = retrieveUserByEmail(emailAddress); return doAs(user, () -> usersRolesService.getProcessRoleByUserIdAndApplicationId(user.getId(), applicationId). getSuccess()); }); } protected ProcessRoleResource retrieveLeadApplicant(Long applicationId) { return fromCache(applicationId, leadApplicantsByApplicationId, () -> doAs(compAdmin(), () -> simpleFindFirst(usersRolesService.getProcessRolesByApplicationId(applicationId). getSuccess(), pr -> pr.getRole() == ProcessRoleType.LEADAPPLICANT).get())); } protected Organisation retrieveOrganisationByName(String organisationName) { return organisationRepository.findOneByName(organisationName); } protected Competition retrieveCompetitionByName(String competitionName) { if (competitionRepository.findByName(competitionName).isEmpty()){ throw new RuntimeException("Unable to find competition with name:" + competitionName); } return competitionRepository.findByName(competitionName).get(0); } protected QuestionResource retrieveQuestionByCompetitionAndName(String questionName, Long competitionId) { return simpleFindFirst(retrieveQuestionsByCompetitionId(competitionId), q -> questionName.equals(q.getName())).get(); } protected List<QuestionResource> retrieveQuestionsByCompetitionId(Long competitionId) { return fromCache(competitionId, questionsByCompetitionId, () -> doAs(compAdmin(), () -> questionService.findByCompetition(competitionId).getSuccess())); } protected List<FormInputResource> retrieveFormInputsByQuestionId(QuestionResource question) { return fromCache(question.getId(), formInputsByQuestionId, () -> formInputService.findByQuestionId(question.getId()).getSuccess()); } protected OrganisationResource retrieveOrganisationResourceByName(String organisationName) { return fromCache(organisationName, organisationsByName, () -> doAs(systemRegistrar(), () -> { Organisation organisation = retrieveOrganisationByName(organisationName); return organisationService.findById(organisation.getId()).getSuccess(); })); } protected ProcessRole retrieveAssessorByApplicationNameAndUser(String applicationName, UserResource user) { return testService.doWithinTransaction(() -> { Application application = applicationRepository.findByName(applicationName).get(0); return processRoleRepository.findByUserAndApplicationId(userRepository.findById(user.getId()).get(), application.getId()) .stream() .filter(x -> x.getRole() == ProcessRoleType.ASSESSOR) .findFirst() .get(); }); } protected <T> T doAs(UserResource user, Supplier<T> action) { UserResource currentUser = setLoggedInUser(user); try { return action.get(); } catch (Exception e) { throw new RuntimeException(e); } finally { setLoggedInUser(currentUser); } } protected void doAs(UserResource user, Runnable action) { UserResource currentUser = setLoggedInUser(user); try { action.run(); } catch (Exception e) { throw new RuntimeException(e); } finally { setLoggedInUser(currentUser); } } protected S asCompAdmin(Consumer<T> action) { return with(data -> doAs(compAdmin(), () -> action.accept(data))); } protected S asIfsAdmin(Consumer<T> action) { return with(data -> doAs(ifsAdmin(), () -> action.accept(data))); } protected UserResource retrieveUserByEmailInternal(String email, Role role) { return fromCache(email, usersByEmailAddressInternal, () -> { User user = userRepository.findByEmail(email).get(); return newUserResource(). withRolesGlobal(asList(role)). withId(user.getId()). build(); }); } protected<K, V> V fromCache(K key, Cache<K, V> cache, Callable<V> loadingFunction) { try { return cache.get(key, loadingFunction); } catch (ExecutionException e) { throw new RuntimeException("Exception encountered whilst reading from Cache", e); } } protected List<FinanceRowItem> getCostItems(long applicationFinanceId, FinanceRowType type) { return financeService.getApplicationFinanceById(applicationFinanceId).andOnSuccess(applicationFinance -> { return financeService.financeDetails(applicationFinance.getApplication(), applicationFinance.getOrganisation()).andOnSuccessReturn(finance -> finance.getFinanceOrganisationDetails().values().stream().flatMap(category -> category.getCosts().stream()) .filter(row -> row.getCostType() == type) .collect(toList()) ); }).getSuccess(); } }
package org.eclipse.persistence.internal.jpa.metamodel; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedActionException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.CollectionAttribute; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.ManagedType; import javax.persistence.metamodel.MapAttribute; import javax.persistence.metamodel.PluralAttribute; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.PluralAttribute.CollectionType; import org.eclipse.persistence.descriptors.RelationalDescriptor; import org.eclipse.persistence.indirection.IndirectSet; import org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor; import org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor; import org.eclipse.persistence.internal.helper.ClassConstants; import org.eclipse.persistence.internal.localization.ExceptionLocalization; import org.eclipse.persistence.internal.queries.ContainerPolicy; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.internal.security.PrivilegedGetDeclaredField; import org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod; import org.eclipse.persistence.mappings.CollectionMapping; import org.eclipse.persistence.mappings.DatabaseMapping; /** * <p> * <b>Purpose</b>: Provides the implementation for the ManagedType interface * of the JPA 2.0 Metamodel API (part of the JSR-317 EJB 3.1 Criteria API) * <p> * <b>Description</b>: * Instances of the type ManagedType represent entities, mapped superclasses * and embeddable types. * * @see javax.persistence.metamodel.ManagedType * * @since EclipseLink 2.0 - JPA 2.0 * @param <X> The represented type. */ public abstract class ManagedTypeImpl<X> extends TypeImpl<X> implements ManagedType<X> { /** Native RelationalDescriptor that contains all the mappings of this type **/ private RelationalDescriptor descriptor; /** The map of attributes keyed on attribute string name **/ protected Map<String, Attribute<X,?>> members; /** Reference to the metamodel that this managed type belongs to **/ protected MetamodelImpl metamodel; /** * INTERNAL: * This constructor will create a ManagedType but will not initialize its member mappings. * This is accomplished by delayed initialization in MetamodelImpl.initialize() * in order that we have access to all types when resolving relationships in mappings. * @param metamodel - the metamodel that this managedType is associated with * @param descriptor - the RelationalDescriptor that defines this managedType */ protected ManagedTypeImpl(MetamodelImpl metamodel, RelationalDescriptor descriptor) { super(descriptor.getJavaClass()); this.descriptor = descriptor; // the metamodel field must be instantiated prior to any *AttributeImpl instantiation which will use the metamodel this.metamodel = metamodel; // Cache the ManagedType on the descriptor descriptor.setProperty(getClass().getName(), this); // Note: Full initialization of the ManagedType occurs during MetamodelImpl.initialize() after all types are instantiated } public Attribute<X, ?> getAttribute(String name) { if(!members.containsKey(name)) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_not_present", new Object[] { name, this })); } return members.get(name); } /** * Return the attributes of the managed type. */ public Set<Attribute<? super X, ?>> getAttributes() { // We return a new Set instead of directly returning the Collection of values from the members HashMap return new HashSet<Attribute<? super X, ?>>(this.members.values()); } public CollectionAttribute<? super X, ?> getCollection(String name) { // Get the named collection from the set directly /* * Note: We do not perform type checking on the get(name) * If the type is not of the correct Attribute implementation class then * a possible CCE will be allowed to propagate to the client. * For example if a getCollection() is performed on a ListAttribute a CCE will occur */ CollectionAttribute<? super X, ?> anAttribute = (CollectionAttribute<? super X, ?>)this.members.get(name); if(null == anAttribute) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_not_present", new Object[] { name, this })); } return anAttribute; } public <E> CollectionAttribute<? super X, E> getCollection(String name, Class<E> elementType) { // We do not use getCollection(name) so that we can catch a possible CCE on the wrong attribute type Attribute<? super X, E> anAttribute = (Attribute<? super X, E>)this.members.get(name); if(null == anAttribute) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_not_present", new Object[] { name, this })); } else { // Throw appropriate IAException if required verifyAttributeTypeAndReturnType(anAttribute, elementType, CollectionType.COLLECTION); } return (CollectionAttribute<? super X, E>)anAttribute; } /** * Return all collection-valued attributes of the managed type. * @return collection valued attributes */ public Set<PluralAttribute<? super X, ?, ?>> getCollections() { // Get all attributes and filter only for PluralAttributes Set<Attribute<? super X, ?>> allAttributes = this.getAttributes(); // Is it better to add to a new Set or remove from an existing Set without a concurrentModificationException Set<PluralAttribute<? super X, ?, ?>> pluralAttributes = new HashSet<PluralAttribute<? super X, ?, ?>>(); for(Iterator<Attribute<? super X, ?>> anIterator = allAttributes.iterator(); anIterator.hasNext();) { Attribute<? super X, ?> anAttribute = anIterator.next(); // Add only CollectionType attributes if(anAttribute.isCollection()) { pluralAttributes.add((PluralAttribute<? super X, ?, ?>)anAttribute); } } return pluralAttributes; } public Attribute<X, ?> getDeclaredAttribute(String name){ // get the attribute parameterized by <Owning type, return Type> - throw an IAE if not found (no need to check hierarchy) // Handles UC1 and UC2 Attribute<X, ?> anAttribute = getAttribute(name); // Check the hierarchy for a declaration in the superclass(s) - keep moving up only when the attribute is not found ManagedTypeImpl aManagedSuperType = getManagedSuperType(); if(null == aManagedSuperType) { return anAttribute; } else { // keep checking the hierarchy but skip this level if(aManagedSuperType.hasDeclaredAttribute(name)) { // Handles UC4 and UC5 throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_declared_attribute_not_present_but_is_on_superclass", new Object[] { name, this })); } else { // Handles UC3 (normal case - attribute is not declared on a superclass) return anAttribute; } } } /** * All getDeclared*(name, *) function calls require navigation up the superclass tree * in order to determine if the member name is declared on the current managedType.<p> * If the attribute is found anywhere above on the superclass tree - then throw an IAE. * Use Case Partitioning: - attribute positioning(none, current, 1st parent, Nth parent) - attribute type (right, wrong type) - attribute classification for current and parents (Entity, MappedSuperclass, embeddable?, Basic?) UC1) Attribute is not found on current attribute (regardless of what is on its' superclasses) - throw IAException UC2) Attribute is found on current attribute but is of the wrong type - throw IAException UC3) Attribute is found on on current managedType Entity/MappedSuperclass (but not found anywhere on the supertype hierarchy - declared above) In this case we do the reverse - keep checking only when attribute is null - return attribute UC4) Attribute is declared on immediate superclass - throw IAException UC5) Attribute is declared on Nth superclass - throw IAException We use two functions, one public, one a private recursive function. If the attribute is not found at the current level or above, or is of the wrong type - throw an IAException If the attribute is found then we still need to search to the top of the hierarchy tree to verify it is not declared above - if it is also not found above - return the attribute in this case only */ /** * Return the attributes declared by the managed type. */ public Set<Attribute<X, ?>> getDeclaredAttributes() { // return only the set of attributes declared on this class - not via inheritance // Get all attributes and filter only for declared attributes Set<Attribute<X, ?>> allAttributes = new HashSet<Attribute<X, ?>>(this.members.values());; // Is it better to add to a new Set or remove from an existing Set without a concurrentModificationException Set<Attribute<X, ?>> declaredAttributes = new HashSet<Attribute<X, ?>>(); for(Iterator<Attribute<X, ?>> anIterator = allAttributes.iterator(); anIterator.hasNext();) { Attribute<? super X, ?> anAttribute = anIterator.next(); // Check the inheritance hierarchy for higher declarations if(this.hasDeclaredAttribute(anAttribute.getName())) { declaredAttributes.add((Attribute<X, ?>)anAttribute); } } return declaredAttributes; } public CollectionAttribute<X, ?> getDeclaredCollection(String name) { // return only a collection declared on this class - not via inheritance // Handles UC1 and UC2 CollectionAttribute<X, ?> anAttribute = (CollectionAttribute<X, ?>) getCollection(name); // The following verification step will throw an appropriate IAException if required (we can discard the return attribute here) getDeclaredAttribute(name); // We return an attribute that has passed through both a get and a declared inheritance check // all of which would throw an IAException before the return below. return anAttribute; } public <E> CollectionAttribute<X, E> getDeclaredCollection(String name, Class<E> elementType) { // return only a collection declared on this class - not via inheritance // Handles UC1 and UC2 CollectionAttribute<X, E> anAttribute = (CollectionAttribute<X, E>) getCollection(name, elementType); // The following verification step will throw an appropriate IAException if required (type checking has been done, and we can discard the return attribute here) getDeclaredAttribute(name); // We return an attribute that has passed through both a get, (optionally a type check) and a declared inheritance check // all of which would throw an IAException before the return below. return anAttribute; } /** * Return all collection-valued attributes declared by the * managed type. * @return declared collection valued attributes */ public Set<PluralAttribute<X, ?, ?>> getDeclaredCollections() { // It is evident from the fact that we have only getAttributes(), getCollections() and getSingularAttributes() that a Collection is a superset of all Set, List and even Map // return only a set of collections declared on this class - not via inheritance // Get all collection attribute and filter only on declared ones Set<PluralAttribute<? super X, ?, ?>> pluralAttributes = this.getCollections(); // Is it better to add to a new Set or remove from an existing Set without a concurrentModificationException Set<PluralAttribute<X, ?, ?>> declaredAttributes = new HashSet<PluralAttribute<X, ?, ?>>(); // The set is a copy of the underlying metamodel attribute set - we will remove all SingularAttribute(s) for(Iterator<PluralAttribute<? super X, ?, ?>> anIterator = pluralAttributes.iterator(); anIterator.hasNext();) { PluralAttribute<? super X, ?, ?> anAttribute = anIterator.next(); if(((TypeImpl)anAttribute.getElementType()).isManagedType()) { // check for declarations in the hierarchy and don't add if declared above //if(!((ManagedTypeImpl)anAttribute.getElementType()).hasDeclaredAttribute(anAttribute.getName())) { // add attributes that don't have superclasses automatically ManagedTypeImpl potentialSuperType = getManagedSuperType(); if(null == potentialSuperType) { declaredAttributes.add((PluralAttribute<X, ?, ?>)anAttribute); } else { // add only if we reach the root without finding another declaration if(!potentialSuperType.hasDeclaredAttribute(anAttribute.getName())) { declaredAttributes.add((PluralAttribute<X, ?, ?>)anAttribute); } } } } return declaredAttributes; } /** * INTERNAL: * Return an instance of a ManagedType based on the RelationalDescriptor parameter * @param metamodel * @param descriptor * @return */ public static ManagedTypeImpl<?> create(MetamodelImpl metamodel, RelationalDescriptor descriptor) { // Get the ManagedType property on the descriptor if it exists ManagedTypeImpl<?> managedType = (ManagedTypeImpl<?>) descriptor.getProperty(ManagedTypeImpl.class.getName()); // Create an Entity, Embeddable or MappedSuperclass if (null == managedType) { // The descriptor can be one of NORMAL, INTERFACE (not supported), AGGREGATE or AGGREGATE_COLLECTION // TODO: handle MappedSuperclass if (descriptor.isAggregateDescriptor()) { managedType = new EmbeddableTypeImpl(metamodel, descriptor); //} else if (descriptor.isAggregateCollectionDescriptor()) { // managedType = new EntityTypeImpl(metamodel, descriptor); } else { managedType = new EntityTypeImpl(metamodel, descriptor); } } return managedType; } public <E> ListAttribute<X, E> getDeclaredList(String name, Class<E> elementType) { // get the attribute parameterized by <Owning type, return Type> - throw an IAE if not found (no need to check hierarchy) // Handles UC1 and UC2 ListAttribute<X, E> anAttribute = (ListAttribute<X, E>) getList(name, elementType); // The following verification step will throw an appropriate IAException if required (type checking has been done, and we can discard the return attribute here) getDeclaredAttribute(name); // We return an attribute that has passed through both a get, (optionally a type check) and a declared inheritance check // all of which would throw an IAException before the return below. return anAttribute; } public ListAttribute<X, ?> getDeclaredList(String name) { // return only a List declared on this class - not via inheritance // Handles UC1 and UC2 ListAttribute<X, ?> anAttribute = (ListAttribute<X, ?>) getList(name); // The following verification step will throw an appropriate IAException if required (we can discard the return attribute here) getDeclaredAttribute(name); // We return an attribute that has passed through both a get and a declared inheritance check // all of which would throw an IAException before the return below. return anAttribute; } public MapAttribute<X, ?, ?> getDeclaredMap(String name) { // return only a map declared on this class - not via inheritance // Handles UC1 and UC2 MapAttribute<X, ?, ?> anAttribute = (MapAttribute<X, ?, ?>) getMap(name); // The following verification step will throw an appropriate IAException if required (we can discard the return attribute here) getDeclaredAttribute(name); // We return an attribute that has passed through both a get and a declared inheritance check // all of which would throw an IAException before the return below. return anAttribute; } public <K, V> MapAttribute<X, K, V> getDeclaredMap(String name, Class<K> keyType, Class<V> valueType) { // return only a map declared on this class - not via inheritance // Handles UC1 and UC2 MapAttribute<X, K, V> anAttribute = (MapAttribute<X, K, V>) getMap(name, keyType, valueType); // The following verification step will throw an appropriate IAException if required (type checking has been done, and we can discard the return attribute here) getDeclaredAttribute(name); // We return an attribute that has passed through both a get, (optionally a type check) and a declared inheritance check // all of which would throw an IAException before the return below. return anAttribute; } public SetAttribute<X, ?> getDeclaredSet(String name) { // return only a set declared on this class - not via inheritance // Handles UC1 and UC2 SetAttribute<X, ?> anAttribute = (SetAttribute<X, ?>) getSet(name); // The following verification step will throw an appropriate IAException if required (we can discard the return attribute here) getDeclaredAttribute(name); // We return an attribute that has passed through both a get and a declared inheritance check // all of which would throw an IAException before the return below. return anAttribute; } public <E> SetAttribute<X, E> getDeclaredSet(String name, Class<E> elementType) { // return only a set declared on this class - not via inheritance // Handles UC1 and UC2 SetAttribute<X, E> anAttribute = (SetAttribute<X, E>) getSet(name, elementType); // The following verification step will throw an appropriate IAException if required (type checking has been done, and we can discard the return attribute here) getDeclaredAttribute(name); // We return an attribute that has passed through both a get, (optionally a type check) and a declared inheritance check // all of which would throw an IAException before the return below. return anAttribute; } public SingularAttribute<X, ?> getDeclaredSingularAttribute(String name) { // return only a SingularAttribute declared on this class - not via inheritance // Handles UC1 and UC2 SingularAttribute<X, ?> anAttribute = (SingularAttribute<X, ?>) getSingularAttribute(name); // The following verification step will throw an appropriate IAException if required (we can discard the return attribute here) getDeclaredAttribute(name); // We return an attribute that has passed through both a get and a declared inheritance check // all of which would throw an IAException before the return below. return anAttribute; } public <Y> SingularAttribute<X, Y> getDeclaredSingularAttribute(String name, Class<Y> type) { // return only a SingularAttribute declared on this class - not via inheritance // Handles UC1 and UC2 SingularAttribute<X, Y> anAttribute = (SingularAttribute<X, Y>) getSingularAttribute(name, type); // The following verification step will throw an appropriate IAException if required (type checking has been done, and we can discard the return attribute here) getDeclaredAttribute(name); // We return an attribute that has passed through both a get, (optionally a type check) and a declared inheritance check // all of which would throw an IAException before the return below. return anAttribute; } /** * Return the single-valued attributes declared by the managed * type. * @return declared single-valued attributes */ public Set<SingularAttribute<X, ?>> getDeclaredSingularAttributes() { // return the set of SingularAttributes declared on this class - not via inheritance // Get all attributes and filter only for declared attributes Set<Attribute<X, ?>> allAttributes = new HashSet<Attribute<X, ?>>(this.members.values());; // Is it better to add to a new Set or remove from an existing Set without a concurrentModificationException Set<SingularAttribute<X, ?>> declaredAttributes = new HashSet<SingularAttribute<X, ?>>(); for(Iterator<Attribute<X, ?>> anIterator = allAttributes.iterator(); anIterator.hasNext();) { Attribute<? super X, ?> anAttribute = anIterator.next(); if(!anAttribute.isCollection()) { declaredAttributes.add((SingularAttribute<X, ?>)anAttribute); } } return declaredAttributes; } /** * INTERNAL: * Return the RelationalDescriptor associated with this ManagedType * @return */ public RelationalDescriptor getDescriptor() { return this.descriptor; } public ListAttribute<? super X, ?> getList(String name) { return getList(name, true); } /** * INTERNAL: * @param name * @param performNullCheck - flag on whether we should be doing an IAException check * @return */ protected ListAttribute<? super X, ?> getList(String name, boolean performNullCheck) { /* * Note: We do not perform type checking on the get(name) * If the type is not of the correct Attribute implementation class then * a possible CCE will be allowed to propagate to the client. */ ListAttribute<? super X, ?> anAttribute = (ListAttribute<? super X, ?>)this.members.get(name); if(performNullCheck && null == anAttribute) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_not_present", new Object[] { name, this })); } return anAttribute; } private void verifyAttributeTypeAndReturnType(Attribute anAttribute, Class attributeElementType, CollectionType aReturnCollectionType) { // Check for plural or singular attribute if(anAttribute.isCollection()) { // check for CollectionAttribute if(((PluralAttribute)anAttribute).getCollectionType().equals(aReturnCollectionType)) { // check that the java class is correct (use BindableJavaType not elementType.getJavaType() Class aBindableJavaClass = ((PluralAttribute)anAttribute).getBindableJavaType(); if(attributeElementType != aBindableJavaClass) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_type_incorrect", new Object[] { anAttribute.getName(), this, attributeElementType, aBindableJavaClass })); } } else { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_return_type_incorrect", new Object[] { anAttribute.getName(), this, aReturnCollectionType, ((PluralAttribute)anAttribute).getCollectionType()})); } } } public <E> ListAttribute<? super X, E> getList(String name, Class<E> elementType) { // We do not use getList(name) so that we can catch a possible CCE on the wrong attribute type ListAttribute<? super X, E> anAttribute = (ListAttribute<? super X, E>)this.members.get(name); if(null == anAttribute) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_not_present", new Object[] { name, this })); } else { // Throw appropriate IAException if required verifyAttributeTypeAndReturnType(anAttribute, elementType, CollectionType.LIST); } return (ListAttribute<? super X, E>)anAttribute; } /** * INTERNAL: * Return the ManagedType that represents the superType (superclass) of * the current ManagedType. * * @return ManagedType supertype or null if no superclass */ private ManagedTypeImpl getManagedSuperType() { // Note this method provides the same functionality of the more specific IdentifiableType.superType but is general to ManagedTypeImpl ManagedTypeImpl<?> aSuperType = null; // Get the superType if it exists (without using IdentifiableType.superType) Class aSuperClass = this.getJavaType().getSuperclass(); // The superclass for top-level types will be Object - which we will leave as a null supertype on the type if(null != aSuperClass && aSuperClass != ClassConstants.OBJECT) { // Get the managedType from the metamodel aSuperType = (ManagedTypeImpl<?>)this.getMetamodel().type(aSuperClass); } return aSuperType; } public MapAttribute<? super X, ?, ?> getMap(String name) { /* * Note: We do not perform type checking on the get(name) * If the type is not of the correct Attribute implementation class then * a possible CCE will be allowed to propagate to the client. */ MapAttribute<? super X, ?, ?> anAttribute = (MapAttribute<? super X, ?, ?>)this.members.get(name); if(null == anAttribute) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_not_present", new Object[] { name, this })); } return anAttribute; } public <K, V> MapAttribute<? super X, K, V> getMap(String name, Class<K> keyType, Class<V> valueType) { MapAttribute<? super X, K, V> anAttribute = (MapAttribute<? super X, K, V>)this.getMap(name); Class<V> aClass = anAttribute.getElementType().getJavaType(); if(valueType != aClass) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_type_incorrect", new Object[] { name, this, valueType, aClass })); } return anAttribute; } /** * INTERNAL: * Return the Map of AttributeImpl members keyed by String. * @return */ public java.util.Map<String, Attribute<X, ?>> getMembers() { return this.members; } /** * INTERNAL: * Return the Metamodel that this ManagedType is associated with. * @return */ public MetamodelImpl getMetamodel() { return this.metamodel; } public SetAttribute<? super X, ?> getSet(String name) { /* * Note: We do not perform type checking on the get(name) * If the type is not of the correct Attribute implementation class then * a possible CCE will be allowed to propagate to the client. */ SetAttribute<? super X, ?> anAttribute = (SetAttribute<? super X, ?>)this.members.get(name); if(null == anAttribute) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_not_present", new Object[] { name, this })); } return anAttribute; } public <E> SetAttribute<? super X, E> getSet(String name, Class<E> elementType) { SetAttribute<? super X, E> anAttribute = (SetAttribute<? super X, E>)getSet(name); Class<E> aClass = anAttribute.getElementType().getJavaType(); if(elementType != aClass) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_type_incorrect", new Object[] { name, this, elementType, aClass.getName() })); } return anAttribute; } public SingularAttribute<? super X, ?> getSingularAttribute(String name) { Attribute<X, ?> anAttribute = getMembers().get(name); if(null == anAttribute) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_not_present", new Object[] { name, this })); } return (SingularAttribute<? super X, ?>)anAttribute; } public <Y> SingularAttribute<? super X, Y> getSingularAttribute(String name, Class<Y> type) { SingularAttribute<? super X, Y> anAttribute = (SingularAttribute<? super X, Y>)getSingularAttribute(name); Class<Y> aClass = anAttribute.getType().getJavaType(); if(type != aClass) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage( "metamodel_managed_type_attribute_type_incorrect", new Object[] { name, this, type, aClass })); } return anAttribute; } /** * Return the single-valued attributes of the managed type. * @return single-valued attributes */ public Set<SingularAttribute<? super X, ?>> getSingularAttributes() { // Iterate the members set for attributes of type SingularAttribute //Set<SingularAttribute<? super X, ?>> singularAttributeSet = new HashSet<SingularAttribute<? super X, ?>>(); Set singularAttributeSet = new HashSet<SingularAttribute<? super X, ?>>(); for(Iterator<Attribute<X, ?>> anIterator = this.members.values().iterator(); anIterator.hasNext();) { AttributeImpl<? super X, ?> anAttribute = (AttributeImpl<? super X, ?>)anIterator.next(); if(!anAttribute.isPlural()) { singularAttributeSet.add(anAttribute); } } return singularAttributeSet; } /** * INTERNAL: * Recursively search the superclass tree of the current managedType * for the named attribute.<p> * This internal function is used exclusively by the getDeclared*() calls on ManagedType objects.<p> * This function is type agnostic (Set, List, Map and Collection are treated as attributes) * @param attributeName - String name of possible declared attribute search * @return true if the attribute is declared at this first level, * false if no attribute is found in the superTree, or * false if the attribute is found declared higher up in the inheritance superTree */ private boolean hasDeclaredAttribute(String attributeName) { return hasDeclaredAttribute(attributeName, this.getMembers().get(attributeName)); } /** * INTERNAL: * Recursively search the superclass tree of the current managedType * for the named attribute.<p> * This internal function is used exclusively by the getDeclared*() calls on ManagedType objects.<p> * This function is type agnostic (Set, List, Map and Collection are treated as attributes) * @param attributeName - String name of possible declared attribute search * @return true if the attribute is declared at this first level, * false if no attribute is found in the superTree, or * false if the attribute is found declared higher up in the inheritance superTree */ private boolean hasDeclaredAttribute(String attributeName, Attribute firstLevelAttribute) { /* * Issues: We need to take into account whether the superType is an Entity or MappedSuperclass * - If superType is entity then inheriting entities will not have copies of the inherited mappings * - however, if superType is mappedSuperclass then all inheriting mappedSuperclasses and the first * entity will have copies of the inherited mappings * - Note: a sub-entity can override a mapping above it * Use Cases: * UC1 Superclass declares attribute * UC1.1: Entity (searched) --> Entity --> Entity (declares attribute) * UC1.2: Entity (searched) --> Entity (copy of attribute) --> MappedSuperclass (declares attribute) * UC1.3: Entity (searched) --> MappedSuperclass --> Entity (declares attribute) * UC1.4: Entity (copy of attribute) (searched) --> MappedSuperclass (no copy of attribute) (searched) --> MappedSuperclass (declares attribute) (searched) * UC1.5: Entity (copy of attribute) (searched) --> MappedSuperclass (declares attribute) (searched) --> MappedSuperclass * UC2 Nobody declares attribute * UC2.1: Entity (searched) --> Entity --> MappedSuperclass (declares attribute) * UC2.2: Entity (searched) --> Entity --> Entity (declares attribute) * UC2.3: Entity (searched) --> MappedSuperclass (searched) --> MappedSuperclass (declares attribute) * UC2.4: Entity (searched) --> MappedSuperclass (searched) --> Entity (declares attribute) * UC3 Superclass declares attribute but child overrides it * UC3.1: Entity (searched) --> Entity --> MappedSuperclass (declares attribute) * UC3.2: Entity (searched) --> Entity --> Entity (declares attribute) * UC3.3: Entity (searched) --> MappedSuperclass (override attribute) (searched) --> MappedSuperclass (declares attribute) * UC3.4: Entity (searched) --> MappedSuperclass (override attribute) (searched) --> Entity (declares attribute) (searched) * UC3.5: Entity (override attribute) (searched) --> MappedSuperclass (searched) --> MappedSuperclass (declares attribute) (searched) * UC3.6: Entity (override attribute) (searched) --> MappedSuperclass (searched) --> Entity (declares attribute) * Solution: * Results Expected for hasDeclaredAttribute() * True = attribute declared only on current type * False = attribute not found in superType tree or attribute found in more than one(1) level of the superType tree * Base Case * attribute found && no superType exists = true * attribute not found && no superType exists = false * Recursive Case * Exit(false) as soon as attribute is found in a superType - without continuing to the root * continue as long as we find an attribute in the superType (essentially only MappedSuperclass parents) **/ Attribute anAttribute = this.getMembers().get(attributeName); ManagedTypeImpl<?> aSuperType = getManagedSuperType(); // Base Case: If we are at the root, check for the attribute and return results immediately if(null == aSuperType) { if(null == anAttribute && null != firstLevelAttribute) { return true; } else { // UC 1.3 (part of the else condition (anAttribute != null)) is handled by the return false in null != aSuperTypeAttribute return false; } } else { // Recursive Case: check hierarchy only if the immediate superclass is a MappedSuperclassType if(aSuperType.isMappedSuperclass()) { Attribute aSuperTypeAttribute = aSuperType.getMembers().get(attributeName); // UC1.3 The immediate mappedSuperclass may have the attribute - we check it in the base case of the next recursive call if(null != aSuperTypeAttribute) { // return false immediately if a superType exists above the first level return false; } else { // UC1.4 The immediate mappedSuperclass may not have the attribute if another one up the chain of rmappedSuperclasses declares it if(null == aSuperTypeAttribute) { // UC 1.5: keep searching a possible chain of mappedSuperclasses return aSuperType.hasDeclaredAttribute(attributeName, firstLevelAttribute); } else { // superType does not contain the attribute - check that the current attribute and the first differ if(anAttribute != firstLevelAttribute) { return false; } else { return true; } } } } else { // superType (Entity) may declare the attribute higher up - we do not need to check this // TODO: verify handling of XML mapped non-Entity (plain Java Class) inherited mappings // http://wiki.eclipse.org/EclipseLink/Development/JPA_2.0/metamodel_api#DI_53:_20090729:_Verify_that_inheritied_non-JPA_class_mappings_are_handled_by_the_Metamodel if(null == anAttribute) { return false; } else { return true; } } } } /** * INTERNAL: * Handle the case where we were unable to determine the element type of the plural attribute. * Normally this function is never required and should have a code coverage of 0%. * @param managedType * @param colMapping * @param validation */ private AttributeImpl initializePluralAttributeTypeNotFound(ManagedTypeImpl managedType, CollectionMapping collectionMapping, boolean validation) { // default to List // TODO: System.out.println("_Warning: type is null on " + colMapping); AttributeImpl<X, ?> member = new ListAttributeImpl(managedType, collectionMapping, validation); return member; } /** * INTERNAL: * Initialize the members of this ManagedType based on the mappings defined on the descriptor. * We process the appropriate Map, List, Set, Collection or Object/primitive types.<p> * Initialization should occur after all types in the metamodel have been created already. * */ protected void initialize() { // TODO: Check all is*Policy() calls this.members = new HashMap<String, Attribute<X, ?>>(); // Get and process all mappings on the relationalDescriptor for (Iterator<DatabaseMapping> i = getDescriptor().getMappings().iterator(); i.hasNext();) { DatabaseMapping mapping = (DatabaseMapping) i.next(); AttributeImpl<X, ?> member = null; /** * The following section will determine the plural attribute type for each mapping on the managedType. * Special handling is required for differentiation of List and Collection * beyond their shared IndirectList ContainerPolicy, * as even though a List is an implementation of Collection in Java, * In the Metamodel we treat the Collection as a peer of a List. * * Collection.class --> via IndirectList --> CollectionAttributeImpl * List.class --> via IndirectList --> ListAttributeImpl * Set.class --> SetAttributeImpl * Map.class --> MapAttributeImpl * * If the type is Embeddable then special handling will be required to get the plural type. * The embeddable's MethodAttributeAccessor will not have the getMethod set. * We can however use reflection and get the returnType directly from the class * using the getMethodName on the accessor. */ // Tie into the collection hierarchy at a lower level if (mapping.isCollectionMapping()) { // Handle 1:m, n:m collection mappings CollectionMapping colMapping = (CollectionMapping) mapping; ContainerPolicy collectionContainerPolicy = colMapping.getContainerPolicy(); if (collectionContainerPolicy.isMapPolicy()) { // Handle Map type mappings member = new MapAttributeImpl(this, colMapping, true); // check mapping.attributeAcessor.attributeField.type=Collection } else if (collectionContainerPolicy.isListPolicy()) { /** * Handle lazy Collections and Lists and the fact that both return an IndirectList policy. * We check the type on the attributeField of the attributeAccessor on the mapping */ Class aType = null; if(colMapping.getAttributeAccessor() instanceof InstanceVariableAttributeAccessor) { Field aField = ((InstanceVariableAttributeAccessor)colMapping.getAttributeAccessor()).getAttributeField(); // MappedSuperclasses need special handling to get their type from an inheriting subclass if(null == aField) { // MappedSuperclass field will not be set if(this.isMappedSuperclass()) { // get inheriting subtype member (without handling @override annotations) MappedSuperclassTypeImpl aMappedSuperclass = ((MappedSuperclassTypeImpl)this); AttributeImpl inheritingTypeMember = aMappedSuperclass.getMemberFromInheritingType(colMapping.getAttributeName()); aField = ((InstanceVariableAttributeAccessor)inheritingTypeMember.getMapping().getAttributeAccessor()).getAttributeField(); } } if(null != aField) { aType = aField.getType(); } // This attribute is declared as List if(aType == List.class) { member = new ListAttributeImpl(this, colMapping, true); } else { if(aType == Collection.class) { // This attribute is therefore declared as Collection member = new CollectionAttributeImpl(this, colMapping, true); } else { member = initializePluralAttributeTypeNotFound(this, colMapping, true); } } } else { // handle variations of missing get/set methods - only for Collection vs List if(colMapping.getAttributeAccessor() instanceof MethodAttributeAccessor) { /** * The following call will perform a getMethod call for us. * If no getMethod exists, we will secondarily check the getMethodName below. */ aType = ((MethodAttributeAccessor)colMapping.getAttributeAccessor()).getAttributeClass(); if(aType == Collection.class) { member = new CollectionAttributeImpl(this, colMapping, true); } else if(aType == List.class) { member = new ListAttributeImpl(this, colMapping, true); } else { /** * In this block we have the following scenario: * 1) The access type is "field" * 2) The get method is not set on the entity * 3) The get method is named differently than the attribute */ // Type may be null when no getMethod exists for the class for a ManyToMany mapping // Here we check the returnType on the declared method on the class directly String getMethodName = ((MethodAttributeAccessor)colMapping.getAttributeAccessor()).getGetMethodName(); if(null == getMethodName) { // Check declaredFields in the case where we have no getMethod or getMethodName try { Field field = null; if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){ try { field = (Field)AccessController.doPrivileged(new PrivilegedGetDeclaredField( this.getJavaType(), colMapping.getAttributeName(), false)); } catch (PrivilegedActionException exception) { member = initializePluralAttributeTypeNotFound(this, colMapping, true); } } else { field = PrivilegedAccessHelper.getDeclaredField( this.getJavaType(), colMapping.getAttributeName(), false); } if(null == field) { member = initializePluralAttributeTypeNotFound(this, colMapping, true); } else { aType = field.getType(); if(aType == Collection.class) { member = new CollectionAttributeImpl(this, colMapping, true); } else if(aType == List.class) { member = new ListAttributeImpl(this, colMapping, true); } else { member = initializePluralAttributeTypeNotFound(this, colMapping, true); } } } catch (Exception e) { member = initializePluralAttributeTypeNotFound(this, colMapping, true); } } else { /** * Field access Handling: * If a get method name exists, we check the return type on the method directly * using reflection. * In all failure cases we default to the List type. */ try { Method aMethod = null; if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) { aMethod = (Method) AccessController.doPrivileged(new PrivilegedGetDeclaredMethod( this.getJavaType(), getMethodName, null)); } else { aMethod = PrivilegedAccessHelper.getDeclaredMethod( this.getJavaType(), getMethodName, null); } if(null == aMethod) { member = initializePluralAttributeTypeNotFound(this, colMapping, true); } else { aType = aMethod.getReturnType(); if(aType == Collection.class) { member = new CollectionAttributeImpl(this, colMapping, true); } else if(aType == List.class) { member = new ListAttributeImpl(this, colMapping, true); } else { member = initializePluralAttributeTypeNotFound(this, colMapping, true); } } } catch (Exception e) { member = initializePluralAttributeTypeNotFound(this, colMapping, true); } } } } } } else { // Handle Set type mappings (IndirectSet.isAssignableFrom(Set.class) == false) if (collectionContainerPolicy.getContainerClass().isAssignableFrom(Set.class) || collectionContainerPolicy.getContainerClass().isAssignableFrom(IndirectSet.class)) { member = new SetAttributeImpl(this, colMapping, true); } else { // Check for non-lazy Collection policy if(collectionContainerPolicy.isCollectionPolicy()) { member = new CollectionAttributeImpl(this, colMapping, true); } else { // Handle Collection type mappings as a default // TODO: System.out.println("_Warning: defaulting to non-Set specific Collection type on " + colMapping); member = new CollectionAttributeImpl(this, colMapping, true); } } } } else { // Handle 1:1 single object and direct mappings member = new SingularAttributeImpl(this, mapping, true); } this.members.put(mapping.getAttributeName(), member); } } /** * INTERNAL: * Return whether this type is identifiable. * This would be EntityType and MappedSuperclassType * @return */ @Override public boolean isIdentifiableType() { return false; } /** * INTERNAL: * Return whether this type is identifiable. * This would be EmbeddableType as well as EntityType and MappedSuperclassType * @return */ @Override public boolean isManagedType() { return true; } /** * INTERNAL: * Append the partial string representation of the receiver to the StringBuffer. */ @Override protected void toStringHelper(StringBuffer aBuffer) { aBuffer.append(" descriptor: "); aBuffer.append(this.getDescriptor()); if(null != this.getDescriptor()) { aBuffer.append(", mappings: "); aBuffer.append(this.getDescriptor().getMappings()); } } }
package com.konkerlabs.platform.registry.api.config.oauth; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; @Configuration @EnableResourceServer public class ResourceServer extends ResourceServerConfigurerAdapter { public static final String RESOURCE_ID = "registryapi"; private static final String[] PUBLIC_RESOURCES = new String[]{ "/oauth/token", "/configuration/ui", "/swagger-ui.html", "/swagger-resources", "/api/docs", "/v2/api-docs", }; @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers(PUBLIC_RESOURCES).permitAll() .antMatchers("/").access("#oauth2.hasScope('read')") .anyRequest().authenticated(); } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(RESOURCE_ID); } }
package org.languagetool.openoffice; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.Image; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JProgressBar; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextPane; import javax.swing.ListSelectionModel; import javax.swing.ToolTipManager; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.MutableAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.Languages; import org.languagetool.JLanguageTool.ParagraphHandling; import org.languagetool.gui.Tools; import org.languagetool.openoffice.DocumentCache.TextParagraph; import org.languagetool.openoffice.OfficeTools.DocumentType; import org.languagetool.openoffice.OfficeTools.RemoteCheck; import org.languagetool.rules.RuleMatch; import com.sun.star.beans.PropertyState; import com.sun.star.beans.PropertyValue; import com.sun.star.lang.Locale; import com.sun.star.lang.XComponent; import com.sun.star.linguistic2.ProofreadingResult; import com.sun.star.linguistic2.SingleProofreadingError; import com.sun.star.text.TextMarkupType; import com.sun.star.text.XFlatParagraph; import com.sun.star.text.XMarkingAccess; import com.sun.star.text.XParagraphCursor; import com.sun.star.text.XTextCursor; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; /** * Class defines the spell and grammar check dialog * @since 5.1 * @author Fred Kruse */ public class SpellAndGrammarCheckDialog extends Thread { private static boolean debugMode = OfficeTools.DEBUG_MODE_CD; // should be false except for testing private static final ResourceBundle messages = JLanguageTool.getMessageBundle(); private static final String spellingError = messages.getString("desc_spelling"); private static final String spellRuleId = "LO_SPELLING_ERROR"; private final static String dialogName = messages.getString("guiOOoCheckDialogName"); private final static String labelLanguage = messages.getString("textLanguage"); private final static String labelSuggestions = messages.getString("guiOOosuggestions"); private final static String moreButtonName = messages.getString("guiMore"); private final static String ignoreButtonName = messages.getString("guiOOoIgnoreButton"); private final static String ignoreAllButtonName = messages.getString("guiOOoIgnoreAllButton"); private final static String deactivateRuleButtonName = messages.getString("loContextMenuDeactivateRule"); private final static String addToDictionaryName = messages.getString("guiOOoaddToDictionary"); private final static String changeButtonName = messages.getString("guiOOoChangeButton"); private final static String changeAllButtonName = messages.getString("guiOOoChangeAllButton"); private final static String helpButtonName = messages.getString("guiMenuHelp"); private final static String optionsButtonName = messages.getString("guiOOoOptionsButton"); private final static String undoButtonName = messages.getString("guiUndo"); private final static String closeButtonName = messages.getString("guiCloseButton"); private final static String changeLanguageList[] = { messages.getString("guiOOoChangeLanguageRequest"), messages.getString("guiOOoChangeLanguageMatch"), messages.getString("guiOOoChangeLanguageParagraph") }; private final static String languageHelp = messages.getString("loDialogLanguageHelp"); private final static String changeLanguageHelp = messages.getString("loDialogChangeLanguageHelp"); private final static String matchDescriptionHelp = messages.getString("loDialogMatchDescriptionHelp"); private final static String matchParagraphHelp = messages.getString("loDialogMatchParagraphHelp"); private final static String suggestionsHelp = messages.getString("loDialogSuggestionsHelp"); private final static String checkTypeHelp = messages.getString("loDialogCheckTypeHelp"); private final static String helpButtonHelp = messages.getString("loDialogHelpButtonHelp"); private final static String optionsButtonHelp = messages.getString("loDialogOptionsButtonHelp"); private final static String undoButtonHelp = messages.getString("loDialogUndoButtonHelp"); private final static String closeButtonHelp = messages.getString("loDialogCloseButtonHelp"); private final static String moreButtonHelp = messages.getString("loDialogMoreButtonHelp"); private final static String ignoreButtonHelp = messages.getString("loDialogIgnoreButtonHelp"); private final static String ignoreAllButtonHelp = messages.getString("loDialogIgnoreAllButtonHelp"); private final static String deactivateRuleButtonHelp = messages.getString("loDialogDeactivateRuleButtonHelp"); private final static String activateRuleButtonHelp = messages.getString("loDialogActivateRuleButtonHelp"); private final static String addToDictionaryHelp = messages.getString("loDialogAddToDictionaryButtonHelp"); private final static String changeButtonHelp = messages.getString("loDialogChangeButtonHelp"); private final static String changeAllButtonHelp = messages.getString("loDialogChangeAllButtonHelp"); private final static String checkStatusInitialization = messages.getString("loCheckStatusInitialization"); private final static String checkStatusCheck = messages.getString("loCheckStatusCheck"); private final static String checkStatusResult = messages.getString("loCheckStatusResult"); private static int nLastFlat = 0; private final XComponentContext xContext; private final MultiDocumentsHandler documents; private final ExtensionSpellChecker spellChecker; private SwJLanguageTool lt; private Language lastLanguage; private Locale locale; private int checkType = 0; private DocumentCache docCache; private DocumentType docType = DocumentType.WRITER; private boolean doInit = true; private int dialogX = -1; private int dialogY = -1; SpellAndGrammarCheckDialog(XComponentContext xContext, MultiDocumentsHandler documents, Language language) { debugMode = OfficeTools.DEBUG_MODE_CD; this.xContext = xContext; this.documents = documents; spellChecker = new ExtensionSpellChecker(); lastLanguage = language; locale = LinguisticServices.getLocale(language); setLangTool(documents, language); if(!documents.javaVersionOkay()) { return; } } /** * Initialize LanguageTool to run in LT check dialog and next error function */ private void setLangTool(MultiDocumentsHandler documents, Language language) { lt = documents.initLanguageTool(language, false); documents.initCheck(lt); if (debugMode) { for (String id : lt.getDisabledRules()) { MessageHandler.printToLogFile("CheckDialog: setLangTool: After init disabled rule: " + id); } } doInit = false; } /** * opens the LT check dialog for spell and grammar check */ @Override public void run() { try { LtCheckDialog checkDialog = new LtCheckDialog(xContext); documents.setLtDialog(checkDialog); checkDialog.show(); } catch (Throwable e) { MessageHandler.showError(e); } } /** * Actualize impress/calc document cache */ private void actualizeNonWriterDocumentCache(SingleDocument document) { if (docType != DocumentType.WRITER) { DocumentCache oldCache = new DocumentCache(docCache); docCache.refresh(null, null, null, document.getXComponent(), 7); if (!oldCache.isEmpty()) { boolean isSame = true; if (oldCache.size() != docCache.size()) { isSame = false; } else { for (int i = 0; i < docCache.size(); i++) { if (!docCache.getFlatParagraph(i).equals(oldCache.getFlatParagraph(i))) { isSame = false; break; } } } if (!isSame) { document.resetCache(); } } } } /** * Actualize impress document cache */ private void actualizeWriterDocumentCache(SingleDocument document) { if (docType == DocumentType.WRITER) { XComponent xComponent = document.getXComponent(); DocumentCursorTools docCursor = new DocumentCursorTools(xComponent); DocumentCache oldCache = new DocumentCache(docCache); docCache.refresh(docCursor, document.getFlatParagraphTools(), locale, xComponent, 8); if (!oldCache.isEmpty() && !docCache.isEmpty()) { if (oldCache.size() != docCache.size()) { int from = 0; int to = 1; // to prevent spontaneous recheck of nearly the whole text // the change of text contents has to be checked first // ignore headers and footers and the change of function inside of them while (from < docCache.size() && from < oldCache.size() && (docCache.getNumberOfTextParagraph(from).type == DocumentCache.CURSOR_TYPE_HEADER_FOOTER || docCache.getFlatParagraph(from).equals(oldCache.getFlatParagraph(from)))) { from++; } boolean isTextChange = from < docCache.size() && from < oldCache.size(); if (isTextChange) { // if change in text is found check the number of text paragraphs which have changed while (to <= docCache.size() && to <= oldCache.size() && (docCache.getNumberOfTextParagraph(docCache.size() - to).type == DocumentCache.CURSOR_TYPE_HEADER_FOOTER || docCache.getFlatParagraph(docCache.size() - to).equals( oldCache.getFlatParagraph(oldCache.size() - to)))) { to++; } to = docCache.size() - to; if (to < 0) { to = 0; } } else { // if no change in text is found check the number of flat paragraphs which have changed from = 0; while (from < docCache.size() && from < oldCache.size() && (docCache.getNumberOfTextParagraph(from).type != DocumentCache.CURSOR_TYPE_HEADER_FOOTER || docCache.getFlatParagraph(from).equals(oldCache.getFlatParagraph(from)))) { from++; } while (to <= docCache.size() && to <= oldCache.size() && (docCache.getNumberOfTextParagraph(docCache.size() - to).type != DocumentCache.CURSOR_TYPE_HEADER_FOOTER || docCache.getFlatParagraph(docCache.size() - to).equals( oldCache.getFlatParagraph(oldCache.size() - to)))) { to++; } to = docCache.size() - to; } if (debugMode) { MessageHandler.printToLogFile("CheckDialog: actualizeWriterDocumentCache: Changed paragraphs: from:" + from + ", to: " + to); } for (ResultCache cache : document.getParagraphsCache()) { cache.removeAndShift(from, to, docCache.size() - oldCache.size()); } } else { for (int i = 0; i < docCache.size(); i++) { if (!docCache.getFlatParagraph(i).equals(oldCache.getFlatParagraph(i))) { for (ResultCache cache : document.getParagraphsCache()) { cache.remove(i); } } } } } } } /** * Get the current document * Wait until it is initialized (by LO/OO) */ private SingleDocument getCurrentDocument(boolean actualize) { SingleDocument currentDocument = documents.getCurrentDocument(); int nWait = 0; while (currentDocument == null) { if (documents.isNotTextDocument()) { return null; } if (nWait > 400) { return null; } MessageHandler.printToLogFile("CheckDialog: getCurrentDocument: Wait: " + ((nWait + 1) * 20)); nWait++; try { Thread.sleep(20); } catch (InterruptedException e) { MessageHandler.printException(e); } currentDocument = documents.getCurrentDocument(); } if (currentDocument != null) { docType = currentDocument.getDocumentType(); docCache = currentDocument.getDocumentCache(); if (docType != DocumentType.WRITER) { actualizeNonWriterDocumentCache(currentDocument); } else if (docCache.size() == 0) { XComponent xComponent = currentDocument.getXComponent(); DocumentCursorTools docCursor = new DocumentCursorTools(xComponent); docCache.refresh(docCursor, currentDocument.getFlatParagraphTools(), locale, xComponent, 8); } else if (actualize) { actualizeWriterDocumentCache(currentDocument); } } return currentDocument; } /** * Find the next error relative to the position of cursor and set the view cursor to the position */ public void nextError() { try { SingleDocument document = getCurrentDocument(false); if (document == null || docType != DocumentType.WRITER || !documents.isEnoughHeapSpace()) { return; } XComponent xComponent = document.getXComponent(); DocumentCursorTools docCursor = new DocumentCursorTools(xComponent); if (docCache == null || docCache.size() <= 0) { return; } ViewCursorTools viewCursor = new ViewCursorTools(xComponent); int yFlat = getCurrentFlatParagraphNumber(viewCursor, docCache); if (yFlat < 0) { MessageHandler.showClosingInformationDialog(messages.getString("loNextErrorUnsupported")); return; } int x = viewCursor.getViewCursorCharacter(); while (yFlat < docCache.size()) { CheckError nextError = getNextErrorInParagraph (x, yFlat, document, docCursor); if (nextError != null && setFlatViewCursor(nextError.error.nErrorStart + 1, yFlat, viewCursor, docCache)) { return; } x = 0; yFlat++; } MessageHandler.showClosingInformationDialog(messages.getString("guiCheckComplete")); } catch (Throwable t) { MessageHandler.showError(t); } } /** * get the current number of the flat paragraph related to the position of view cursor * the function considers footnotes, headlines, tables, etc. included in the document */ private int getCurrentFlatParagraphNumber(ViewCursorTools viewCursor, DocumentCache docCache) { TextParagraph textPara = viewCursor.getViewCursorParagraph(); if (textPara.type == DocumentCache.CURSOR_TYPE_UNKNOWN) { return -1; } nLastFlat = docCache.getFlatParagraphNumber(textPara); return nLastFlat; } /** * Set the view cursor to text position x, y * y = Paragraph of pure text (no footnotes, tables, etc.) * x = number of character in paragraph */ public static void setTextViewCursor(int x, TextParagraph y, ViewCursorTools viewCursor) { viewCursor.setTextViewCursor(x, y); } /** * Set the view cursor to position of flat paragraph xFlat, yFlat * y = Flat paragraph of pure text (includes footnotes, tables, etc.) * x = number of character in flat paragraph */ private boolean setFlatViewCursor(int xFlat, int yFlat, ViewCursorTools viewCursor, DocumentCache docCache) { if (yFlat < 0) { return false; } TextParagraph para = docCache.getNumberOfTextParagraph(yFlat); viewCursor.setTextViewCursor(xFlat, para); return true; } /** * change the text of a paragraph independent of the type of document */ private void changeTextOfParagraph(int nFPara, int nStart, int nLength, String replace, SingleDocument document, ViewCursorTools viewCursor) { String sPara = docCache.getFlatParagraph(nFPara); String sEnd = (nStart + nLength < sPara.length() ? sPara.substring(nStart + nLength) : ""); sPara = sPara.substring(0, nStart) + replace + sEnd; if (debugMode) { MessageHandler.printToLogFile("CheckDialog: changeTextOfParagraph: set setFlatParagraph: " + sPara); } docCache.setFlatParagraph(nFPara, sPara); document.removeResultCache(nFPara); document.removeIgnoredMatch(nFPara, true); if (docType == DocumentType.IMPRESS) { OfficeDrawTools.changeTextOfParagraph(nFPara, nStart, nLength, replace, document.getXComponent()); } else if (docType == DocumentType.CALC) { OfficeSpreadsheetTools.setTextofCell(nFPara, sPara, document.getXComponent()); } else { TextParagraph tPara = docCache.getNumberOfTextParagraph(nFPara); if (tPara.type != DocumentCache.CURSOR_TYPE_UNKNOWN) { MessageHandler.printToLogFile("CheckDialog: changeTextOfParagraph: nStart = " + nStart + ", nLength = " + nLength + ", replace = " + replace); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: changeTextOfParagraph: set viewCursor"); } setTextViewCursor(nStart, tPara, viewCursor); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: changeTextOfParagraph: set setViewCursorParagraphText:" + replace); } viewCursor.setViewCursorParagraphText(nStart, nLength, replace); } else { document.getFlatParagraphTools().changeTextOfParagraph(nFPara, nStart, nLength, replace); } } if (documents.getConfiguration().useTextLevelQueue() && !documents.getConfiguration().noBackgroundCheck()) { for (int i = 1; i < documents.getNumMinToCheckParas().size(); i++) { document.addQueueEntry(nFPara, i, documents.getNumMinToCheckParas().get(i), document.getDocID(), false, true); } } } /** * Get the first error in the flat paragraph nFPara at or after character position x * @throws Throwable */ private CheckError getNextErrorInParagraph (int x, int nFPara, SingleDocument document, DocumentCursorTools docTools) throws Throwable { String text = docCache.getFlatParagraph(nFPara); locale = docCache.getFlatParagraphLocale(nFPara); if (locale.Language.equals("zxx")) { // unknown Language locale = documents.getLocale(); } int[] footnotePosition = docCache.getFlatParagraphFootnotes(nFPara); CheckError sError = null; SingleProofreadingError gError = null; if (checkType != 2) { sError = getNextSpellErrorInParagraph (x, nFPara, text, locale, document); } if (checkType != 1) { gError = getNextGrammatikErrorInParagraph(x, nFPara, text, footnotePosition, locale, document); } if (sError != null) { if (gError != null && gError.nErrorStart < sError.error.nErrorStart) { return new CheckError(locale, gError); } return sError; } else if (gError != null) { return new CheckError(locale, gError); } else { return null; } } /** * Get the first spelling error in the flat paragraph nPara at or after character position x * @throws Throwable */ private CheckError getNextSpellErrorInParagraph (int x, int nPara, String text, Locale locale, SingleDocument document) throws Throwable { List<CheckError> spellErrors; if (lt.isRemote()) { spellErrors = getRemoteSpellErrorInParagraph(nPara, text, locale, document); } else { spellErrors = spellChecker.getSpellErrors(nPara, text, locale, document); } if (spellErrors != null) { for (CheckError spellError : spellErrors) { if (spellError.error != null && spellError.error.nErrorStart >= x) { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: getNextSpellErrorInParagraph: Next Error: ErrorStart == " + spellError.error.nErrorStart + ", x: " + x); } return spellError; } } } return null; } /** * Get the first grammatical error in the flat paragraph y at or after character position x */ private List<CheckError> getRemoteSpellErrorInParagraph(int nPara, String text, Locale locale, SingleDocument document) throws Throwable { if (text == null || text.isEmpty()) { return null; } List<CheckError> errorArray = new ArrayList<CheckError>(); List<RuleMatch> matches = lt.check(text, true, ParagraphHandling.ONLYNONPARA, RemoteCheck.ONLY_SPELL); for (RuleMatch match : matches) { String word = text.substring(match.getFromPos(), match.getToPos()); if (!document.isIgnoreOnce(match.getFromPos(), match.getToPos(), nPara, spellRuleId) && !spellChecker.getLinguServices().isCorrectSpell(word, locale)) { SingleProofreadingError aError = new SingleProofreadingError(); aError.nErrorType = TextMarkupType.SPELLCHECK; aError.aFullComment = JLanguageTool.getMessageBundle().getString("desc_spelling"); aError.aShortComment = aError.aFullComment; aError.nErrorStart = match.getFromPos(); aError.nErrorLength = match.getToPos() - match.getFromPos(); aError.aRuleIdentifier = spellRuleId; errorArray.add(new CheckError(locale, aError)); if (match.getSuggestedReplacements() != null) { aError.aSuggestions = match.getSuggestedReplacements().toArray(new String[match.getSuggestedReplacements().size()]); } else { aError.aSuggestions = new String[0]; } } } return errorArray; } /** * Get the first grammatical error in the flat paragraph y at or after character position x */ SingleProofreadingError getNextGrammatikErrorInParagraph(int x, int nFPara, String text, int[] footnotePosition, Locale locale, SingleDocument document) throws Throwable { if (text == null || text.isEmpty() || x >= text.length() || !documents.hasLocale(locale)) { return null; } PropertyValue[] propertyValues = { new PropertyValue("FootnotePositions", -1, footnotePosition, PropertyState.DIRECT_VALUE) }; ProofreadingResult paRes = new ProofreadingResult(); paRes.nStartOfSentencePosition = 0; paRes.nStartOfNextSentencePosition = 0; paRes.nBehindEndOfSentencePosition = paRes.nStartOfNextSentencePosition; paRes.xProofreader = null; paRes.aLocale = locale; paRes.aDocumentIdentifier = document.getDocID(); paRes.aText = text; paRes.aProperties = propertyValues; paRes.aErrors = null; Language langForShortName = documents.getLanguage(locale); if (doInit || !langForShortName.equals(lastLanguage)) { lastLanguage = langForShortName; setLangTool(documents, lastLanguage); document.removeResultCache(nFPara); } while (paRes.nStartOfNextSentencePosition < text.length()) { paRes.nStartOfSentencePosition = paRes.nStartOfNextSentencePosition; paRes.nStartOfNextSentencePosition = text.length(); paRes.nBehindEndOfSentencePosition = paRes.nStartOfNextSentencePosition; if (debugMode) { for (String id : lt.getDisabledRules()) { MessageHandler.printToLogFile("CheckDialog: getNextGrammatikErrorInParagraph: Dialog disabled rule: " + id); } } paRes = document.getCheckResults(text, locale, paRes, propertyValues, false, lt, nFPara); if (paRes.aErrors != null) { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: getNextGrammatikErrorInParagraph: Number of Errors = " + paRes.aErrors.length + ", Paragraph: " + nFPara + ", Next Position: " + paRes.nStartOfNextSentencePosition + ", Text.lenth: " + text.length()); } for (SingleProofreadingError error : paRes.aErrors) { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: getNextGrammatikErrorInParagraph: Start: " + error.nErrorStart + ", ID: " + error.aRuleIdentifier); } if (error.nErrorStart >= x) { return error; } } } } return null; } /** * Class for spell checking in LT check dialog * The LO/OO spell checker is used */ public class ExtensionSpellChecker { private LinguisticServices linguServices; ExtensionSpellChecker() { linguServices = new LinguisticServices(xContext); } /** * get a list of all spelling errors of the flat paragraph nPara */ public List<CheckError> getSpellErrors(int nPara, String text, Locale lang, SingleDocument document) throws Throwable { try { List<CheckError> errorArray = new ArrayList<CheckError>(); if (document == null) { return null; } XFlatParagraph xFlatPara = null; if (docType == DocumentType.WRITER) { xFlatPara = document.getFlatParagraphTools().getFlatParagraphAt(nPara); if (xFlatPara == null) { return null; } } Locale locale = null; AnalyzedSentence analyzedSentence = lt.getAnalyzedSentence(text); AnalyzedTokenReadings[] tokens = analyzedSentence.getTokensWithoutWhitespace(); for (int i = 0; i < tokens.length; i++) { AnalyzedTokenReadings token = tokens[i]; String sToken = token.getToken(); if (!token.isNonWord()) { int nStart = token.getStartPos(); int nEnd = token.getEndPos(); if (i < tokens.length - 1) { if (tokens[i + 1].getToken().equals(".")) { sToken += "."; } else { String nextToken = tokens[i + 1].getToken(); boolean shouldComposed = nextToken.length() > 1 && (nextToken.charAt(0) == '’' || nextToken.charAt(0) == '\'' || nextToken.startsWith("n’") || nextToken.startsWith("n'")); if (shouldComposed) { sToken += nextToken; nEnd = tokens[i + 1].getEndPos(); i++; } } } if (sToken.length() > 1) { if (xFlatPara != null) { locale = xFlatPara.getLanguageOfText(nStart, nEnd - nStart); } if (locale == null) { locale = lang; } if (!linguServices.isCorrectSpell(sToken, locale)) { SingleProofreadingError aError = new SingleProofreadingError(); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: getSpellErrors: Spell Error: Word: " + sToken + ", Start: " + nStart + ", End: " + nEnd + ", Token(" + i + "): " + tokens[i].getToken() + (i < tokens.length - 1 ? (", Token(" + (i + 1) + "): " + tokens[i + 1].getToken()) : "")); } if (!document.isIgnoreOnce(nStart, nEnd, nPara, spellRuleId)) { aError.nErrorType = TextMarkupType.SPELLCHECK; aError.aFullComment = spellingError; aError.aShortComment = aError.aFullComment; aError.nErrorStart = nStart; aError.nErrorLength = nEnd - nStart; aError.aRuleIdentifier = spellRuleId; errorArray.add(new CheckError(locale, aError)); String[] alternatives = linguServices.getSpellAlternatives(token.getToken(), locale); if (alternatives != null) { aError.aSuggestions = alternatives; } else { aError.aSuggestions = new String[0]; } } } } } } return errorArray; } catch (Throwable t) { MessageHandler.showError(t); } return null; } /** * replaces all words that matches 'word' with the string 'replace' * gives back a map of positions where a replace was done (for undo function) */ public Map<Integer, List<Integer>> replaceAllWordsInText(String word, String replace, DocumentCursorTools cursorTools, SingleDocument document, ViewCursorTools viewCursor) { if (word == null || replace == null || word.isEmpty() || replace.isEmpty() || word.equals(replace)) { return null; } Map<Integer, List<Integer>> replacePoints = new HashMap<Integer, List<Integer>>(); try { int xVC = 0; TextParagraph yVC = null; if (docType == DocumentType.WRITER) { yVC = viewCursor.getViewCursorParagraph(); xVC = viewCursor.getViewCursorCharacter(); } for (int n = 0; n < docCache.size(); n++) { if (lt.isRemote()) { String text = docCache.getFlatParagraph(n); List<RuleMatch> matches = lt.check(text, true, ParagraphHandling.ONLYNONPARA, RemoteCheck.ONLY_SPELL); for (RuleMatch match : matches) { List<Integer> x; String matchWord = text.substring(match.getFromPos(), match.getToPos()); if (matchWord.equals(word)) { changeTextOfParagraph(n, match.getFromPos(), word.length(), replace, document, viewCursor); if (replacePoints.containsKey(n)) { x = replacePoints.get(n); } else { x = new ArrayList<Integer>(); } x.add(0, match.getFromPos()); replacePoints.put(n, x); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: replaceAllWordsInText: add change undo: y = " + n + ", NumX = " + replacePoints.get(n).size()); } } } } else { AnalyzedSentence analyzedSentence = lt.getAnalyzedSentence(docCache.getFlatParagraph(n)); AnalyzedTokenReadings[] tokens = analyzedSentence.getTokensWithoutWhitespace(); for (int i = tokens.length - 1; i >= 0 ; i List<Integer> x ; if (tokens[i].getToken().equals(word)) { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: replaceAllWordsInText: change paragraph: y = " + n + ", word = " + tokens[i].getToken() + ", replace = " + word); } changeTextOfParagraph(n, tokens[i].getStartPos(), word.length(), replace, document, viewCursor); if (replacePoints.containsKey(n)) { x = replacePoints.get(n); } else { x = new ArrayList<Integer>(); } x.add(0, tokens[i].getStartPos()); replacePoints.put(n, x); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: replaceAllWordsInText: add change undo: y = " + n + ", NumX = " + replacePoints.get(n).size()); } } } } } if (docType == DocumentType.WRITER) { setTextViewCursor(xVC, yVC, viewCursor); } } catch (Throwable t) { MessageHandler.showError(t); } return replacePoints; } public LinguisticServices getLinguServices() { return linguServices; } } /** * class to store the information for undo */ public class UndoContainer { public int x; public int y; public String action; public String ruleId; public String word; public Map<Integer, List<Integer>> orgParas; UndoContainer(int x, int y, String action, String ruleId, String word, Map<Integer, List<Integer>> orgParas) { this.x = x; this.y = y; this.action = action; this.ruleId = ruleId; this.orgParas = orgParas; this.word = word; } } /** * class contains the SingleProofreadingError and the locale of the match */ public class CheckError { public Locale locale; public SingleProofreadingError error; CheckError(Locale locale, SingleProofreadingError error) { this.locale = locale; this.error = error; } } /** * Class for dialog to check text for spell and grammar errors */ public class LtCheckDialog implements ActionListener { private final static int maxUndos = 20; private final static int toolTipWidth = 300; private final static int begFirstCol = 10; private final static int widFirstCol = 440; private final static int disFirstCol = 10; private final static int buttonHigh = 30; private final static int begSecondCol = 460; private final static int buttonWidthCol = 160; private final static int buttonDistCol = 10; private final static int buttonWidthRow = 120; private final static int buttonDistRow = (begSecondCol + buttonWidthCol - begFirstCol - 4 * buttonWidthRow) / 3; private final static int progressBarDist = 65; private final static int dialogWidth = 640; private final static int dialogHeight = 525; private Color defaultForeground; private final JDialog dialog; private final JLabel languageLabel; private final JComboBox<String> language; private final JComboBox<String> changeLanguage; private final JTextArea errorDescription; private final JTextPane sentenceIncludeError; private final JLabel suggestionsLabel; private final JList<String> suggestions; private final JLabel checkTypeLabel; private final JLabel checkStatus; private final ButtonGroup checkTypeGroup; private final JRadioButton[] checkTypeButtons; private final JButton more; private final JButton ignoreOnce; private final JButton ignoreAll; private final JButton deactivateRule; private final JComboBox<String> addToDictionary; private final JComboBox<String> activateRule; private final JButton change; private final JButton changeAll; private final JButton help; private final JButton options; private final JButton undo; private final JButton close; private final JProgressBar checkProgress; private final Image ltImage; private SingleDocument currentDocument; private ViewCursorTools viewCursor; private SingleProofreadingError error; String docId; private String[] userDictionaries; private String informationUrl; private String lastLang = new String(); private String endOfDokumentMessage; private int x = 0; private int y = 0; // current flat Paragraph private int startOfRange = -1; private int endOfRange = -1; private int lastPara = -1; private boolean isSpellError = false; private boolean focusLost = false; private boolean isRunning = false; private String wrongWord; private List<UndoContainer> undoList; private Locale locale; private Object checkWakeup = new Object(); /** * the constructor of the class creates all elements of the dialog */ public LtCheckDialog(XComponentContext xContext) { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: LtCheckDialog: LtCheckDialog called"); } currentDocument = getCurrentDocument(false); docId = currentDocument.getDocID(); undoList = new ArrayList<UndoContainer>(); setUserDictionaries(); ltImage = OfficeTools.getLtImage(); dialog = new JDialog(); if (dialog == null) { MessageHandler.printToLogFile("CheckDialog: LtCheckDialog: LtCheckDialog == null"); } dialog.setName(dialogName); dialog.setTitle(dialogName); dialog.setLayout(null); dialog.setSize(dialogWidth, dialogHeight); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); ((Frame) dialog.getOwner()).setIconImage(ltImage); defaultForeground = dialog.getForeground() == null ? Color.BLACK : dialog.getForeground(); languageLabel = new JLabel(labelLanguage); Font dialogFont = languageLabel.getFont(); languageLabel.setBounds(begFirstCol, disFirstCol, 180, 30); languageLabel.setFont(dialogFont); dialog.add(languageLabel); changeLanguage = new JComboBox<String> (changeLanguageList); language = new JComboBox<String>(getPossibleLanguages()); language.setFont(dialogFont); language.setBounds(190, disFirstCol, widFirstCol + begFirstCol - 190, 30); language.setToolTipText(formatToolTipText(languageHelp)); language.addItemListener(e -> { if (e.getStateChange() == ItemEvent.SELECTED) { String selectedLang = (String) language.getSelectedItem(); if (!lastLang.equals(selectedLang)) { changeLanguage.setEnabled(true); } } }); dialog.add(language); changeLanguage.setFont(dialogFont); changeLanguage.setBounds(begSecondCol, disFirstCol, buttonWidthCol, buttonHigh); changeLanguage.setToolTipText(formatToolTipText(changeLanguageHelp)); changeLanguage.addItemListener(e -> { if (e.getStateChange() == ItemEvent.SELECTED) { try { Locale locale = null; FlatParagraphTools flatPara= null; if (changeLanguage.getSelectedIndex() > 0) { String selectedLang = (String) language.getSelectedItem(); locale = getLocaleFromLanguageName(selectedLang); flatPara = currentDocument.getFlatParagraphTools(); currentDocument.removeResultCache(y); if (changeLanguage.getSelectedIndex() == 1) { if (docType == DocumentType.IMPRESS) { OfficeDrawTools.setLanguageOfParagraph(y, error.nErrorStart, error.nErrorLength, locale, currentDocument.getXComponent()); } else if (docType == DocumentType.CALC) { OfficeSpreadsheetTools.setLanguageOfSpreadsheet(locale, currentDocument.getXComponent()); } else { flatPara.setLanguageOfParagraph(y, error.nErrorStart, error.nErrorLength, locale); } addLanguageChangeUndo(y, error.nErrorStart, error.nErrorLength, lastLang); docCache.setMultilingualFlatParagraph(y); } else if (changeLanguage.getSelectedIndex() == 2) { if (docType == DocumentType.IMPRESS) { OfficeDrawTools.setLanguageOfParagraph(y, 0, docCache.getFlatParagraph(y).length(), locale, currentDocument.getXComponent()); } else if (docType == DocumentType.CALC) { OfficeSpreadsheetTools.setLanguageOfSpreadsheet(locale, currentDocument.getXComponent()); } else { flatPara.setLanguageOfParagraph(y, 0, docCache.getFlatParagraph(y).length(), locale); } docCache.setFlatParagraphLocale(y, locale); addLanguageChangeUndo(y, 0, docCache.getFlatParagraph(y).length(), lastLang); } lastLang = selectedLang; changeLanguage.setSelectedIndex(0); gotoNextError(); } } catch (Throwable t) { MessageHandler.showError(t); } } }); changeLanguage.setSelectedIndex(0); changeLanguage.setEnabled(false); dialog.add(changeLanguage); int yFirstCol = 2 * disFirstCol + 30; errorDescription = new JTextArea(); errorDescription.setEditable(false); errorDescription.setLineWrap(true); errorDescription.setWrapStyleWord(true); errorDescription.setBackground(dialog.getContentPane().getBackground()); errorDescription.setForeground(defaultForeground); Font descriptionFont = dialogFont.deriveFont(Font.BOLD); errorDescription.setFont(descriptionFont); errorDescription.setToolTipText(formatToolTipText(matchDescriptionHelp)); JScrollPane descriptionPane = new JScrollPane(errorDescription); descriptionPane.setBounds(begFirstCol, yFirstCol, widFirstCol, 40); dialog.add(descriptionPane); yFirstCol += disFirstCol + 40; sentenceIncludeError = new JTextPane(); sentenceIncludeError.setFont(dialogFont); sentenceIncludeError.setToolTipText(formatToolTipText(matchParagraphHelp)); sentenceIncludeError.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { if (!change.isEnabled()) { change.setEnabled(true); } if (changeAll.isEnabled()) { changeAll.setEnabled(false); } } @Override public void insertUpdate(DocumentEvent e) { changedUpdate(e); } @Override public void removeUpdate(DocumentEvent e) { changedUpdate(e); } }); JScrollPane sentencePane = new JScrollPane(sentenceIncludeError); sentencePane.setBounds(begFirstCol, yFirstCol, widFirstCol, 110); dialog.add(sentencePane); yFirstCol += disFirstCol + 110; suggestionsLabel = new JLabel(labelSuggestions); suggestionsLabel.setFont(dialogFont); suggestionsLabel.setBounds(begFirstCol, yFirstCol, widFirstCol, 15); dialog.add(suggestionsLabel); yFirstCol += disFirstCol + 10; int suggestionsY = yFirstCol; suggestions = new JList<String>(); suggestions.setFont(dialogFont); suggestions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); suggestions.setFixedCellHeight((int)(suggestions.getFont().getSize() * 1.2 + 0.5)); suggestions.setToolTipText(formatToolTipText(suggestionsHelp)); JScrollPane suggestionsPane = new JScrollPane(suggestions); suggestionsPane.setBounds(begFirstCol, yFirstCol, widFirstCol, 110); dialog.add(suggestionsPane); yFirstCol += disFirstCol + 105; checkTypeLabel = new JLabel(Tools.getLabel(messages.getString("guiOOoCheckTypeLabel"))); checkTypeLabel.setFont(dialogFont); checkTypeLabel.setBounds(begFirstCol, yFirstCol, 3*widFirstCol/16 - 1, 30); checkTypeLabel.setToolTipText(formatToolTipText(checkTypeHelp)); dialog.add(checkTypeLabel); checkTypeButtons = new JRadioButton[3]; checkTypeGroup = new ButtonGroup(); checkTypeButtons[0] = new JRadioButton(Tools.getLabel(messages.getString("guiOOoCheckAllButton"))); checkTypeButtons[0].setBounds(begFirstCol + 3*widFirstCol/16, yFirstCol, 3*widFirstCol/16 - 1, 30); checkTypeButtons[0].setSelected(true); checkTypeButtons[0].addActionListener(e -> { checkType = 0; gotoNextError(); }); checkTypeButtons[1] = new JRadioButton(Tools.getLabel(messages.getString("guiOOoCheckSpellingButton"))); checkTypeButtons[1].setBounds(begFirstCol + 6*widFirstCol/16, yFirstCol, 5*widFirstCol/16 - 1, 30); checkTypeButtons[1].addActionListener(e -> { checkType = 1; gotoNextError(); }); checkTypeButtons[2] = new JRadioButton(Tools.getLabel(messages.getString("guiOOoCheckGrammarButton"))); checkTypeButtons[2].setBounds(begFirstCol + 11*widFirstCol/16, yFirstCol, 5*widFirstCol/16 - 1, 30); checkTypeButtons[2].addActionListener(e -> { checkType = 2; gotoNextError(); }); for (int i = 0; i < 3; i++) { checkTypeGroup.add(checkTypeButtons[i]); checkTypeButtons[i].setFont(dialogFont); checkTypeButtons[i].setToolTipText(formatToolTipText(checkTypeHelp)); dialog.add(checkTypeButtons[i]); } yFirstCol += 2 * disFirstCol + 30; help = new JButton (helpButtonName); help.setFont(dialogFont); help.setBounds(begFirstCol, yFirstCol, buttonWidthRow, buttonHigh); help.addActionListener(this); help.setActionCommand("help"); help.setToolTipText(formatToolTipText(helpButtonHelp)); dialog.add(help); int xButtonRow = begFirstCol + buttonWidthRow + buttonDistRow; options = new JButton (optionsButtonName); options.setFont(dialogFont); options.setBounds(xButtonRow, yFirstCol, buttonWidthRow, buttonHigh); options.addActionListener(this); options.setActionCommand("options"); options.setToolTipText(formatToolTipText(optionsButtonHelp)); dialog.add(options); xButtonRow += buttonWidthRow + buttonDistRow; undo = new JButton (undoButtonName); undo.setFont(dialogFont); undo.setBounds(xButtonRow, yFirstCol, buttonWidthRow, buttonHigh); undo.addActionListener(this); undo.setActionCommand("undo"); undo.setToolTipText(formatToolTipText(undoButtonHelp)); dialog.add(undo); xButtonRow += buttonWidthRow + buttonDistRow; close = new JButton (closeButtonName); close.setFont(dialogFont); close.setBounds(xButtonRow, yFirstCol, buttonWidthRow, buttonHigh); close.addActionListener(this); close.setActionCommand("close"); close.setToolTipText(formatToolTipText(closeButtonHelp)); dialog.add(close); int ySecondCol = 2 * disFirstCol + 30; more = new JButton (moreButtonName); more.setBounds(begSecondCol, ySecondCol, buttonWidthCol, buttonHigh); more.setFont(dialogFont); more.addActionListener(this); more.setActionCommand("more"); more.setToolTipText(formatToolTipText(moreButtonHelp)); dialog.add(more); ySecondCol += disFirstCol + 40; ignoreOnce = new JButton (ignoreButtonName); ignoreOnce.setFont(dialogFont); ignoreOnce.setBounds(begSecondCol, ySecondCol, buttonWidthCol, buttonHigh); ignoreOnce.addActionListener(this); ignoreOnce.setActionCommand("ignoreOnce"); ignoreOnce.setToolTipText(formatToolTipText(ignoreButtonHelp)); dialog.add(ignoreOnce); ySecondCol += buttonDistCol + buttonHigh; ignoreAll = new JButton (ignoreAllButtonName); ignoreAll.setFont(dialogFont); ignoreAll.setBounds(begSecondCol, ySecondCol, buttonWidthCol, buttonHigh); ignoreAll.addActionListener(this); ignoreAll.setActionCommand("ignoreAll"); ignoreAll.setToolTipText(formatToolTipText(ignoreAllButtonHelp)); dialog.add(ignoreAll); ySecondCol += buttonDistCol + buttonHigh; deactivateRule = new JButton (deactivateRuleButtonName); deactivateRule.setFont(dialogFont); deactivateRule.setBounds(begSecondCol, ySecondCol, buttonWidthCol, buttonHigh); deactivateRule.setVisible(false); deactivateRule.addActionListener(this); deactivateRule.setActionCommand("deactivateRule"); deactivateRule.setToolTipText(formatToolTipText(deactivateRuleButtonHelp)); dialog.add(deactivateRule); addToDictionary = new JComboBox<String> (userDictionaries); addToDictionary.setFont(dialogFont); addToDictionary.setBounds(begSecondCol, ySecondCol, buttonWidthCol, buttonHigh); addToDictionary.setToolTipText(formatToolTipText(addToDictionaryHelp)); addToDictionary.addItemListener(e -> { if (e.getStateChange() == ItemEvent.SELECTED) { if (addToDictionary.getSelectedIndex() > 0) { try { String dictionary = (String) addToDictionary.getSelectedItem(); documents.getLtDictionary().addWordToDictionary(dictionary, wrongWord, xContext); addUndo(y, "addToDictionary", dictionary, wrongWord); addToDictionary.setSelectedIndex(0); gotoNextError(); } catch (Throwable t) { MessageHandler.showError(t); } } } }); dialog.add(addToDictionary); ySecondCol = suggestionsY; change = new JButton (changeButtonName); change.setFont(dialogFont); change.setBounds(begSecondCol, ySecondCol, buttonWidthCol, buttonHigh); change.addActionListener(this); change.setActionCommand("change"); change.setToolTipText(formatToolTipText(changeButtonHelp)); dialog.add(change); ySecondCol += buttonDistCol + buttonHigh; changeAll = new JButton (changeAllButtonName); changeAll.setFont(dialogFont); changeAll.setBounds(begSecondCol, ySecondCol, buttonWidthCol, buttonHigh); changeAll.addActionListener(this); changeAll.setActionCommand("changeAll"); changeAll.setEnabled(false); changeAll.setToolTipText(formatToolTipText(changeAllButtonHelp)); dialog.add(changeAll); ySecondCol += buttonDistCol + buttonHigh; activateRule = new JComboBox<String> (); activateRule.setFont(dialogFont); activateRule.setBounds(begSecondCol, ySecondCol, buttonWidthCol, buttonHigh); activateRule.setToolTipText(formatToolTipText(activateRuleButtonHelp)); activateRule.addItemListener(e -> { if (e.getStateChange() == ItemEvent.SELECTED) { try { int selectedIndex = activateRule.getSelectedIndex(); if (selectedIndex > 0) { Map<String, String> deactivatedRulesMap = documents.getDisabledRulesMap(OfficeTools.localeToString(locale)); int j = 1; for(String ruleId : deactivatedRulesMap.keySet()) { if (j == selectedIndex) { documents.activateRule(ruleId); addUndo(y, "activateRule", ruleId, null); activateRule.setSelectedIndex(0); gotoNextError(); } j++; } } } catch (Throwable t) { MessageHandler.showError(t); } } }); dialog.add(activateRule); dialog.addWindowFocusListener(new WindowFocusListener() { @Override public void windowGainedFocus(WindowEvent e) { try { dialog.setEnabled(false); Point p = dialog.getLocation(); dialogX = p.x; dialogY = p.y; if (focusLost) { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: LtCheckDialog: Window Focus gained: Event = " + e.paramString()); } currentDocument = getCurrentDocument(true); if (currentDocument == null) { closeDialog(); return; } String newDocId = currentDocument.getDocID(); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: LtCheckDialog: Window Focus gained: new docID = " + newDocId + ", old = " + docId + ", docType: " + docType); } if (!docId.equals(newDocId)) { docId = newDocId; undoList = new ArrayList<UndoContainer>(); } dialog.setEnabled(false); if (!initCursor()) { closeDialog(); return; } if (debugMode) { MessageHandler.printToLogFile("CheckDialog: LtCheckDialog: cache refreshed - size: " + docCache.size()); } gotoNextError(); dialog.setEnabled(true); focusLost = false; } } catch (Throwable t) { MessageHandler.showError(t); } } @Override public void windowLostFocus(WindowEvent e) { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: LtCheckDialog: Window Focus lost: Event = " + e.paramString()); } focusLost = true; } }); checkStatus = new JLabel(checkStatusInitialization); checkStatus.setBounds(begFirstCol, dialogHeight - progressBarDist, 100, 20); checkStatus.setFont(checkStatus.getFont().deriveFont(Font.BOLD)); checkStatus.setForeground(Color.RED); dialog.add(checkStatus); checkProgress = new JProgressBar(0, 100); checkProgress.setStringPainted(true); checkProgress.setBounds(begFirstCol + 100, dialogHeight - progressBarDist, dialogWidth - begFirstCol - 120, 20); dialog.add(checkProgress); ToolTipManager.sharedInstance().setDismissDelay(30000); } /** * show the dialog * @throws Throwable */ public void show() throws Throwable { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: show: Goto next Error"); } dialog.setEnabled(false); dialog.setEnabled(true); if (dialogX < 0 || dialogY < 0) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = dialog.getSize(); dialogX = screenSize.width / 2 - frameSize.width / 2; dialogY = screenSize.height / 2 - frameSize.height / 2; } dialog.setLocation(dialogX, dialogY); isRunning = true; setInitialButtonState(); dialog.setAutoRequestFocus(true); dialog.setVisible(true); try { Thread.sleep(500); } catch (InterruptedException e) { MessageHandler.printException(e); } dialog.toFront(); if (!initCursor()) { return; } // runCheckForNextError(false); gotoNextError(false); } /** * Initialize the cursor / define the range for check * @throws Throwable */ private boolean initCursor() throws Throwable { if (docType == DocumentType.WRITER) { viewCursor = new ViewCursorTools(currentDocument.getXComponent()); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: initCursor: viewCursor initialized: docId: " + docId); } XTextCursor tCursor = viewCursor.getTextCursorBeginn(); if (tCursor != null) { tCursor.gotoStart(true); int nBegin = tCursor.getString().length(); tCursor = viewCursor.getTextCursorEnd(); tCursor.gotoStart(true); int nEnd = tCursor.getString().length(); if (nBegin < nEnd) { startOfRange = viewCursor.getViewCursorCharacter(); endOfRange = nEnd - nBegin + startOfRange; } else { startOfRange = -1; endOfRange = -1; } } else { MessageHandler.showClosingInformationDialog(messages.getString("loDialogUnsupported")); closeDialog(); return false; } } else { startOfRange = -1; endOfRange = -1; } lastPara = -1; return true; } /** * Formats the tooltip text * The text is given by a text string which is formated into html: * \n are formated to html paragraph breaks * \n- is formated to an unordered List * \n1. is formated to an ordered List (every digit 1 - 9 is allowed */ private String formatToolTipText(String Text) { String toolTipText = Text; int breakIndex = 0; int isNum = 0; while (breakIndex >= 0) { breakIndex = toolTipText.indexOf("\n", breakIndex); if (breakIndex >= 0) { int nextNonBlank = breakIndex + 1; while (' ' == toolTipText.charAt(nextNonBlank)) { nextNonBlank++; } if (isNum == 0) { if (toolTipText.charAt(nextNonBlank) == '-') { toolTipText = toolTipText.substring(0, breakIndex) + "</p><ul width=\"" + toolTipWidth + "\"><li>" + toolTipText.substring(nextNonBlank + 1); isNum = 1; } else if (toolTipText.charAt(nextNonBlank) >= '1' && toolTipText.charAt(nextNonBlank) <= '9' && toolTipText.charAt(nextNonBlank + 1) == '.') { toolTipText = toolTipText.substring(0, breakIndex) + "</p><ol width=\"" + toolTipWidth + "\"><li>" + toolTipText.substring(nextNonBlank + 2); isNum = 2; } else { toolTipText = toolTipText.substring(0, breakIndex) + "</p><p width=\"" + toolTipWidth + "\">" + toolTipText.substring(breakIndex + 1); } } else if (isNum == 1) { if (toolTipText.charAt(nextNonBlank) == '-') { toolTipText = toolTipText.substring(0, breakIndex) + "</li><li>" + toolTipText.substring(nextNonBlank + 1); } else { toolTipText = toolTipText.substring(0, breakIndex) + "</li></ul><p width=\"" + toolTipWidth + "\">" + toolTipText.substring(breakIndex + 1); isNum = 0; } } else { if (toolTipText.charAt(nextNonBlank) >= '1' && toolTipText.charAt(nextNonBlank) <= '9' && toolTipText.charAt(nextNonBlank + 1) == '.') { toolTipText = toolTipText.substring(0, breakIndex) + "</li><li>" + toolTipText.substring(nextNonBlank + 2); } else { toolTipText = toolTipText.substring(0, breakIndex) + "</li></ol><p width=\"" + toolTipWidth + "\">" + toolTipText.substring(breakIndex + 1); isNum = 0; } } } } if (isNum == 0) { toolTipText = "<html><div style='color:black;'><p width=\"" + toolTipWidth + "\">" + toolTipText + "</p></html>"; } else if (isNum == 1) { toolTipText = "<html><div style='color:black;'><p width=\"" + toolTipWidth + "\">" + toolTipText + "</ul></html>"; } else { toolTipText = "<html><div style='color:black;'><p width=\"" + toolTipWidth + "\">" + toolTipText + "</ol></html>"; } return toolTipText; } /** * Initial button state */ private void setInitialButtonState() { ignoreOnce.setEnabled(false); ignoreAll.setEnabled(false); deactivateRule.setEnabled(false); change.setEnabled(false); changeAll.setVisible(false); addToDictionary.setEnabled(false); more.setEnabled(false); help.setEnabled(false); options.setEnabled(false); undo.setEnabled(false); close.setEnabled(false); language.setEnabled(false); changeLanguage.setEnabled(false); activateRule.setEnabled(false); endOfDokumentMessage = null; sentenceIncludeError.setEnabled(false); suggestions.setEnabled(false); errorDescription.setForeground(defaultForeground); } *//* *//* /** * find the next match * set the view cursor to the position of match * fill the elements of the dialog with the information of the match * @throws Throwable */ private void gotoNextError() { gotoNextError(true); } private void gotoNextError(boolean startAtBegin) { // private void findNextError(boolean startAtBegin) throws Throwable { try { if (!documents.isEnoughHeapSpace()) { closeDialog(); return; } setInitialButtonState(); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: findNextError: start getNextError"); } CheckError checkError = getNextError(startAtBegin); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: findNextError: Error is " + (checkError == null ? "Null" : "NOT Null")); } error = checkError == null ? null : checkError.error; locale = checkError == null ? null : checkError.locale; dialog.setEnabled(true); help.setEnabled(true); options.setEnabled(true); close.setEnabled(true); activateRule.setEnabled(true); if (sentenceIncludeError == null || errorDescription == null || suggestions == null) { MessageHandler.printToLogFile("CheckDialog: findNextError: SentenceIncludeError == null || errorDescription == null || suggestions == null"); error = null; } if (error != null) { checkStatus.setText(checkStatusResult); checkStatus.setForeground(defaultForeground); ignoreOnce.setEnabled(true); ignoreAll.setEnabled(true); isSpellError = error.aRuleIdentifier.equals(spellRuleId); sentenceIncludeError.setEnabled(true); sentenceIncludeError.setText(docCache.getFlatParagraph(y)); setAttributesForErrorText(error); errorDescription.setText(error.aFullComment); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: findNextError: Error Text set"); } if (error.aSuggestions != null && error.aSuggestions.length > 0) { suggestions.setListData(error.aSuggestions); suggestions.setSelectedIndex(0); suggestions.setEnabled(true); change.setEnabled(true); changeAll.setEnabled(true); } else { suggestions.setListData(new String[0]); change.setEnabled(false); changeAll.setEnabled(false); } if (debugMode) { MessageHandler.printToLogFile("CheckDialog: findNextError: Suggestions set"); } Language lang = locale == null ? lt.getLanguage() : documents.getLanguage(locale); if (debugMode && lt.getLanguage() == null) { MessageHandler.printToLogFile("CheckDialog: findNextError: LT language == null"); } lastLang = lang.getTranslatedName(messages); language.setEnabled(true); language.setSelectedItem(lang.getTranslatedName(messages)); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: findNextError: Language set"); } Map<String, String> deactivatedRulesMap = documents.getDisabledRulesMap(OfficeTools.localeToString(locale)); if (!deactivatedRulesMap.isEmpty()) { activateRule.removeAllItems(); activateRule.addItem(messages.getString("loContextMenuActivateRule")); for (String ruleId : deactivatedRulesMap.keySet()) { activateRule.addItem(deactivatedRulesMap.get(ruleId)); } activateRule.setVisible(true); } else { activateRule.setVisible(false); } if (isSpellError) { addToDictionary.setVisible(true); changeAll.setVisible(true); deactivateRule.setVisible(false); addToDictionary.setEnabled(true); changeAll.setEnabled(true); } else { addToDictionary.setVisible(false); changeAll.setVisible(false); deactivateRule.setVisible(true); deactivateRule.setEnabled(true); } informationUrl = getUrl(error); more.setVisible(informationUrl != null); more.setEnabled(informationUrl != null); undo.setEnabled(undoList != null && !undoList.isEmpty()); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: findNextError: All set"); } } else { ignoreOnce.setEnabled(false); ignoreAll.setEnabled(false); deactivateRule.setEnabled(false); change.setEnabled(false); changeAll.setVisible(false); addToDictionary.setVisible(false); deactivateRule.setVisible(false); more.setVisible(false); focusLost = false; suggestions.setListData(new String[0]); undo.setEnabled(undoList != null && !undoList.isEmpty()); errorDescription.setForeground(Color.RED); errorDescription.setText(endOfDokumentMessage == null ? "" : endOfDokumentMessage); sentenceIncludeError.setText(""); if (docCache.size() > 0) { locale = docCache.getFlatParagraphLocale(docCache.size() - 1); } Language lang = locale == null || !documents.hasLocale(locale)? lt.getLanguage() : documents.getLanguage(locale); language.setSelectedItem(lang.getTranslatedName(messages)); checkStatus.setText(checkStatusResult); checkStatus.setForeground(defaultForeground); checkProgress.setValue(docCache != null && docCache.size() > 0 ? docCache.size() : 100); // Note: a delay interval is needed to update the dialog before wait // Thread.sleep(500); } } catch (Throwable e) { MessageHandler.showError(e); } } /** * stores the list of local dictionaries into the dialog element */ private void setUserDictionaries () { String[] tmpDictionaries = documents.getLtDictionary().getUserDictionaries(xContext); userDictionaries = new String[tmpDictionaries.length + 1]; userDictionaries[0] = addToDictionaryName; for (int i = 0; i < tmpDictionaries.length; i++) { userDictionaries[i + 1] = tmpDictionaries[i]; } } /** * returns an array of the translated names of the languages supported by LT */ private String[] getPossibleLanguages() { List<String> languages = new ArrayList<>(); for (Language lang : Languages.get()) { languages.add(lang.getTranslatedName(messages)); languages.sort(null); } return languages.toArray(new String[languages.size()]); } /** * returns the locale from a translated language name */ private Locale getLocaleFromLanguageName(String translatedName) { for (Language lang : Languages.get()) { if (translatedName.equals(lang.getTranslatedName(messages))) { return (LinguisticServices.getLocale(lang)); } } return null; } /** * set the attributes for the text inside the editor element */ private void setAttributesForErrorText(SingleProofreadingError error) { // Get Attributes MutableAttributeSet attrs = sentenceIncludeError.getInputAttributes(); StyledDocument doc = sentenceIncludeError.getStyledDocument(); // Set back to default values StyleConstants.setBold(attrs, false); StyleConstants.setUnderline(attrs, false); StyleConstants.setForeground(attrs, defaultForeground); doc.setCharacterAttributes(0, doc.getLength() + 1, attrs, true); // Set values for error StyleConstants.setBold(attrs, true); StyleConstants.setUnderline(attrs, true); Color color = null; if (isSpellError) { color = Color.RED; } else { PropertyValue[] properties = error.aProperties; for (PropertyValue property : properties) { if ("LineColor".equals(property.Name)) { color = new Color((int) property.Value); break; } } if (color == null) { color = Color.BLUE; } } StyleConstants.setForeground(attrs, color); doc.setCharacterAttributes(error.nErrorStart, error.nErrorLength, attrs, true); } /** * returns the URL to more information of match * returns null, if such an URL does not exist */ private String getUrl(SingleProofreadingError error) { if (!isSpellError) { PropertyValue[] properties = error.aProperties; for (PropertyValue property : properties) { if ("FullCommentURL".equals(property.Name)) { String url = new String((String) property.Value); return url; } } } return null; } /** * returns the next match * starting at the current cursor position * @throws Throwable */ private CheckError getNextError(boolean startAtBegin) throws Throwable { if (docType != DocumentType.WRITER) { currentDocument = getCurrentDocument(false); } if (currentDocument == null) { closeDialog(); return null; } XComponent xComponent = currentDocument.getXComponent(); DocumentCursorTools docCursor = new DocumentCursorTools(xComponent); if (docCache.size() <= 0) { MessageHandler.printToLogFile("CheckDialog: getNextError: docCache size == 0: Return null"); return null; } if (docType == DocumentType.WRITER) { y = docCache.getFlatParagraphNumber(viewCursor.getViewCursorParagraph()); } else if (docType == DocumentType.IMPRESS) { y = OfficeDrawTools.getParagraphFromCurrentPage(xComponent); } else { y = OfficeSpreadsheetTools.getParagraphFromCurrentSheet(xComponent); } if (y < 0 || y >= docCache.size()) { MessageHandler.printToLogFile("CheckDialog: getNextError: y (= " + y + ") >= text size (= " + docCache.size() + "): Return null"); endOfDokumentMessage = messages.getString("guiCheckComplete"); return null; } if (lastPara < 0) { lastPara = y; } if (debugMode) { MessageHandler.printToLogFile("CheckDialog: getNextError: (x/y): (" + x + "/" + y + ") < text size (= " + docCache.size() + ")"); } if (endOfRange >= 0 && y == lastPara) { x = startOfRange; } else { x = 0; } int nStart = 0; for (int i = lastPara; i < y && i < docCache.size(); i++) { nStart += docCache.getFlatParagraph(i).length() + 1; } checkProgress.setMaximum(endOfRange < 0 ? docCache.size() : endOfRange); checkStatus.setText(checkStatusCheck); checkStatus.setForeground(Color.RED); CheckError nextError = null; while (y < docCache.size() && y >= lastPara && nextError == null && (endOfRange < 0 || nStart < endOfRange)) { checkProgress.setValue(endOfRange < 0 ? y - lastPara : nStart); nextError = getNextErrorInParagraph (x, y, currentDocument, docCursor); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: getNextError: endOfRange = " + endOfRange + ", startOfRange = " + startOfRange + ", nStart = " + nStart); } int pLength = docCache.getFlatParagraph(y).length() + 1; nStart += pLength; if (nextError != null && (endOfRange < 0 || nStart - pLength + nextError.error.nErrorStart < endOfRange)) { if (nextError.error.aRuleIdentifier.equals(spellRuleId)) { wrongWord = docCache.getFlatParagraph(y).substring(nextError.error.nErrorStart, nextError.error.nErrorStart + nextError.error.nErrorLength); } if (debugMode) { MessageHandler.printToLogFile("CheckDialog: getNextError: endOfRange: " + endOfRange + "; ErrorStart(" + nStart + "/" + pLength + "/" + nextError.error.nErrorStart + "): " + (nStart - pLength + nextError.error.nErrorStart)); MessageHandler.printToLogFile("CheckDialog: getNextError: x: " + x + "; y: " + y); } setFlatViewCursor(nextError.error.nErrorStart, y, viewCursor); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: getNextError: FlatViewCursor set"); } return nextError; } else if (debugMode) { MessageHandler.printToLogFile("CheckDialog: getNextError: Next Error = " + (nextError == null ? "null" : nextError.error.nErrorStart) + ", endOfRange: " + endOfRange); MessageHandler.printToLogFile("x: " + x + "; y: " + y); } y++; x = 0; } if (endOfRange < 0) { if (y == docCache.size()) { y = 0; } while (y < lastPara) { checkProgress.setValue(docCache.size() + y - lastPara); nextError = getNextErrorInParagraph (0, y, currentDocument, docCursor); if (nextError != null) { if (nextError.error.aRuleIdentifier.equals(spellRuleId)) { wrongWord = docCache.getFlatParagraph(y).substring(nextError.error.nErrorStart, nextError.error.nErrorStart + nextError.error.nErrorLength); } setFlatViewCursor(nextError.error.nErrorStart, y, viewCursor); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: getNextError: y: " + y + "lastPara: " + lastPara + ", ErrorStart: " + nextError.error.nErrorStart + ", ErrorLength: " + nextError.error.nErrorLength); } return nextError; } y++; } endOfDokumentMessage = messages.getString("guiCheckComplete"); checkProgress.setValue(docCache.size()); } else { endOfDokumentMessage = messages.getString("guiSelectionCheckComplete"); checkProgress.setValue(endOfRange); } lastPara = -1; if (debugMode) { MessageHandler.printToLogFile("CheckDialog: getNextError: Error == null, y: " + y + "lastPara: " + lastPara); } return null; } /** * Actions of buttons */ @Override public void actionPerformed(ActionEvent action) { try { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: actionPerformed: Action: " + action.getActionCommand()); } if (action.getActionCommand().equals("close")) { closeDialog(); } else if (action.getActionCommand().equals("ignoreOnce")) { ignoreOnce(); } else if (action.getActionCommand().equals("ignoreAll")) { ignoreAll(); } else if (action.getActionCommand().equals("deactivateRule")) { deactivateRule(); } else if (action.getActionCommand().equals("change")) { changeText(); } else if (action.getActionCommand().equals("changeAll")) { changeAll(); } else if (action.getActionCommand().equals("undo")) { undo(); } else if (action.getActionCommand().equals("more")) { Tools.openURL(informationUrl); } else if (action.getActionCommand().equals("options")) { documents.runOptionsDialog(); } else if (action.getActionCommand().equals("help")) { MessageHandler.showMessage(messages.getString("loDialogHelpText")); } else { MessageHandler.showMessage("Action '" + action.getActionCommand() + "' not supported"); } } catch (Throwable e) { MessageHandler.showError(e); } } /** * closes the dialog */ public void closeDialog() throws Throwable { if (isRunning) { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: closeDialog: Close Spell And Grammar Check Dialog"); } undoList = null; documents.setLtDialog(null); documents.setLtDialogIsRunning(false); isRunning = false; gotoNextError(); } dialog.setVisible(false); } /** * remove a mark for spelling error in document * TODO: The function works very temporarily */ private void removeSpellingMark(int nFlat) throws Throwable { XParagraphCursor pCursor = viewCursor.getParagraphCursorUnderViewCursor(); pCursor.gotoStartOfParagraph(false); pCursor.goRight((short)error.nErrorStart, false); pCursor.goRight((short)error.nErrorLength, true); XMarkingAccess xMarkingAccess = UnoRuntime.queryInterface(XMarkingAccess.class, pCursor); if (xMarkingAccess == null) { MessageHandler.printToLogFile("CheckDialog: removeSpellingMark: xMarkingAccess == null"); } else { xMarkingAccess.invalidateMarkings(TextMarkupType.SPELLCHECK); } } /** * set the information to ignore just the match at the given position * @throws Throwable */ private void ignoreOnce() throws Throwable { x = error.nErrorStart; if (isSpellError && docType == DocumentType.WRITER) { removeSpellingMark(y); } currentDocument.setIgnoredMatch(x, y, error.aRuleIdentifier, true); addUndo(x, y, "ignoreOnce", error.aRuleIdentifier); gotoNextError(); } /** * ignore all performed: * spelling error: add word to temporary dictionary * grammatical error: deactivate rule * both actions are only for the current session * @throws Throwable */ private void ignoreAll() throws Throwable { if (isSpellError) { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: ignoreAll: Ignored word: " + wrongWord); } documents.getLtDictionary().addIgnoredWord(wrongWord); } else { documents.ignoreRule(error.aRuleIdentifier, locale); documents.initDocuments(); documents.resetDocument(); doInit = true; } addUndo(y, "ignoreAll", error.aRuleIdentifier); gotoNextError(); } /** * the rule is deactivated permanently (saved in the configuration file) * @throws Throwable */ private void deactivateRule() throws Throwable { if (!isSpellError) { documents.deactivateRule(error.aRuleIdentifier, OfficeTools.localeToString(locale), false); addUndo(y, "deactivateRule", error.aRuleIdentifier); doInit = true; } gotoNextError(); } /** * compares two strings from the beginning * returns the first different character */ private int getDifferenceFromBegin(String text1, String text2) { for (int i = 0; i < text1.length() && i < text2.length(); i++) { if (text1.charAt(i) != text2.charAt(i)) { return i; } } return (text1.length() < text2.length() ? text1.length() : text2.length()); } /** * compares two strings from the end * returns the first different character */ private int getDifferenceFromEnd(String text1, String text2) { for (int i = 1; i <= text1.length() && i <= text2.length(); i++) { if (text1.charAt(text1.length() - i) != text2.charAt(text2.length() - i)) { return text1.length() - i + 1; } } return (text1.length() < text2.length() ? 0 : text1.length() - text2.length()); } /** * change the text of the paragraph inside the document * use the difference between the original paragraph and the text inside the editor element * or if there is no difference replace the match by the selected suggestion * @throws Throwable */ private void changeText() throws Throwable { String word; String replace; String orgText; if (debugMode) { MessageHandler.printToLogFile("CheckDialog: changeText entered - docType: " + docType); } String dialogText = sentenceIncludeError.getText(); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: changeText: dialog text: " + dialogText); } if (docType != DocumentType.WRITER) { orgText = docCache.getFlatParagraph(y); if (!orgText.equals(dialogText)) { int firstChange = getDifferenceFromBegin(orgText, dialogText); int lastEqual = getDifferenceFromEnd(orgText, dialogText); if (lastEqual < firstChange) { lastEqual = firstChange; } int lastDialogEqual = dialogText.length() - orgText.length() + lastEqual; word = orgText.substring(firstChange, lastEqual); replace = dialogText.substring(firstChange, lastDialogEqual); changeTextOfParagraph(y, firstChange, lastEqual - firstChange, replace, currentDocument, viewCursor); addSingleChangeUndo(firstChange, y, word, replace); } else if (suggestions.getComponentCount() > 0) { word = orgText.substring(error.nErrorStart, error.nErrorStart + error.nErrorLength); replace = suggestions.getSelectedValue(); changeTextOfParagraph(y, error.nErrorStart, error.nErrorLength, replace, currentDocument, viewCursor); addSingleChangeUndo(error.nErrorStart, y, word, replace); } else { MessageHandler.printToLogFile("CheckDialog: changeText: No text selected to change"); return; } } else { orgText = docCache.getFlatParagraph(y); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: changeText: original text: " + orgText); } if (!orgText.equals(dialogText)) { int firstChange = getDifferenceFromBegin(orgText, dialogText); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: changeText: firstChange: " + firstChange); } int lastEqual = getDifferenceFromEnd(orgText, dialogText); if (lastEqual < firstChange) { lastEqual = firstChange; } if (debugMode) { MessageHandler.printToLogFile("CheckDialog: changeText: lastEqual: " + lastEqual); } int lastDialogEqual = dialogText.length() - orgText.length() + lastEqual; if (debugMode) { MessageHandler.printToLogFile("CheckDialog: changeText: lastDialogEqual: " + lastDialogEqual); } if (firstChange < lastEqual) { word = orgText.substring(firstChange, lastEqual); } else { word =""; } if (firstChange < lastDialogEqual) { replace = dialogText.substring(firstChange, lastDialogEqual); } else { replace =""; } if (debugMode) { MessageHandler.printToLogFile("CheckDialog: changeText: word: '" + word + "', replace: '" + replace + "'"); } changeTextOfParagraph(y, firstChange, lastEqual - firstChange, replace, currentDocument, viewCursor); addSingleChangeUndo(firstChange, y, word, replace); } else if (suggestions.getComponentCount() > 0) { word = orgText.substring(error.nErrorStart, error.nErrorStart + error.nErrorLength); replace = suggestions.getSelectedValue(); changeTextOfParagraph(y, error.nErrorStart, error.nErrorLength, replace, currentDocument, viewCursor); addSingleChangeUndo(error.nErrorStart, y, word, replace); } else { MessageHandler.printToLogFile("CheckDialog: changeText: No text selected to change"); return; } } if (debugMode) { MessageHandler.printToLogFile("CheckDialog: changeText: Org: " + word + "\nDia: " + replace); } gotoNextError(); } /** * Change all matched words of the document by the selected suggestion * @throws Throwable */ private void changeAll() throws Throwable { if (suggestions.getComponentCount() > 0) { String orgText = sentenceIncludeError.getText(); String word = orgText.substring(error.nErrorStart, error.nErrorStart + error.nErrorLength); String replace = suggestions.getSelectedValue(); XComponent xComponent = currentDocument.getXComponent(); DocumentCursorTools docCursor = new DocumentCursorTools(xComponent); Map<Integer, List<Integer>> orgParas = spellChecker.replaceAllWordsInText(word, replace, docCursor, currentDocument, viewCursor); if (orgParas != null) { addChangeUndo(error.nErrorStart, y, word, replace, orgParas); } gotoNextError(); } } /** * Add undo information * maxUndos changes are stored in the undo list */ private void addUndo(int y, String action, String ruleId) throws Throwable { addUndo(0, y, action, ruleId); } private void addUndo(int x, int y, String action, String ruleId) throws Throwable { addUndo(x, y, action, ruleId, null); } private void addUndo(int y, String action, String ruleId, String word) throws Throwable { addUndo(0, y, action, ruleId, word, null); } private void addUndo(int x, int y, String action, String ruleId, Map<Integer, List<Integer>> orgParas) throws Throwable { addUndo(x, y, action, ruleId, null, orgParas); } private void addUndo(int x, int y, String action, String ruleId, String word, Map<Integer, List<Integer>> orgParas) throws Throwable { if (undoList.size() >= maxUndos) { undoList.remove(0); } undoList.add(new UndoContainer(x, y, action, ruleId, word, orgParas)); } /** * add undo information for change function (general) */ private void addChangeUndo(int x, int y, String word, String replace, Map<Integer, List<Integer>> orgParas) throws Throwable { addUndo(x, y, "change", replace, word, orgParas); } /** * add undo information for a single change * @throws Throwable */ private void addSingleChangeUndo(int x, int y, String word, String replace) throws Throwable { Map<Integer, List<Integer>> paraMap = new HashMap<Integer, List<Integer>>(); List<Integer> xVals = new ArrayList<Integer>(); xVals.add(x); paraMap.put(y, xVals); addChangeUndo(x, y, word, replace, paraMap); } /** * add undo information for a language change * @throws Throwable */ private void addLanguageChangeUndo(int nFlat, int nStart, int nLen, String originalLanguage) throws Throwable { Map<Integer, List<Integer>> paraMap = new HashMap<Integer, List<Integer>>(); List<Integer> xVals = new ArrayList<Integer>(); xVals.add(nStart); xVals.add(nLen); paraMap.put(nFlat, xVals); addUndo(0, nFlat, "changeLanguage", originalLanguage, null, paraMap); } /** * undo the last change triggered by the LT check dialog */ private void undo() throws Throwable { if (undoList == null || undoList.isEmpty()) { return; } try { int nLastUndo = undoList.size() - 1; UndoContainer lastUndo = undoList.get(nLastUndo); String action = lastUndo.action; int xUndo = lastUndo.x; int yUndo = lastUndo.y; if (debugMode) { MessageHandler.printToLogFile("CheckDialog: Undo: Action: " + action); } if (action.equals("ignoreOnce")) { currentDocument.removeIgnoredMatch(xUndo, yUndo, lastUndo.ruleId, true); } else if (action.equals("ignoreAll")) { if (lastUndo.ruleId.equals(spellRuleId)) { if (debugMode) { MessageHandler.printToLogFile("CheckDialog: Undo: Ignored word removed: " + wrongWord); } documents.getLtDictionary().removeIgnoredWord(wrongWord); } else { Locale locale = docCache.getFlatParagraphLocale(yUndo); documents.removeDisabledRule(OfficeTools.localeToString(locale), lastUndo.ruleId); documents.initDocuments(); documents.resetDocument(); doInit = true; } } else if (action.equals("deactivateRule")) { currentDocument.removeResultCache(yUndo); Locale locale = docCache.getFlatParagraphLocale(yUndo); documents.deactivateRule(lastUndo.ruleId, OfficeTools.localeToString(locale), true); doInit = true; } else if (action.equals("activateRule")) { currentDocument.removeResultCache(yUndo); Locale locale = docCache.getFlatParagraphLocale(yUndo); documents.deactivateRule(lastUndo.ruleId, OfficeTools.localeToString(locale), false); doInit = true; } else if (action.equals("addToDictionary")) { documents.getLtDictionary().removeWordFromDictionary(lastUndo.ruleId, lastUndo.word, xContext); } else if (action.equals("changeLanguage")) { Locale locale = getLocaleFromLanguageName(lastUndo.ruleId); FlatParagraphTools flatPara = currentDocument.getFlatParagraphTools(); int nFlat = lastUndo.y; int nStart = lastUndo.orgParas.get(nFlat).get(0); int nLen = lastUndo.orgParas.get(nFlat).get(1); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: Undo: Change Language: Locale: " + locale.Language + "-" + locale.Country + ", nFlat = " + nFlat + ", nStart = " + nStart + ", nLen = " + nLen); } if (docType == DocumentType.IMPRESS) { OfficeDrawTools.setLanguageOfParagraph(nFlat, nStart, nLen, locale, currentDocument.getXComponent()); } else if (docType == DocumentType.CALC) { OfficeSpreadsheetTools.setLanguageOfSpreadsheet(locale, currentDocument.getXComponent()); } else { flatPara.setLanguageOfParagraph(nFlat, nStart, nLen, locale); } if (nLen == docCache.getFlatParagraph(nFlat).length()) { docCache.setFlatParagraphLocale(nFlat, locale); DocumentCache curDocCache = currentDocument.getDocumentCache(); if (curDocCache != null) { curDocCache.setFlatParagraphLocale(nFlat, locale); } } currentDocument.removeResultCache(nFlat); } else if (action.equals("change")) { Map<Integer, List<Integer>> paras = lastUndo.orgParas; short length = (short) lastUndo.ruleId.length(); for (int nFlat : paras.keySet()) { List<Integer> xStarts = paras.get(nFlat); TextParagraph n = docCache.getNumberOfTextParagraph(nFlat); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: Undo: Ignore change: nFlat = " + nFlat + ", n = (" + n.type + "," + n.number + "), x = " + xStarts.get(0)); } if (docType != DocumentType.WRITER) { for (int i = xStarts.size() - 1; i >= 0; i int xStart = xStarts.get(i); changeTextOfParagraph(nFlat, xStart, length, lastUndo.word, currentDocument, viewCursor); } } else { String para = docCache.getFlatParagraph(nFlat); for (int i = xStarts.size() - 1; i >= 0; i int xStart = xStarts.get(i); para = para.substring(0, xStart) + lastUndo.word + para.substring(xStart + length); changeTextOfParagraph(nFlat, xStart, length, lastUndo.word, currentDocument, viewCursor); } } currentDocument.removeResultCache(nFlat); } } else { MessageHandler.showMessage("Undo '" + action + "' not supported"); } undoList.remove(nLastUndo); setFlatViewCursor(xUndo, yUndo, viewCursor); if (debugMode) { MessageHandler.printToLogFile("CheckDialog: Undo: yUndo = " + yUndo + ", xUndo = " + xUndo + ", lastPara = " + lastPara); } gotoNextError(); } catch (Throwable e) { MessageHandler.showError(e); } } void setFlatViewCursor(int x, int y, ViewCursorTools viewCursor) throws Throwable { this.x = x; this.y = y; if (docType == DocumentType.WRITER) { TextParagraph para = docCache.getNumberOfTextParagraph(y); SpellAndGrammarCheckDialog.setTextViewCursor(x, para, viewCursor); } else if (docType == DocumentType.IMPRESS) { OfficeDrawTools.setCurrentPage(y, currentDocument.getXComponent()); if (OfficeDrawTools.isParagraphInNotesPage(y, currentDocument.getXComponent())) { OfficeTools.dispatchCmd(".uno:NotesMode", xContext); // Note: a delay interval is needed to put the dialog to front try { Thread.sleep(500); } catch (InterruptedException e) { MessageHandler.printException(e); } dialog.toFront(); } } else { OfficeSpreadsheetTools.setCurrentSheet(y, currentDocument.getXComponent()); } } } }
package lib.layout; import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.HtmlLink; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.recipes.PresetData; public class LayoutTest { @Rule public JenkinsRule r = new JenkinsRule(); @Issue("JENKINS-21254") @PresetData(PresetData.DataSet.NO_ANONYMOUS_READACCESS) @Test public void rejectedLinks() throws Exception { JenkinsRule.WebClient wc = r.createWebClient(); String prefix = r.contextPath + '/'; for (DomElement e : wc.goTo("login").getElementsByTagName("link")) { String href = ((HtmlLink) e).getHrefAttribute(); if (!href.startsWith(prefix)) { System.err.println("ignoring " + href); continue; } System.err.println("checking " + href); wc.goTo(href.substring(prefix.length()), null); } } }
package xal.tools.swing; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.LineBorder; import xal.tools.swing.wheelswitch.util.SetEvent; import xal.tools.swing.wheelswitch.util.SetListener; import xal.tools.swing.Wheelswitch; import com.cosylab.gui.components.demonstrator.AbstractDemoPanel; import com.cosylab.gui.components.util.IconHelper; /** * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. * * @author <a href="mailto:[email protected]">Gasper Pajor</a> * @version $id$ */ public class WheelswitchTest extends AbstractDemoPanel { String defaultText = "Wheelswitch displays a formatted numerical value with a set of numerical digits which can optionally be individually modified for precision setting of values.\n"+ "Click on any of the numerical digits inside the wheelswitch to modify them through the two-button switch on the right side of the component."; /** * Constructor for WheelSwitchDemoContent. */ public WheelswitchTest() { super("Wheelswitch"); setIcon(IconHelper.createIcon("Resources/icons/components/Wheelswitch16.gif")); getHelpTextArea().setText(defaultText); } /** * * @version @@VERSION@@ * @author Jernej Kamenik([email protected]) */ public class WheelSwitchDemoPanel extends JPanel { Wheelswitch wSwitch; JTextField txt1; JTextField txt2; JTextField txt3; JTextField txt4; JTextField txt5; JButton jb1; JButton jb2; JCheckBox tgb1, tgb2, tgb3; JPanel pan0; private class HelpAdapter extends MouseAdapter { String string; /** * @param newString String */ public HelpAdapter(String newString) { string = newString; } /** * @param e MouseEvent * @see java.awt.event.MouseListener#mouseEntered(MouseEvent) */ public void mouseEntered(MouseEvent e) { getHelpTextArea().setText(string); } /** * @param e MouseEvent * @see java.awt.event.MouseListener#mouseExited(MouseEvent) */ public void mouseExited(MouseEvent e) { getHelpTextArea().setText(defaultText); } } public WheelSwitchDemoPanel() { wSwitch = new Wheelswitch("+ wSwitch.setGraphMax(200); wSwitch.setGraphMin(-200); txt1 = new JTextField("+ txt2 = new JTextField("12.3456789",10); txt3 = new JTextField("unit",10); txt4 = new JTextField("200",10); txt5 = new JTextField("-200",10); jb1 = new JButton("Apply Settings"); jb2 = new JButton("Get Value"); tgb1 = new JCheckBox("Stretch"); tgb2 = new JCheckBox("Enhanced"); tgb3 = new JCheckBox("Editable"); txt1.addMouseListener(new HelpAdapter("The values in the wheelswitch can be display in numerous formats, controlled by the format string.\n To change the format alter this string and press the 'Apply' button.")); txt2.addMouseListener(new HelpAdapter("Enter the value to be set to the wheelswitch here nad press the 'Apply' button.")); txt3.addMouseListener(new HelpAdapter("Units can be also displayed next to the value in the wheelswitch. To change the unit display enter the new text here and press the 'Apply' button.")); txt4.addMouseListener(new HelpAdapter("Values in the wheelswitch can be bounded by setting maximum and minimum values. To change these, enter new values here press the 'Apply' button")); txt5.addMouseListener(new HelpAdapter("Values in the wheelswitch can be bounded by setting maximum and minimum values. To change these, enter new values here press the 'Apply' button")); jb1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { wSwitch.setValue(Double.parseDouble(txt2.getText())); wSwitch.setFormat(txt1.getText()); wSwitch.setUnit(txt3.getText()); wSwitch.setGraphMax(Double.parseDouble(txt4.getText())); wSwitch.setGraphMin(Double.parseDouble(txt5.getText())); } }); jb1.addMouseListener(new HelpAdapter("Press the 'Apply' button to apply settings in the textfields to the wheelswitch.")); jb2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { txt2.setText(String.valueOf(wSwitch.getValue())); } }); jb2.addMouseListener(new HelpAdapter("Press the 'Get Value' button to read the value in the wheelswitch and display it in the 'Value' textfield.")); wSwitch.addSetListener(new SetListener() { public void setPerformed(SetEvent e) { txt2.setText(String.valueOf(e.getDoubleValue())); } }); // pan0 = new JPanel(); tgb1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tgb1.isSelected()) wSwitch.getParent().setLayout(new GridLayout(1,1)); else wSwitch.getParent().setLayout(new FlowLayout()); wSwitch.getParent().doLayout(); wSwitch.getParent().validate(); repaint(); } }); tgb1.addMouseListener(new HelpAdapter("Check here to demonstrate wheelswitch resizing.")); tgb2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tgb2.isSelected()) wSwitch.setEnhanced(true); else wSwitch.setEnhanced(false); } }); tgb2.setSelected(true); tgb2.addMouseListener(new HelpAdapter("Check here to set the enhnced mode of the wheelswitch.")); tgb3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tgb3.isSelected()) wSwitch.setEditable(true); else wSwitch.setEditable(false); } }); tgb3.setSelected(true); tgb3.addMouseListener(new HelpAdapter("Check here to set the editable mode of the wheelswitch.")); // Composition setLayout(new GridBagLayout()); GridBagConstraints cons = new GridBagConstraints(0,0,1,1,0,0,GridBagConstraints.EAST,GridBagConstraints.NONE,new Insets(6,6,0,0),0,0); // Wheelswitch Panel JPanel panWs = new JPanel(); panWs.setBorder(new LineBorder(Color.GRAY)); panWs.add(wSwitch); // 1st part of conf panel JPanel pan0 = new JPanel(); pan0.setLayout(new GridBagLayout()); pan0.add(new JLabel("Format: "), cons); cons.gridy = cons.gridy +1; pan0.add(new JLabel("Value: "), cons); cons.gridy = cons.gridy +1; pan0.add(new JLabel("Unit: "), cons); cons.gridy=0; cons.gridx=1; pan0.add(txt1, cons); cons.gridy = cons.gridy +1; pan0.add(txt2, cons); cons.gridy = cons.gridy +1; pan0.add(txt3, cons); // 2nd part of conf panel JPanel pan1 = new JPanel(); pan1.setLayout(new GridBagLayout()); cons.gridx=0; cons.gridy=0; pan1.add(new JLabel("Maximum: "), cons); cons.gridy = cons.gridy +1; pan1.add(new JLabel("Minimum: "), cons); cons.gridy=0; cons.gridx=1; pan1.add(txt4, cons); cons.gridy = cons.gridy +1; pan1.add(txt5, cons); // 3rd part of conf panel JPanel pan2 = new JPanel(); pan2.setLayout(new GridBagLayout()); cons.gridx=0; cons.gridy=0; cons.anchor= GridBagConstraints.CENTER; pan2.add(jb1, cons); cons.gridx = cons.gridx +1; pan2.add(jb2, cons); cons.anchor= GridBagConstraints.EAST; // 4th part of conf panel JPanel pan3 = new JPanel(); pan3.setLayout(new GridBagLayout()); cons.gridx=0; cons.gridy=0; cons.anchor= GridBagConstraints.CENTER; pan3.add(tgb1, cons); cons.gridx = cons.gridx +1; pan3.add(tgb2, cons); cons.gridx = cons.gridx +1; pan3.add(tgb3, cons); // Conf / Control panel JPanel panControl = new JPanel(); panControl.setLayout(new GridBagLayout()); cons.gridx=0; cons.gridy=0; panControl.add(pan0, cons); cons.gridx=cons.gridx+1; panControl.add(pan1, cons); cons.gridx=0; cons.gridy=cons.gridy+1; cons.gridwidth =2; panControl.add(pan2, cons); cons.gridy=cons.gridy+1; panControl.add(pan3, cons); // adding to this cons.insets.left=0; cons.anchor=GridBagConstraints.CENTER; cons.gridwidth=1; cons.gridx=0; cons.gridy=0; cons.fill=GridBagConstraints.BOTH; cons.weightx=1; cons.weighty=1; add(panWs,cons ); cons.gridy=cons.gridy+1; JPanel divider = new JPanel(); divider.setPreferredSize(new Dimension(1,20)); add(divider, cons); cons.weighty=0; cons.gridy=cons.gridy+1; add(panControl, cons); cons.weighty=1; cons.gridy=cons.gridy+1; JPanel divider2 = new JPanel(); divider2.setPreferredSize(new Dimension(1,20)); add(divider2, cons); } } /** * @return JComponent * @see AbstractDemoPanel#getContentPanel() */ public JComponent initializeContentPanel() { return new WheelSwitchDemoPanel(); } /** * @return boolean * @see com.cosylab.util.Suspendable#isSuspended() */ public boolean isSuspended() { return false; } /** * @param suspended boolean * @see com.cosylab.util.Suspendable#setSuspended(boolean) */ public void setSuspended(boolean suspended) { } }
package org.terasology.codecity.world.generator; import java.io.IOException; import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import org.terasology.codecity.world.map.CodeMap; import org.terasology.codecity.world.map.CodeMapFactory; import org.terasology.codecity.world.map.DrawableCode; import org.terasology.codecity.world.structure.CodeClass; import org.terasology.codecity.world.structure.CodePackage; import org.terasology.codecity.world.structure.CodeRepresentation; import org.terasology.codecity.world.structure.scale.CodeScale; import org.terasology.codecity.world.structure.scale.SquareRootCodeScale; import org.terasology.engine.SimpleUri; import org.terasology.registry.CoreRegistry; import org.terasology.world.generation.BaseFacetedWorldGenerator; import org.terasology.world.generation.WorldBuilder; import org.terasology.world.generator.RegisterWorldGenerator; /** * Generate a new world using information provided by JEdit */ @RegisterWorldGenerator(id = "codecity", displayName = "CodeCity", description = "Generates the world using a CodeCity structure") public class CodeCityWorldGenerator extends BaseFacetedWorldGenerator { private final CodeScale cScale = new SquareRootCodeScale(); public CodeCityWorldGenerator(SimpleUri uri) { super(uri); } @Override public void initialize() { CodeRepresentation code = loadCodeRepresentationDefault(); //CodeRepresentation code = loadCodeRepresentationFromSocket(); CodeMap codeMap = generateCodeMap(code); CoreRegistry.put(CodeMap.class, codeMap); super.initialize(); } @Override protected WorldBuilder createWorld(long seed) { return new WorldBuilder(seed) .addProvider(new CodeCityGroundProvider()) .addProvider(new CodeCityBuildingProvider()) .addRasterizer(new CodeCityGroundRasterizer()) .addRasterizer(new CodeCityBuildingRasterizer()) .setSeaLevel(0); } /** * Load the Code Representation object from a socket connection * @return The loaded Code Representation */ private CodeRepresentation loadCodeRepresentationFromSocket() { int portNumber = 25778; ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(portNumber); return getCodeRepresentation(serverSocket); } catch (IOException | ClassNotFoundException e) { return new CodePackage("", ""); } finally { try { if (serverSocket != null) { serverSocket.close(); } } catch (IOException e) { } } } /** * Get the Code Representation from the given ServerSocket * @param serverSocket Socket from where the client will be connected * @return The loaded Code Representation */ private CodeRepresentation getCodeRepresentation(ServerSocket serverSocket) throws IOException, ClassNotFoundException { Socket clientSocket = serverSocket.accept(); ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream()); return (CodeRepresentation)input.readObject(); } /** * Insert into the CodeRegistry the DrawableCode, gen * @param code */ private CodeMap generateCodeMap(CodeRepresentation code) { List<DrawableCode> list = new ArrayList<DrawableCode>(); list.add(code.getDrawableCode()); CodeMapFactory factory = new CodeMapFactory(cScale); return factory.generateMap(list); } /** * Load the default code representation */ private CodeRepresentation loadCodeRepresentationDefault() { CodePackage facet = new CodePackage("facet", ""); CodePackage generator = new CodePackage("generator", ""); CodePackage map = new CodePackage("map", ""); CodePackage structure = new CodePackage("structure", ""); CodePackage scale = new CodePackage("scale", ""); CodePackage terasology = new CodePackage("terasology", ""); CodeClass fac = new CodeClass("CodeCityFacet", 1, 18, ""); facet.addCodeContent(fac); CodeClass bProv = new CodeClass("", 3, 122, ""); CodeClass bRast = new CodeClass("", 1, 54, ""); CodeClass gProv = new CodeClass("", 0, 37, ""); CodeClass gRast = new CodeClass("", 1, 34, ""); CodeClass wGen = new CodeClass("", 0, 24, ""); generator.addCodeContent(bProv); generator.addCodeContent(bRast); generator.addCodeContent(gProv); generator.addCodeContent(gRast); generator.addCodeContent(wGen); terasology.addCodeContent(generator); CodeClass cMap = new CodeClass("", 0, 83, ""); CodeClass cMapF = new CodeClass("", 1,101, ""); CodeClass cMapH = new CodeClass("", 3,147, ""); CodeClass cMapN = new CodeClass("", 0,57, ""); CodeClass cMapC = new CodeClass("", 0,36, ""); CodeClass cMapCC = new CodeClass("", 1,34, ""); CodeClass cMapCP = new CodeClass("", 1,43, ""); CodeClass cMapO = new CodeClass("", 4,67, ""); map.addCodeContent(cMap); map.addCodeContent(cMapF); map.addCodeContent(cMapH); map.addCodeContent(cMapN); map.addCodeContent(cMapC); map.addCodeContent(cMapCC); map.addCodeContent(cMapCP); map.addCodeContent(cMapO); terasology.addCodeContent(map); CodeClass cClas = new CodeClass("", 2, 45, ""); CodeClass cPac = new CodeClass("", 1,34, ""); CodeClass cRep = new CodeClass("", 0,17, ""); structure.addCodeContent(cClas); structure.addCodeContent(cPac); structure.addCodeContent(cRep); terasology.addCodeContent(structure); CodeClass cSca = new CodeClass("", 0,28, ""); CodeClass cLin = new CodeClass("", 0,16, ""); CodeClass cSqu = new CodeClass("", 0,21, ""); scale.addCodeContent(cSca); scale.addCodeContent(cLin); scale.addCodeContent(cSqu); structure.addCodeContent(scale); return terasology; } }
package org.activiti.cycle.impl.connector; import java.io.IOException; import java.util.Map; import java.util.logging.Level; import org.activiti.cycle.RepositoryException; import org.activiti.cycle.impl.conf.PasswordEnabledRepositoryConnectorConfiguration; import org.activiti.cycle.impl.connector.util.RestClientLogHelper; import org.restlet.Client; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.representation.Representation; public abstract class AbstractRestClientConnector<T extends PasswordEnabledRepositoryConnectorConfiguration> extends AbstractRepositoryConnector<T> { protected Map<String, Object> properties; protected transient Client restletClient; protected Context context; public AbstractRestClientConnector(T configuration) { super(configuration); } public Client initClient() { // TODO: Check timeout on client and re-create it if (restletClient == null) { // TODO: check for additional options // Create and initialize HTTP client for HTTP REST API calls context.getParameters().set("maxConnectionsPerHost", "20"); restletClient = new Client(context, Protocol.HTTP); } return restletClient; } public Response sendRequest(Request request) throws IOException { injectSecurityMechanism(request); if (log.isLoggable(Level.FINE)) { RestClientLogHelper.logHttpRequest(log, Level.FINE, request); } Client client = initClient(); Response response = client.handle(request); if (log.isLoggable(Level.FINE)) { RestClientLogHelper.logHttpResponse(log, Level.FINE, response); } if (response.getStatus().isSuccess()) { return response; } throw new RepositoryException("Encountered error while retrieving http response (HttpStatus: " + response.getStatus() + ", Body: " + response.getEntity().getText() + ")"); } /** * Overwrite this method to add required security mechanisms to request. * For example: request.setChallengeResponse(new ChallengeResponse(ChallengeScheme.HTTP_BASIC, getConfiguration().getUser(), getConfiguration().getPassword())); * @param request * @return modified request enhanced with security data */ protected abstract Request injectSecurityMechanism(Request request); private Request createRequest(Reference reference, Representation representation) { if (reference != null) { Request request = new Request(); request.setResourceRef(reference); if (representation != null) { request.setEntity(representation); } return request; } throw new RepositoryException("Reference object is null!"); } private Request createJsonRequest(Reference reference, Representation representation) { Request jsonRequest = createRequest(reference, representation); jsonRequest.getClientInfo().getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.APPLICATION_JSON)); return jsonRequest; } private Request createXmlRequest(Reference reference, Representation representation) { Request xmlRequest = createRequest(reference, representation); xmlRequest.getClientInfo().getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.APPLICATION_XML)); return xmlRequest; } public Response getJson(Reference reference, Representation representation) throws IOException { Request getRequest = createJsonRequest(reference, representation); getRequest.setMethod(Method.GET); return sendRequest(getRequest); } public Response postJson(Reference reference, Representation representation) throws IOException { Request postRequest = createJsonRequest(reference, representation); postRequest.setMethod(Method.POST); return sendRequest(postRequest); } public Response putJson(Reference reference, Representation representation) throws IOException { Request putRequest = createJsonRequest(reference, representation); putRequest.setMethod(Method.PUT); return sendRequest(putRequest); } public Response deleteJson(Reference reference, Representation representation) throws IOException { Request deleteRequest = createJsonRequest(reference, representation); deleteRequest.setMethod(Method.DELETE); return sendRequest(deleteRequest); } public Response getXml(Reference reference, Representation representation) throws IOException { Request getRequest = createXmlRequest(reference, representation); getRequest.setMethod(Method.GET); return sendRequest(getRequest); } public Response postXml(Reference reference, Representation representation) throws IOException { Request postRequest = createXmlRequest(reference, representation); postRequest.setMethod(Method.POST); return sendRequest(postRequest); } public Response putXml(Reference reference, Representation representation) throws IOException { Request putRequest = createXmlRequest(reference, representation); putRequest.setMethod(Method.PUT); return sendRequest(putRequest); } public Response deleteXml(Reference reference, Representation representation) throws IOException { Request deleteRequest = createXmlRequest(reference, representation); deleteRequest.setMethod(Method.DELETE); return sendRequest(deleteRequest); } }
package org.navalplanner.web.orders; import static org.navalplanner.web.I18nHelper._; import java.math.BigDecimal; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.joda.time.LocalDate; import org.navalplanner.business.advance.bootstrap.PredefinedAdvancedTypes; import org.navalplanner.business.advance.entities.AdvanceAssignment; import org.navalplanner.business.advance.entities.AdvanceMeasurement; import org.navalplanner.business.advance.entities.AdvanceType; import org.navalplanner.business.advance.entities.DirectAdvanceAssignment; import org.navalplanner.business.advance.entities.IndirectAdvanceAssignment; import org.navalplanner.business.advance.exceptions.DuplicateAdvanceAssignmentForOrderElementException; import org.navalplanner.business.advance.exceptions.DuplicateValueTrueReportGlobalAdvanceException; import org.navalplanner.business.common.exceptions.InstanceNotFoundException; import org.navalplanner.business.orders.entities.OrderElement; import org.navalplanner.web.common.IMessagesForUser; import org.navalplanner.web.common.Level; import org.navalplanner.web.common.MessagesForUser; import org.navalplanner.web.common.Util; import org.zkoss.util.InvalidValueException; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.WrongValueException; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Button; import org.zkoss.zul.Chart; import org.zkoss.zul.Checkbox; import org.zkoss.zul.Combobox; import org.zkoss.zul.Comboitem; import org.zkoss.zul.Constraint; import org.zkoss.zul.Datebox; import org.zkoss.zul.Decimalbox; import org.zkoss.zul.Hbox; import org.zkoss.zul.Label; import org.zkoss.zul.Listbox; import org.zkoss.zul.Listcell; import org.zkoss.zul.Listitem; import org.zkoss.zul.ListitemRenderer; import org.zkoss.zul.Radio; import org.zkoss.zul.Tabbox; import org.zkoss.zul.XYModel; /** * Controller for show the advances of the selected order element<br /> * @author Susana Montes Pedreria <[email protected]> */ public class ManageOrderElementAdvancesController extends GenericForwardComposer { private static final Log LOG = LogFactory .getLog(ManageOrderElementAdvancesController.class); private IMessagesForUser messagesForUser; private int indexSelectedItem = -1; private IManageOrderElementAdvancesModel manageOrderElementAdvancesModel; private AdvanceTypeListRenderer advanceTypeListRenderer = new AdvanceTypeListRenderer(); private AdvanceMeasurementRenderer advanceMeasurementRenderer = new AdvanceMeasurementRenderer(); private Set<AdvanceAssignment> selectedAdvances = new HashSet<AdvanceAssignment>(); private Component messagesContainerAdvances; private Tabbox tabboxOrderElement; @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); comp.setVariable("manageOrderElementAdvancesController", this, true); messagesForUser = new MessagesForUser(messagesContainerAdvances); } public List<AdvanceMeasurement> getAdvanceMeasurements() { return manageOrderElementAdvancesModel.getAdvanceMeasurements(); } public List<AdvanceAssignment> getAdvanceAssignments() { return manageOrderElementAdvancesModel.getAdvanceAssignments(); } public boolean close() { return save(); } private void validate() throws InvalidValueException { if (!validateDataForm()) { throw new InvalidValueException(_("values are not valid, the values must not be null")); } if (!validateReportGlobalAdvance()) { throw new InvalidValueException(_("spread values are not valid, at least one value should be true")); } } public boolean save() { try { validate(); manageOrderElementAdvancesModel.confirmSave(); return true; } catch (DuplicateAdvanceAssignmentForOrderElementException e) { messagesForUser.showMessage(Level.ERROR, _("cannot include an Advance of the same Advance type twice")); } catch (DuplicateValueTrueReportGlobalAdvanceException e) { messagesForUser.showMessage( Level.ERROR, _("spread values are not valid, at least one value should be true")); } catch (InvalidValueException e) { messagesForUser.showMessage(Level.ERROR, e.getMessage()); } catch (InstanceNotFoundException e) { messagesForUser.showMessage( Level.ERROR, e.getMessage()); LOG.error(_("Couldn't find element: {0}", e.getKey()), e); } increaseScreenHeight(); return false; } private IOrderElementModel orderElementModel; public void openWindow(IOrderElementModel orderElementModel) { setOrderElementModel(orderElementModel); manageOrderElementAdvancesModel.initEdit(getOrderElement()); selectedAdvances.clear(); createAndLoadBindings(); selectSpreadAdvanceLine(); } public void openWindow(OrderElement orderElement) { manageOrderElementAdvancesModel.initEdit(orderElement); selectedAdvances.clear(); createAndLoadBindings(); selectSpreadAdvanceLine(); } public void createAndLoadBindings() { Util.createBindingsFor(self); Util.reloadBindings(self); } public void setOrderElementModel(IOrderElementModel orderElementModel) { this.orderElementModel = orderElementModel; } private OrderElement getOrderElement() { return orderElementModel.getOrderElement(); } private void increaseScreenHeight() { if ((tabboxOrderElement != null) && (!tabboxOrderElement.getHeight().equals("680px"))) { tabboxOrderElement.setHeight("680px"); tabboxOrderElement.invalidate(); } } private void resetScreenHeight() { if ((tabboxOrderElement != null) && (!tabboxOrderElement.getHeight().equals("620px"))) { tabboxOrderElement.setHeight("620px"); tabboxOrderElement.invalidate(); } } private void reloadAdvances() { Util.reloadBindings(self); resetScreenHeight(); setSelectedAdvanceLine(); } private void setSelectedAdvanceLine() { if ((indexSelectedItem > -1) && (indexSelectedItem < editAdvances.getItemCount())) { editAdvances.setSelectedItem(editAdvances .getItemAtIndex(indexSelectedItem)); editAdvances.invalidate(); } } private Listbox editAdvances; public void selectAdvanceLine(Listitem selectedItem) { /* * validate the previous advance line before changing the selected * advance. */ setSelectedAdvanceLine(); validateListAdvanceMeasurement(); /* * preparation to select the advance line. Set the current selected * index that will show when the grid reloads. */ AdvanceAssignment advance = (AdvanceAssignment) selectedItem.getValue(); indexSelectedItem = editAdvances.getIndexOfItem(selectedItem); prepareEditAdvanceMeasurements(advance); reloadAdvances(); } public void selectAdvanceLine(int index) { indexSelectedItem = index; if ((indexSelectedItem >= 0) && (indexSelectedItem < getAdvanceAssignments().size())) { prepareEditAdvanceMeasurements(getAdvanceAssignments().get( indexSelectedItem)); } reloadAdvances(); } public void selectSpreadAdvanceLine() { AdvanceAssignment advance = manageOrderElementAdvancesModel .getSpreadAdvance(); if (advance != null) { indexSelectedItem = getAdvanceAssignments().indexOf(advance); prepareEditAdvanceMeasurements(advance); } else { selectAdvanceLine(getAdvanceAssignments().size() - 1); } reloadAdvances(); } public void prepareEditAdvanceMeasurements(AdvanceAssignment advance) { if (advance != null && advance.getAdvanceType() != null) { manageOrderElementAdvancesModel .prepareEditAdvanceMeasurements(advance); } } public void goToCreateLineAdvanceAssignment() { validateListAdvanceMeasurement(); boolean fineResult = manageOrderElementAdvancesModel .addNewLineAdvaceAssignment(); if (fineResult) { selectAdvanceLine(getAdvanceAssignments().size() - 1); } else { showMessageNotAddMoreAdvances(); } } public void goToCreateLineAdvanceMeasurement() { AdvanceMeasurement newMeasure = manageOrderElementAdvancesModel .addNewLineAdvaceMeasurement(); if ((newMeasure != null) && (manageOrderElementAdvancesModel .hasConsolidatedAdvances(newMeasure))) { newMeasure.setDate(null); } reloadAdvances(); } public void goToRemoveLineAdvanceAssignment(Listitem listItem) { AdvanceAssignment advance = (AdvanceAssignment) listItem.getValue(); if ((editAdvances.getItemCount() > 1) && (advance.getReportGlobalAdvance())) { showMessageDeleteSpread(); } else if (manageOrderElementAdvancesModel .hasConsolidatedAdvances(advance)) { showMessagesConsolidation(1); } else { manageOrderElementAdvancesModel .removeLineAdvanceAssignment(advance); if (indexSelectedItem == editAdvances.getIndexOfItem(listItem)) { selectSpreadAdvanceLine(); } else { if (indexSelectedItem > editAdvances.getIndexOfItem(listItem)) { selectAdvanceLine(indexSelectedItem - 1); } else { prepareEditAdvanceMeasurements(getAdvanceAssignments().get( indexSelectedItem)); reloadAdvances(); } } } } private Listbox editAdvancesMeasurement; public void goToRemoveLineAdvanceMeasurement(Listitem listItem) { AdvanceMeasurement advance = (AdvanceMeasurement) listItem.getValue(); if (manageOrderElementAdvancesModel.canRemoveOrChange(advance)) { manageOrderElementAdvancesModel .removeLineAdvanceMeasurement(advance); reloadAdvances(); } else { showMessagesConsolidation(2); } } public String getInfoAdvance() { String infoAdvanceAssignment = manageOrderElementAdvancesModel .getInfoAdvanceAssignment(); if (infoAdvanceAssignment.isEmpty()) { return _("Advance measurements"); } return _("Advance measurements: ") + infoAdvanceAssignment; } public boolean isReadOnlyAdvanceMeasurements() { return manageOrderElementAdvancesModel.isReadOnlyAdvanceMeasurements(); } public AdvanceTypeListRenderer getAdvancesRenderer() { return advanceTypeListRenderer; } public void updatesValue(final Decimalbox item){ this.setPercentage(); this.setCurrentValue(); } public class AdvanceTypeListRenderer implements ListitemRenderer { @Override public void render(Listitem listItem, Object data) throws Exception { final AdvanceAssignment advance = (AdvanceAssignment) data; listItem.setValue(advance); listItem.setDraggable("true"); listItem.setDroppable("true"); boolean isQualityForm = false; if (advance.getAdvanceType() != null) { isQualityForm = manageOrderElementAdvancesModel .isQualityForm(advance); } if ((advance instanceof DirectAdvanceAssignment) && ((DirectAdvanceAssignment) advance) .getAdvanceMeasurements().isEmpty() && !isQualityForm) { appendComboboxAdvanceType(listItem); } else { appendLabelAdvanceType(listItem); } appendDecimalBoxMaxValue(listItem, isQualityForm); appendDecimalBoxValue(listItem); appendLabelPercentage(listItem); appendDateBoxDate(listItem); appendRadioSpread(listItem); appendCalculatedCheckbox(listItem); appendChartCheckbox(listItem); appendOperations(listItem); } } private void appendComboboxAdvanceType(final Listitem listItem) { final DirectAdvanceAssignment advance = (DirectAdvanceAssignment) listItem .getValue(); final Combobox comboAdvanceTypes = new Combobox(); final List<AdvanceType> listAdvanceType = manageOrderElementAdvancesModel .getPossibleAdvanceTypes(advance); for(AdvanceType advanceType : listAdvanceType){ if (!advanceType.getUnitName().equals( PredefinedAdvancedTypes.CHILDREN.getTypeName()) && !advanceType.isQualityForm()) { Comboitem comboItem = new Comboitem(); comboItem.setValue(advanceType); comboItem.setLabel(advanceType.getUnitName()); comboItem.setParent(comboAdvanceTypes); if ((advance.getAdvanceType() != null) && (advance.getAdvanceType().getId().equals(advanceType .getId()))) { comboAdvanceTypes.setSelectedItem(comboItem); } } } comboAdvanceTypes.addEventListener(Events.ON_SELECT, new EventListener() { @Override public void onEvent(Event event) throws Exception { setMaxValue(listItem, comboAdvanceTypes); cleanFields(advance); setPercentage(); reloadAdvances(); } }); Util.bind(comboAdvanceTypes, new Util.Getter<Comboitem>() { @Override public Comboitem get(){ return comboAdvanceTypes.getSelectedItem(); } }, new Util.Setter<Comboitem>() { @Override public void set(Comboitem comboItem) { if(((comboItem!=null))&&(comboItem.getValue() != null)&& (comboItem.getValue() instanceof AdvanceType)){ AdvanceType advanceType = (AdvanceType)comboItem.getValue(); advance.setAdvanceType(advanceType); advance.setMaxValue(manageOrderElementAdvancesModel .getMaxValue(advanceType)); } } }); Listcell listCell = new Listcell(); listCell.appendChild(comboAdvanceTypes); listItem.appendChild(listCell); } private void appendLabelAdvanceType(final Listitem listItem){ final AdvanceAssignment advance = (AdvanceAssignment) listItem.getValue(); Label unitName = new Label(advance.getAdvanceType().getUnitName()); Listcell listCell = new Listcell(); listCell.appendChild(unitName); listItem.appendChild(listCell); } private void appendDecimalBoxMaxValue(final Listitem listItem, boolean isQualityForm) { final AdvanceAssignment advanceAssignment = (AdvanceAssignment) listItem .getValue(); Decimalbox maxValue = new Decimalbox(); maxValue.setScale(2); final DirectAdvanceAssignment directAdvanceAssignment; if ((advanceAssignment instanceof IndirectAdvanceAssignment) || isQualityForm || (advanceAssignment.getAdvanceType() != null && advanceAssignment .getAdvanceType().getPercentage())) { maxValue.setDisabled(true); } if (advanceAssignment instanceof IndirectAdvanceAssignment) { directAdvanceAssignment = manageOrderElementAdvancesModel .calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) advanceAssignment); } else { directAdvanceAssignment = (DirectAdvanceAssignment) advanceAssignment; } Util.bind(maxValue, new Util.Getter<BigDecimal>() { @Override public BigDecimal get() { return directAdvanceAssignment.getMaxValue(); } }, new Util.Setter<BigDecimal>() { @Override public void set(BigDecimal value) { if (!manageOrderElementAdvancesModel .hasConsolidatedAdvances(advanceAssignment)) { directAdvanceAssignment.setMaxValue(value); } } }); maxValue.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) throws Exception { if (manageOrderElementAdvancesModel .hasConsolidatedAdvances(advanceAssignment)) { showMessagesConsolidation(1); } else { setPercentage(); reloadAdvances(); } } }); Listcell listCell = new Listcell(); listCell.appendChild(maxValue); listItem.appendChild(listCell); maxValue.setConstraint(checkMaxValue()); } private void appendDecimalBoxValue(final Listitem listItem){ final AdvanceAssignment advanceAssignment = (AdvanceAssignment) listItem .getValue(); Decimalbox value = new Decimalbox(); value.setScale(2); value.setDisabled(true); DirectAdvanceAssignment directAdvanceAssignment; if (advanceAssignment instanceof IndirectAdvanceAssignment) { directAdvanceAssignment = manageOrderElementAdvancesModel .calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) advanceAssignment); } else { directAdvanceAssignment = (DirectAdvanceAssignment) advanceAssignment; } final AdvanceMeasurement advanceMeasurement = this.manageOrderElementAdvancesModel .getLastAdvanceMeasurement(directAdvanceAssignment); if (advanceMeasurement != null) { Util.bind(value, new Util.Getter<BigDecimal>() { @Override public BigDecimal get() { return advanceMeasurement.getValue(); } }); } Listcell listCell = new Listcell(); listCell.appendChild(value); listItem.appendChild(listCell); } private void appendLabelPercentage(final Listitem listItem){ final AdvanceAssignment advanceAssignment = (AdvanceAssignment) listItem .getValue(); Label percentage = new Label(); DirectAdvanceAssignment directAdvanceAssignment; if (advanceAssignment instanceof IndirectAdvanceAssignment) { directAdvanceAssignment = manageOrderElementAdvancesModel .calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) advanceAssignment); } else { directAdvanceAssignment = (DirectAdvanceAssignment) advanceAssignment; } final AdvanceMeasurement advanceMeasurement = this.manageOrderElementAdvancesModel .getLastAdvanceMeasurement(directAdvanceAssignment); if (advanceMeasurement != null) { percentage .setValue(this.manageOrderElementAdvancesModel .getPercentageAdvanceMeasurement(advanceMeasurement) .toString() + " %"); } Listcell listCell = new Listcell(); listCell.appendChild(percentage); listItem.appendChild(listCell); } private void appendDateBoxDate(final Listitem listItem){ final AdvanceAssignment advanceAssignment = (AdvanceAssignment) listItem .getValue(); Datebox date = new Datebox(); date.setDisabled(true); DirectAdvanceAssignment directAdvanceAssignment; if (advanceAssignment instanceof IndirectAdvanceAssignment) { directAdvanceAssignment = manageOrderElementAdvancesModel .calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) advanceAssignment); } else { directAdvanceAssignment = (DirectAdvanceAssignment) advanceAssignment; } final AdvanceMeasurement advanceMeasurement = this.manageOrderElementAdvancesModel .getLastAdvanceMeasurement(directAdvanceAssignment); if (advanceMeasurement != null) { Util.bind(date, new Util.Getter<Date>() { @Override public Date get() { if (advanceMeasurement.getDate() == null) { return null; } return advanceMeasurement.getDate() .toDateTimeAtStartOfDay().toDate(); } }); } Listcell listCell = new Listcell(); listCell.appendChild(date); listItem.appendChild(listCell); } private void appendRadioSpread(final Listitem listItem){ final AdvanceAssignment advanceAssignment = (AdvanceAssignment) listItem .getValue(); final Radio reportGlobalAdvance = Util.bind(new Radio(), new Util.Getter<Boolean>() { @Override public Boolean get() { return advanceAssignment.getReportGlobalAdvance(); } }, new Util.Setter<Boolean>() { @Override public void set(Boolean value) { advanceAssignment.setReportGlobalAdvance(value); setReportGlobalAdvance(listItem); } }); Listcell listCell = new Listcell(); listCell.appendChild(reportGlobalAdvance); listItem.appendChild(listCell); if (((AdvanceAssignment) listItem.getValue()).getReportGlobalAdvance()) { reportGlobalAdvance.getRadiogroup().setSelectedItem( reportGlobalAdvance); reportGlobalAdvance.getRadiogroup().invalidate(); } } private void appendCalculatedCheckbox(final Listitem listItem){ final AdvanceAssignment advance = (AdvanceAssignment) listItem.getValue(); Checkbox calculated = new Checkbox(); boolean isCalculated = advance instanceof IndirectAdvanceAssignment; calculated.setChecked(isCalculated); calculated.setDisabled(true); Listcell listCell = new Listcell(); listCell.appendChild(calculated); listItem.appendChild(listCell); } private void appendChartCheckbox(final Listitem listItem) { final AdvanceAssignment advance = (AdvanceAssignment) listItem .getValue(); final Checkbox chartCheckbox = new Checkbox(); chartCheckbox.setChecked(selectedAdvances.contains(advance)); chartCheckbox.addEventListener(Events.ON_CHECK, new EventListener() { @Override public void onEvent(Event event) throws Exception { if (chartCheckbox.isChecked()) { selectedAdvances.add(advance); } else { selectedAdvances.remove(advance); } reloadAdvances(); } }); Listcell listCell = new Listcell(); listCell.appendChild(chartCheckbox); listItem.appendChild(listCell); } private void appendOperations(final Listitem listItem) { Hbox hbox = new Hbox(); appendAddMeasurement(hbox, listItem); appendRemoveButton(hbox, listItem); Listcell listCell = new Listcell(); listCell.appendChild(hbox); listItem.appendChild(listCell); } private void appendAddMeasurement(final Hbox hbox, final Listitem listItem) { final AdvanceAssignment advance = (AdvanceAssignment) listItem .getValue(); final Button addMeasurementButton = createAddMeasurementButton(); addMeasurementButton.addEventListener(Events.ON_CLICK, new EventListener() { @Override public void onEvent(Event event) throws Exception { if (!listItem.equals(editAdvances.getSelectedItem())) { selectAdvanceLine(listItem); } goToCreateLineAdvanceMeasurement(); } }); if ((advance.getAdvanceType() != null) && (advance.getAdvanceType().isQualityForm())) { addMeasurementButton.setDisabled(true); addMeasurementButton .setTooltiptext(_("Advances that are reported by quality forms can not be modified")); } else if (advance instanceof IndirectAdvanceAssignment) { addMeasurementButton.setDisabled(true); addMeasurementButton .setTooltiptext(_("Calculated advances can not be modified")); } hbox.appendChild(addMeasurementButton); } private void appendRemoveButton(final Hbox hbox, final Listitem listItem) { final AdvanceAssignment advance = (AdvanceAssignment) listItem .getValue(); final Button removeButton = createRemoveButton(); removeButton.addEventListener(Events.ON_CLICK, new EventListener() { @Override public void onEvent(Event event) throws Exception { goToRemoveLineAdvanceAssignment(listItem); } }); if ((advance.getAdvanceType() != null) && (advance.getAdvanceType().isQualityForm())) { removeButton.setDisabled(true); removeButton .setTooltiptext(_("Advances that are reported by quality forms can not be modified")); } else if (advance instanceof IndirectAdvanceAssignment) { removeButton.setDisabled(true); removeButton .setTooltiptext(_("Calculated advances can not be removed")); } hbox.appendChild(removeButton); } private void setMaxValue(final Listitem item,Combobox comboAdvanceTypes) { Listcell listCell = (Listcell)item.getChildren().get(1); Decimalbox miBox = ((Decimalbox) listCell.getFirstChild()); Comboitem selectedItem = comboAdvanceTypes.getSelectedItem(); if(selectedItem != null){ AdvanceType advanceType = ((AdvanceType) selectedItem.getValue()); if(advanceType != null){ DirectAdvanceAssignment advance = (DirectAdvanceAssignment) item .getValue(); advance.setMaxValue(manageOrderElementAdvancesModel .getMaxValue(advanceType)); miBox.setValue(manageOrderElementAdvancesModel .getMaxValue(advanceType)); miBox.invalidate(); } } } private Constraint checkMaxValue() { return new Constraint() { @Override public void validate(Component comp, Object value) throws WrongValueException { Listitem item = (Listitem) comp.getParent().getParent(); DirectAdvanceAssignment advance = (DirectAdvanceAssignment) item .getValue(); if (!manageOrderElementAdvancesModel .hasConsolidatedAdvances(advance)) { if (value == null) { ((Decimalbox) comp).setValue(advance.getMaxValue()); ((Decimalbox) comp).invalidate(); throw new WrongValueException(comp, _("The max value must be not empty")); } } } }; } private void setPercentage(){ if ((this.indexSelectedItem < editAdvances.getItemCount()) && (this.indexSelectedItem >= 0)) { Listitem selectedItem = editAdvances.getItemAtIndex(indexSelectedItem); AdvanceAssignment advanceAssignment = (AdvanceAssignment) selectedItem .getValue(); DirectAdvanceAssignment directAdvanceAssignment; if (advanceAssignment instanceof IndirectAdvanceAssignment) { directAdvanceAssignment = manageOrderElementAdvancesModel .calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) advanceAssignment); } else { directAdvanceAssignment = (DirectAdvanceAssignment) advanceAssignment; } final AdvanceMeasurement greatAdvanceMeasurement = this.manageOrderElementAdvancesModel .getLastAdvanceMeasurement(directAdvanceAssignment); if (greatAdvanceMeasurement != null) { Listcell percentage = (Listcell) selectedItem.getChildren() .get(3); ((Label) percentage.getFirstChild()) .setValue(this.manageOrderElementAdvancesModel .getPercentageAdvanceMeasurement( greatAdvanceMeasurement).toString() + " %"); ((Label) percentage.getFirstChild()).invalidate(); } } } private void setCurrentValue(){ if(this.indexSelectedItem >= 0){ Listitem selectedItem = editAdvances.getItemAtIndex(indexSelectedItem); AdvanceAssignment advanceAssignment = (AdvanceAssignment) selectedItem .getValue(); DirectAdvanceAssignment directAdvanceAssignment; if (advanceAssignment instanceof IndirectAdvanceAssignment) { directAdvanceAssignment = manageOrderElementAdvancesModel .calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) advanceAssignment); } else { directAdvanceAssignment = (DirectAdvanceAssignment) advanceAssignment; } final AdvanceMeasurement greatAdvanceMeasurement = this.manageOrderElementAdvancesModel .getLastAdvanceMeasurement(directAdvanceAssignment); if (greatAdvanceMeasurement != null) { Listcell value = (Listcell)selectedItem.getChildren().get(2); ((Decimalbox) value.getFirstChild()) .setValue(greatAdvanceMeasurement.getValue()); ((Decimalbox) value.getFirstChild()).invalidate(); } } } private Chart chart; public void setCurrentDate(Listitem item){ this.manageOrderElementAdvancesModel.sortListAdvanceMeasurement(); Util.reloadBindings(editAdvancesMeasurement); this.setCurrentDate(); this.setPercentage(); this.setCurrentValue(); Util.reloadBindings(chart); } private void setCurrentDate(){ if(this.indexSelectedItem >= 0){ Listitem selectedItem = editAdvances.getItemAtIndex(indexSelectedItem); AdvanceAssignment advanceAssignment = (AdvanceAssignment) selectedItem .getValue(); DirectAdvanceAssignment directAdvanceAssignment; if (advanceAssignment instanceof IndirectAdvanceAssignment) { directAdvanceAssignment = manageOrderElementAdvancesModel .calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) advanceAssignment); } else { directAdvanceAssignment = (DirectAdvanceAssignment) advanceAssignment; } final AdvanceMeasurement greatAdvanceMeasurement = this.manageOrderElementAdvancesModel .getLastAdvanceMeasurement(directAdvanceAssignment); if(greatAdvanceMeasurement != null){ Listcell date = (Listcell) selectedItem.getChildren().get(4); LocalDate newDate = greatAdvanceMeasurement.getDate(); if (newDate != null) { ((Datebox) date.getFirstChild()).setValue(newDate .toDateTimeAtStartOfDay().toDate()); } else { ((Datebox) date.getFirstChild()).setValue(null); } } } } private void cleanFields(DirectAdvanceAssignment advance) { this.manageOrderElementAdvancesModel .cleanAdvance((DirectAdvanceAssignment) advance); } private void setReportGlobalAdvance(final Listitem item){ boolean spread = true; if (!radioSpreadIsConsolidated()) { for (AdvanceAssignment advance : this.getAdvanceAssignments()) { advance.setReportGlobalAdvance(false); } } else { spread = false; } ((AdvanceAssignment) item.getValue()).setReportGlobalAdvance(spread); Util.reloadBindings(editAdvances); resetScreenHeight(); setSelectedAdvanceLine(); } private boolean radioSpreadIsConsolidated() { for (AdvanceAssignment advance : getAdvanceAssignments()) { if ((advance.getReportGlobalAdvance()) && (manageOrderElementAdvancesModel .hasConsolidatedAdvances(advance))) { showMessagesConsolidation(1); return true; } } return false; } private boolean validateDataForm(){ return ((validateListAdvanceAssignment()) &&(validateListAdvanceMeasurement())); } private boolean validateListAdvanceAssignment(){ for(int i=0; i< editAdvances.getChildren().size(); i++){ if(editAdvances.getChildren().get(i) instanceof Listitem){ Listitem listItem = (Listitem) editAdvances.getChildren().get(i); AdvanceAssignment advance = (AdvanceAssignment) listItem .getValue(); if (advance != null) { if (advance.getAdvanceType() == null) { throw new WrongValueException( getComboboxTypeBy(listItem), _("Value is not valid, the type must be not empty")); } DirectAdvanceAssignment directAdvanceAssignment; if (advance instanceof IndirectAdvanceAssignment) { directAdvanceAssignment = manageOrderElementAdvancesModel .calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) advance); } else { directAdvanceAssignment = (DirectAdvanceAssignment) advance; } if (directAdvanceAssignment != null && directAdvanceAssignment.getMaxValue() == null) { throw new WrongValueException( getDecimalboxMaxValueBy(listItem), _("Value is not valid, the current value must be not empty")); } } } } return true; } private boolean validateListAdvanceMeasurement(){ for(int i=0; i< editAdvancesMeasurement.getChildren().size(); i++){ if(editAdvancesMeasurement.getChildren().get(i) instanceof Listitem){ Listitem listItem = (Listitem) editAdvancesMeasurement.getChildren().get(i); AdvanceMeasurement advance = (AdvanceMeasurement) listItem .getValue(); if (advance != null) { // Validate the value of the advance measurement Decimalbox valueBox = getDecimalboxBy(listItem); valueBox.setValue(advance.getValue()); // Validate the date of the advance measurement Datebox dateBox = getDateboxBy(listItem); if (advance.getDate() == null) { dateBox.setValue(null); } else { dateBox.setValue(advance.getDate() .toDateTimeAtStartOfDay().toDate()); } } } } return true; } private Combobox getComboboxTypeBy(Listitem item) { return (Combobox) ((Listcell) item.getChildren().get(0)) .getFirstChild(); } private Combobox getDecimalboxMaxValueBy(Listitem item) { return (Combobox) ((Listcell) item.getChildren().get(1)) .getFirstChild(); } private Decimalbox getDecimalboxBy(Listitem item) { return (Decimalbox) ((Listcell) item.getChildren().get(0)) .getFirstChild(); } private Datebox getDateboxBy(Listitem item) { return (Datebox) ((Listcell) item.getChildren().get(2)).getFirstChild(); } private boolean validateReportGlobalAdvance(){ boolean existItems = false; for (AdvanceAssignment advance : this.getAdvanceAssignments()) { existItems = true; if (advance.getReportGlobalAdvance()) { return true; } } return (!existItems); } public AdvanceMeasurementRenderer getAdvanceMeasurementRenderer() { return advanceMeasurementRenderer; } private class AdvanceMeasurementRenderer implements ListitemRenderer { @Override public void render(Listitem item, Object data) throws Exception { AdvanceMeasurement advanceMeasurement = (AdvanceMeasurement) data; item.setValue(advanceMeasurement); appendDecimalBoxValue(item); appendLabelPercentage(item); appendDateboxDate(item); appendRemoveButton(item); } private void appendDecimalBoxValue(final Listitem listitem) { final AdvanceMeasurement advanceMeasurement = (AdvanceMeasurement) listitem .getValue(); final Decimalbox value = new Decimalbox(); Listcell listcell = new Listcell(); listcell.appendChild(value); listitem.appendChild(listcell); value.setScale(4); value.setDisabled(isReadOnlyAdvanceMeasurements()); value.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) throws Exception { if (manageOrderElementAdvancesModel .canRemoveOrChange(advanceMeasurement)) { updatesValue(value); } else { showMessagesConsolidation(2); } } }); Util.bind(value, new Util.Getter<BigDecimal>() { @Override public BigDecimal get() { return advanceMeasurement.getValue(); } }, new Util.Setter<BigDecimal>() { @Override public void set(BigDecimal value) { if (manageOrderElementAdvancesModel .canRemoveOrChange(advanceMeasurement)) { advanceMeasurement.setValue(value); reloadAdvances(); } } }); value.setConstraint(checkValidValue()); } private void appendLabelPercentage(final Listitem listitem) { final AdvanceMeasurement advanceMeasurement = (AdvanceMeasurement) listitem .getValue(); BigDecimal percentage = manageOrderElementAdvancesModel .getPercentageAdvanceMeasurement(advanceMeasurement); Label percentageLabel = new Label(percentage.toString() + " %"); Listcell listcell = new Listcell(); listcell.appendChild(percentageLabel); listitem.appendChild(listcell); } private void appendDateboxDate(final Listitem listitem) { final AdvanceMeasurement advanceMeasurement = (AdvanceMeasurement) listitem .getValue(); final Datebox date = new Datebox(); Listcell listcell = new Listcell(); listcell.appendChild(date); listitem.appendChild(listcell); date.setDisabled(isReadOnlyAdvanceMeasurements()); date.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) throws Exception { if (manageOrderElementAdvancesModel .canRemoveOrChange(advanceMeasurement)) { setCurrentDate(listitem); } else { showMessagesConsolidation(2); } } }); Util.bind(date, new Util.Getter<Date>() { @Override public Date get() { if (advanceMeasurement.getDate() == null) { return null; } return advanceMeasurement.getDate() .toDateTimeAtStartOfDay().toDate(); } }, new Util.Setter<Date>() { @Override public void set(Date value) { if (manageOrderElementAdvancesModel .canRemoveOrChange(advanceMeasurement)) { LocalDate oldDate = advanceMeasurement.getDate(); advanceMeasurement.setDate(new LocalDate(value)); if (manageOrderElementAdvancesModel .hasConsolidatedAdvances(advanceMeasurement)) { showMessagesConsolidation(new LocalDate(value)); advanceMeasurement.setDate(oldDate); } manageOrderElementAdvancesModel .sortListAdvanceMeasurement(); reloadAdvances(); } } }); date.setConstraint(checkValidDate()); } private Constraint checkValidValue() { Constraint newConstraint = new Constraint() { @Override public void validate(Component comp, Object value) throws WrongValueException { AdvanceMeasurement advanceMeasurement = getAdvanceMeasurementByComponent(comp); if ((advanceMeasurement != null) && (manageOrderElementAdvancesModel .canRemoveOrChange(advanceMeasurement))) { advanceMeasurement.setValue((BigDecimal) value); if (((BigDecimal) value) == null) { throw new WrongValueException( comp, _("Value is not valid, the current value must be not empty")); } else { if (manageOrderElementAdvancesModel .greatThanMaxValue(advanceMeasurement)) { throw new WrongValueException( comp, _("Value is not valid, the current value must be less than max value")); } if (!manageOrderElementAdvancesModel .isPrecisionValid(advanceMeasurement)) { throw new WrongValueException( comp, _("Value is not valid, the Precision value must be exact " + manageOrderElementAdvancesModel .getUnitPrecision())); } if (manageOrderElementAdvancesModel .lessThanPreviousMeasurements()) { throw new WrongValueException( comp, _("Value is not valid, the value must be greater than the value of the previous advances.")); } } } } }; return newConstraint; } private AdvanceMeasurement getAdvanceMeasurementByComponent( Component comp) { try { Listitem item = (Listitem) comp.getParent().getParent(); return (AdvanceMeasurement) item.getValue(); } catch (Exception e) { return null; } } private Constraint checkValidDate() { Constraint newConstraint = new Constraint() { @Override public void validate(Component comp, Object value) throws WrongValueException { AdvanceMeasurement advanceMeasurement = getAdvanceMeasurementByComponent(comp); if ((manageOrderElementAdvancesModel .canRemoveOrChange(advanceMeasurement))) { if (((Date) value) == null) { advanceMeasurement.setDate(null); throw new WrongValueException( comp, _("The date is not valid, the date must be not empty")); } else { if (!manageOrderElementAdvancesModel .isDistinctValidDate((Date) value, advanceMeasurement)) { throw new WrongValueException( comp, _("The date is not valid, the date must be unique for this advanced assignment")); } if (advanceMeasurement != null) { LocalDate oldDate = advanceMeasurement .getDate(); advanceMeasurement.setDate(new LocalDate( (Date) value)); if (manageOrderElementAdvancesModel .hasConsolidatedAdvances(advanceMeasurement)){ advanceMeasurement.setDate(oldDate); } else { manageOrderElementAdvancesModel .sortListAdvanceMeasurement(); if (manageOrderElementAdvancesModel .lessThanPreviousMeasurements()) { throw new WrongValueException( comp, _("Value is not valid, the value must be greater than the value of the previous advances.")); } } } } } } }; return newConstraint; } private void appendRemoveButton(final Listitem listItem) { final AdvanceMeasurement measure = (AdvanceMeasurement) listItem .getValue(); final Button removeButton = createRemoveButton(); DirectAdvanceAssignment advance = (DirectAdvanceAssignment) measure .getAdvanceAssignment(); if ((advance.getAdvanceType() != null) && (advance.getAdvanceType().isQualityForm())) { removeButton.setDisabled(true); removeButton .setTooltiptext(_("Advances measurements that are reported by quality forms can not be removed")); } else if (advance.isFake()) { removeButton.setDisabled(true); removeButton .setTooltiptext(_("Calculated advances measurement can not be removed")); } removeButton.addEventListener(Events.ON_CLICK, new EventListener() { @Override public void onEvent(Event event) throws Exception { goToRemoveLineAdvanceMeasurement(listItem); } }); Listcell listCell = new Listcell(); listCell.appendChild(removeButton); listItem.appendChild(listCell); } } public XYModel getChartData() { return this.manageOrderElementAdvancesModel.getChartData(selectedAdvances); } private Button createRemoveButton() { Button removeButton = new Button(); removeButton.setSclass("icono"); removeButton.setImage("/common/img/ico_borrar1.png"); removeButton.setHoverImage("/common/img/ico_borrar.png"); removeButton.setTooltiptext(_("Delete")); return removeButton; } private Button createAddMeasurementButton() { Button addButton = new Button(); addButton.setLabel(_("Add measure")); addButton.setTooltiptext(_("Add new advance measurement")); return addButton; } public void refreshChangesFromOrderElement() { manageOrderElementAdvancesModel.refreshChangesFromOrderElement(); } private void showMessageNotAddMoreAdvances() { String message = _("All advance types have already been assigned."); increaseScreenHeight(); messagesForUser.showMessage(Level.ERROR, message); } public void refreshSelectedAdvance() { if ((indexSelectedItem < 0) || (indexSelectedItem >= getAdvanceAssignments().size())) { selectSpreadAdvanceLine(); } selectAdvanceLine(indexSelectedItem); } private void showMessageDeleteSpread() { String message = _("This advance can not be removed, because it is spread. It is necessary to select another advance as spread."); increaseScreenHeight(); messagesForUser.showMessage(Level.ERROR, message); } private void showMessagesConsolidation(int opcion) { String message = ""; switch (opcion) { case 1: message = _("This advance can not be changed or removed, because it has got consolidated advances. It is needed to remove the consolidation on all its advances."); break; case 2: message = _("This advance measurement can not be changed or removed, because it is consolidated. It is needed to remove its consolidation."); break; case 3: message = _("This advance measurement can not be in current date, because it is consolidated. it is necessary to select other date."); break; } if (!StringUtils.isBlank(message)) { increaseScreenHeight(); messagesForUser.showMessage(Level.ERROR, message); } } private void showMessagesConsolidation(LocalDate date) { String message = _("This advance measurement can not be in " + date + ", because it is consolidated. it is necessary to select other date."); increaseScreenHeight(); messagesForUser.showMessage(Level.ERROR, message); } public void createPercentageAdvances(IOrderElementModel orderElementModel) throws DuplicateAdvanceAssignmentForOrderElementException, DuplicateValueTrueReportGlobalAdvanceException { setOrderElementModel(orderElementModel); manageOrderElementAdvancesModel.initEdit(getOrderElement()); manageOrderElementAdvancesModel .createPercentageAdvances(getOrderElement()); } }
package org.nuxeo.ecm.automation.core.util; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.google.common.base.Objects; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.nuxeo.ecm.automation.core.Constants; import org.nuxeo.runtime.api.Framework; /** * Inline properties file content. This class exists to have a real type for * parameters accepting properties content. * * @see Constants * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> */ public class Properties extends HashMap<String, String> { private static final long serialVersionUID = 1L; protected static final String PROPERTIES_MULTILINE_ESCAPE = "nuxeo" + ".automation.properties.multiline.escape"; protected static final String multiLineEscape = Objects.firstNonNull (Framework.getProperty(PROPERTIES_MULTILINE_ESCAPE), "false"); public Properties() { } public Properties(int size) { super(size); } public Properties(Map<String, String> props) { super(props); } public Properties(String content) throws Exception { StringReader reader = new StringReader(content); loadProperties(reader, this); } /** * Constructs a Properties map based on a Json node. * * @param node * @throws IOException * * @since 5.7.3 */ public Properties(JsonNode node) throws IOException { Iterator<Entry<String, JsonNode>> fields = node.getFields(); ObjectMapper om = new ObjectMapper(); while (fields.hasNext()) { Entry<String, JsonNode> entry = fields.next(); String key = entry.getKey(); JsonNode subNode = entry.getValue(); put(key, extractValueFromNode(subNode, om)); } } /** * @param om * @param subNode * @return * @throws IOException * * @since 5.8-HF01 */ private String extractValueFromNode(JsonNode node, ObjectMapper om) throws IOException { if (!node.isNull()) { return node.isContainerNode() ? om.writeValueAsString(node) : node.getValueAsText(); } else { return null; } } public static Map<String, String> loadProperties(Reader reader) throws Exception { Map<String, String> map = new HashMap<String, String>(); loadProperties(reader, map); return map; } public static void loadProperties(Reader reader, Map<String, String> map) throws Exception { BufferedReader in = new BufferedReader(reader); String line = in.readLine(); String prevLine = null; while (line != null) { line = line.trim(); if (line.startsWith("#") || line.length() == 0) { prevLine = null; line = in.readLine(); continue; } if (line.endsWith("\\") && Boolean.valueOf(multiLineEscape)) { line = line.substring(0, line.length() - 1); prevLine = prevLine != null ? prevLine + line : line; line = in.readLine(); continue; } if (prevLine != null) { line = prevLine + line; } prevLine = null; setPropertyLine(map, line); line = in.readLine(); } if (prevLine != null) { setPropertyLine(map, prevLine); } } protected static void setPropertyLine(Map<String, String> map, String line) throws Exception { int i = line.indexOf('='); if (i == -1) { throw new IOException("Invalid property line: " + line); } map.put(line.substring(0, i).trim(), line.substring(i + 1).trim()); } }
import java.util.*; import org.xbill.DNS.*; public class lookup { public static void printAnswer(String name, Lookup lookup) { System.out.print(name + ":"); int result = lookup.getResult(); if (result != Lookup.SUCCESSFUL) System.out.print(" " + lookup.getErrorString()); System.out.println(); Name [] aliases = lookup.getAliases(); if (aliases.length > 0) { System.out.print("# aliases: "); for (int i = 0; i < aliases.length; i++) { System.out.print(aliases[i]); if (i < aliases.length - 1) System.out.print(" "); } System.out.println(); } if (lookup.getResult() == Lookup.SUCCESSFUL) { Record [] answers = lookup.getAnswers(); for (int i = 0; i < answers.length; i++) System.out.println(answers[i]); } } public static void main(String [] args) throws Exception { short type = Type.A; int start = 0; if (args.length > 2 && args[0].equals("-t")) { type = Type.value(args[1]); if (type < 0) throw new IllegalArgumentException("invalid type"); start = 2; } for (int i = start; i < args.length; i++) { Lookup l = new Lookup(args[i], type); l.run(); printAnswer(args[i], l); } } }
import java.io.*; import java.util.*; import java.text.*; import javax.servlet.*; import javax.servlet.http.*; import imcode.external.diverse.*; import imcode.external.chat.*; import imcode.server.HTMLConv ; import imcode.util.* ; import imcode.util.fortune.* ; /** * @author Monika Hurtig * @version 1.0 * Date : 2001-09-05 */ public class QuotPicEngine extends HttpServlet { private final static String CVS_REV = "$Revision$" ; private final static String CVS_DATE = "$Date$"; private final static SimpleDateFormat dateF = new SimpleDateFormat("yyMMdd"); public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; res.setContentType("text/html"); Writer out = res.getWriter(); //get parameters String type = req.getParameter("type"); String inFile = req.getParameter("file"); //lets get a list of all questions/citat/pictures List lines; if (type.equals("pic") || type.equals("quot")){ lines = IMCServiceRMI.getQuoteList(imcServer, inFile +".txt"); }else { lines = IMCServiceRMI.getPollList(imcServer,inFile +".txt"); } //ok lets loop and store the ones to use Date date = new Date(); Hashtable hash = new Hashtable(); int counter = 0; for(int i=0; i<lines.size();i++) { Object obj = lines.get(i); DateRange dates; if (obj instanceof Poll) { dates = ((Poll)obj).getDateRange(); }else { dates = ((Quote)obj).getDateRange(); } if (dates.contains(date)) { hash.put(new Integer(counter++),new Integer(i)); } } //get the text and row to return String theText = "<!-- Error in QuotPicEngine, nothing was returned! -->" ; int the_row = -1; if ( counter > 0 ){ //lets get the pos in the list to get Random random = new Random(); the_row = random.nextInt(counter); the_row = ((Integer)hash.get(new Integer(the_row))).intValue(); } if ( type.equals("pic")){ if (the_row != -1) { theText = "<img src=\"" + HTMLConv.toHTMLSpecial(((Quote)lines.get(the_row)).getText()) + "\">" ; } } else if(type.equals("quot")){ if (the_row != -1) { theText = HTMLConv.toHTMLSpecial(((Quote)lines.get(the_row)).getText()) + "<input type=\"hidden\" name=\"quotrow\" value=\"" + the_row + "\">" + "<input type=\"hidden\" name=\"quot\" value=\"" + HTMLConv.toHTMLSpecial(((Quote)lines.get(the_row)).getText()) + "\">" ; } } else { if (the_row != -1) { theText = HTMLConv.toHTMLSpecial(((Poll)lines.get(the_row)).getQuestion()); } } out.write(theText) ; out.close(); return ; } // End doGet public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { this.doGet(req,res); return ; } /** Log function, will work for both servletexec and Apache **/ public void log( String str) { super.log(str) ; } } // End class
package com.moac.android.opensecretsanta.fragment; import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.moac.android.inject.dagger.InjectingDialogFragment; import com.moac.android.opensecretsanta.R; import com.moac.android.opensecretsanta.activity.Intents; import com.moac.android.opensecretsanta.adapter.AccountAdapter; import com.moac.android.opensecretsanta.database.DatabaseManager; import com.moac.android.opensecretsanta.model.Group; import com.moac.android.opensecretsanta.notify.NotifyAuthorization; import com.moac.android.opensecretsanta.notify.mail.EmailAuthorization; import com.moac.android.opensecretsanta.notify.sms.SmsPermissionsManager; import com.moac.android.opensecretsanta.util.AccountUtils; import com.moac.android.opensecretsanta.util.NotifyUtils; import java.util.Arrays; import javax.inject.Inject; import rx.Observable; import rx.android.concurrency.AndroidSchedulers; import rx.concurrency.Schedulers; import rx.util.functions.Action1; public class NotifyDialogFragment extends InjectingDialogFragment { private static final String TAG = NotifyDialogFragment.class.getSimpleName(); private static final String MESSAGE_KEY = "message"; public static final int SMS_PERMISSION_REQUEST_CODE = 53535; @Inject DatabaseManager mDb; @Inject SharedPreferences mSharedPreferences; @Inject AccountManager mAccountManager; @Inject SmsPermissionsManager mSmsPermissionsManager; private EditText mMsgField; private Group mGroup; private long[] mMemberIds; private FragmentContainer mFragmentContainer; private Spinner mSpinner; private TextView mInfoTextView; private ViewGroup mEmailFromContainer; private boolean mIsEmailAuthRequired; private boolean mIsSmsPermissionRequired; private int mMaxMsgLength; private String mSavedMsg; private TextView mCharCountView; public static NotifyDialogFragment create(long groupId, long[] memberIds) { Log.i(TAG, "NotifyDialogFragment() - factory creating for groupId: " + groupId + " memberIds: " + Arrays.toString(memberIds)); NotifyDialogFragment fragment = new NotifyDialogFragment(); Bundle args = new Bundle(); args.putLong(Intents.GROUP_ID_INTENT_EXTRA, groupId); args.putLongArray(Intents.MEMBER_ID_ARRAY_INTENT_EXTRA, memberIds); fragment.setArguments(args); return fragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Log.i(TAG, "onCreateDialog() - start: " + this); mMemberIds = getArguments().getLongArray(Intents.MEMBER_ID_ARRAY_INTENT_EXTRA); mMaxMsgLength = getResources().getInteger(R.integer.max_notify_msg_length); // Inflate layout LayoutInflater inflater = getActivity().getLayoutInflater(); @SuppressLint("InflateParams") // Null parent OK for dialog View view = inflater.inflate(R.layout.fragment_dialog_notify, null); // Configure the views mMsgField = (EditText) view.findViewById(R.id.tv_notify_msg); mCharCountView = (TextView) view.findViewById(R.id.tv_notify_msg_char_count); // Add the callback to the field mMsgField.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { // Update the reported character length mCharCountView.setText(String.valueOf(mMaxMsgLength - s.length())); if (mMsgField.length() == mMaxMsgLength) { mCharCountView.setTextColor(Color.RED); } else { mCharCountView.setTextColor(getResources().getColor(R.color.text_neutral_color)); } } }); // Visibility GONE by default mEmailFromContainer = (ViewGroup) view.findViewById(R.id.layout_notify_email_container); mSpinner = (Spinner) view.findViewById(R.id.spnr_email_selection); mInfoTextView = (TextView) view.findViewById(R.id.tv_notify_info); final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()) .setView(view) .setTitle(getString(R.string.notify_dialog_title)) .setIcon(R.drawable.ic_menu_notify) .setCancelable(true) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(R.string.notify_send_button_text, null) .create(); // We can't allow the dialog to be dismissed before the onActivityResult expected back // when SMS is being sent as the Fragment is usually destroyed before the result is returned. // So to work-around this, add this listener which attaches anotherlistener that handles the // positive (send) button press and explicitly call dismiss() to once onNotifyRequest() has // completed. // The OnShowListener is required as the sendButton is null until the View is created. // While this listener could just be attached in onStart(), it's easier to read here. alertDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { Button sendButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE); sendButton.setOnClickListener(new OnSendClickedListener()); } }); alertDialog.getWindow().setWindowAnimations(R.style.dialog_animate_overshoot); return alertDialog; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Populate those field that require injected dependencies long groupId = getArguments().getLong(Intents.GROUP_ID_INTENT_EXTRA); mGroup = mDb.queryById(groupId, Group.class); String message = mSavedMsg == null ? mGroup.getMessage() : savedInstanceState.getString(MESSAGE_KEY); mMsgField.append(message); int remainingChars = mMaxMsgLength; if (message != null) { remainingChars = message.length() >= mMaxMsgLength ? 0 : mMaxMsgLength - message.length(); } mCharCountView.setText(String.valueOf(remainingChars)); mIsEmailAuthRequired = NotifyUtils.containsEmailSendableEntry(mDb, mMemberIds); mIsSmsPermissionRequired = NotifyUtils.requiresSmsPermission(getActivity()); if (mIsEmailAuthRequired) { // Add all Gmail accounts to list final Observable<Account[]> accountsObservable = AccountUtils.getAllGmailAccountsObservable(getActivity(), mAccountManager); accountsObservable. subscribeOn(Schedulers.newThread()). observeOn(AndroidSchedulers.mainThread()). subscribe(new Action1<Account[]>() { @Override public void call(Account[] accounts) { AccountAdapter aa = new AccountAdapter(getActivity(), accounts); mSpinner.setAdapter(aa); mEmailFromContainer.setVisibility(View.VISIBLE); // TODO Set email to preference } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { mInfoTextView.setText(throwable.getMessage()); mInfoTextView.setVisibility(View.VISIBLE); } } ); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(MESSAGE_KEY, mMsgField.getText().toString()); Log.d(TAG, "onSaveInstanceState() msg: " + outState.getString(MESSAGE_KEY)); mSavedMsg = outState.getString(MESSAGE_KEY); } @Override public void onDestroyView() { if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mFragmentContainer = (FragmentContainer) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement FragmentContainer"); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.i(TAG, "onActivityResult() - requestCode: " + requestCode); if (requestCode == SMS_PERMISSION_REQUEST_CODE) { onNotifyRequested(); } } protected void onNotifyRequested() { final NotifyAuthorization.Builder auth = new NotifyAuthorization.Builder(); if (mIsEmailAuthRequired) { Account acc = (Account) mSpinner.getSelectedItem(); if (acc != null) { // Set the selected email as the user preference String emailPrefKey = getActivity().getString(R.string.gmail_account_preference); mSharedPreferences.edit().putString(emailPrefKey, acc.name).apply(); AccountUtils.getPreferedGmailAuth(getActivity(), mAccountManager, mSharedPreferences, getActivity()). subscribeOn(Schedulers.newThread()). observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<EmailAuthorization>() { @Override public void call(EmailAuthorization emailAuth) { Log.d(TAG, "call() - got EmailAuthorization: " + emailAuth.getEmailAddress() + ":" + emailAuth.getToken()); auth.withAuth(emailAuth); mGroup.setMessage(mMsgField.getText().toString().trim()); mDb.update(mGroup); executeNotifyDraw(auth.build(), mGroup, mMemberIds); } }); } // else no email auth available - do nothing. } else { // We have no additional authorization - just send as is // Get the custom message. mGroup.setMessage(mMsgField.getText().toString().trim()); mDb.update(mGroup); executeNotifyDraw(auth.build(), mGroup, mMemberIds); } this.dismiss(); } private void executeNotifyDraw(NotifyAuthorization auth, Group group, long[] members) { mFragmentContainer.executeNotifyDraw(auth, group, members); } private class OnSendClickedListener implements View.OnClickListener { @Override public void onClick(View v) { if (mIsSmsPermissionRequired) { mSmsPermissionsManager .requestDefaultSmsPermission(getActivity().getApplicationContext(), NotifyDialogFragment.this, SMS_PERMISSION_REQUEST_CODE); } else { onNotifyRequested(); } } } public interface FragmentContainer { public void executeNotifyDraw(NotifyAuthorization auth, Group group, long[] members); } }
import java.io.*; import java.util.*; import java.text.*; import javax.servlet.*; import javax.servlet.http.*; import imcode.external.diverse.*; import imcode.external.chat.*; import imcode.util.* ; /** * @author Monika Hurtig * @version 1.0 * Date : 2001-09-05 */ public class QuotPicEngine extends HttpServlet { String inFile = ""; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; res.setContentType("text/html"); PrintWriter out = res.getWriter(); //get parameters String type = req.getParameter("type"); inFile = req.getParameter("file"); BufferedReader readFile = new BufferedReader( new StringReader( IMCServiceRMI.getFortune(imcServer,inFile + ".txt") ) ); SimpleDateFormat dateF = new SimpleDateFormat("yyMMdd"); //collect the correct questions/citat/pictures HashMap row_texts = new HashMap(50); //rownr int row = 0; String line = readFile.readLine(); //out.println("line: " + line + "<br>"); //get questions while (line != null && line.length() != 0 ) //&& !( ( date1.before(date)||date1.equals(date) ) && ( date2.after(date)||date2.equals(date) ) ) ) { //out.println("line: " + line + "<br>"); StringTokenizer tokens = new StringTokenizer(line," try { //the dates Date date1 = dateF.parse(tokens.nextToken()); Date date2 = dateF.parse(tokens.nextToken()); Date date = new Date(); String tempQ = tokens.nextToken(); if ( ( ( date1.before(date) ) || ( (dateF.format(date1)).equals(dateF.format(date)) ) ) && ( ( date2.after(date) ) || ( (dateF.format(date2)).equals(dateF.format(date)) ) ) ) { row_texts.put( new Integer(row),tempQ ); } } catch(ParseException e) { log("ParseException in QuotPicEngine"); } row++; line = readFile.readLine(); } int max_row = row; Collection texts = row_texts.values(); int nr = texts.size(); //get the text and row to return String theText; int the_row; if (!(nr>0)) { //no question was found theText = "Ingen text kan visas" ; the_row = -1; } else { //get one randomised item Set rows = row_texts.keySet(); do { Random random = new Random(); the_row = random.nextInt(max_row); } while(!rows.contains(new Integer(the_row))); theText = (String)row_texts.get(new Integer(the_row)); } if( type.equals("pic")) { out.println( "<img src=\" " + theText + "\"> "); } else if(type.equals("quot")) { out.println(theText ); //raden i filen out.println("<input type=\"hidden\" name=\"quotrow\" value=\"" + the_row + "\">"); out.println("<input type=\"hidden\" name=\"quot\" value=\"" + theText + "\">"); } else { out.println( theText ); } return ; } // End doGet public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { this.doGet(req,res); return ; } /** Log function, will work for both servletexec and Apache **/ public void log( String str) { super.log(str) ; } } // End class
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import imcode.external.diverse.* ; import imcode.util.*; import imcode.util.IMCServiceRMI; import imcode.util.Parser; import imcode.external.chat.*; /** * superclas for chat servlets. * * Html template in use: * Chat_Admin_Button.htm???? * * Html parstags in use: * #ADMIN_TYPE#??? * #TARGET#??? * * stored procedures in use: * - * * */ public class ChatBase extends HttpServlet { private final static String ADMIN_BUTTON_TEMPLATE = "Chat_Admin_Button.htm"; private final static String UNADMIN_BUTTON_TEMPLATE = "Chat_Unadmin_Button.htm"; private static Map _allChats; /** * Does the things that has to bee done only ones */ public void init(ServletConfig config) throws ServletException { super.init(config); log("init"); //lets create an empty one _allChats = Collections.synchronizedMap(new HashMap()); } /** Returns the metaId from a request object, if not found, we will get the one from our session object. If still not found then null is returned. */ public String getMetaId (HttpServletRequest req) throws ServletException, IOException { String metaId = req.getParameter("meta_id") ; if( metaId == null ) { HttpSession session = req.getSession(false) ; if (session != null) { metaId = (String) session.getValue("Chat.meta_id") ; } } if( metaId == null) { log("No meta_id could be found! Error in Chat.class") ; return null ; } return metaId ; } /** Returns the ForumId from a request object, if not found, we will get the one from our session object. If still not found then null is returned. */ public String getForumId (HttpServletRequest req) throws ServletException, IOException { String forumId = req.getParameter("forum_id") ; if( forumId == null ) { HttpSession session = req.getSession(false) ; if (session != null) { forumId = (String) session.getValue("Chat.forum_id") ; } } if( forumId == null) { log("No forum_id could be found! Error in Chat.class") ; return null ; } return forumId ; } /** Collects all information from the user object. To get information from the userobject. * userObject.getString(String theKey) * userObject.getInt(String theKey) * userObject.getBoolean(String theKey) **/ public Properties getUserParameters(imcode.server.User user) { Properties userParams= new Properties() ; userParams.setProperty("USER_ID", user.getString("user_id")) ; userParams.setProperty("LOGIN_NAME", user.getString("login_name")) ; userParams.setProperty("LOGIN_PASSWORD", user.getString("login_password")) ; userParams.setProperty("FIRST_NAME", user.getString("first_name")) ; userParams.setProperty("LAST_NAME", user.getString("last_name")) ; userParams.setProperty("ADDRESS", user.getString("address")) ; userParams.setProperty("CITY", user.getString("city")) ; userParams.setProperty("ZIP", user.getString("zip")) ; userParams.setProperty("COUNTRY", user.getString("country")) ; userParams.setProperty("COUNTY_COUNCIL", user.getString("county_council")) ; userParams.setProperty("EMAIL", user.getString("email")) ; userParams.setProperty("ADMIN_MODE", user.getString("admin_mode")) ; userParams.setProperty("LAST_PAGE", user.getString("last_page")) ; userParams.setProperty("ARCHIVE_MODE", user.getString("archive_mode")) ; userParams.setProperty("USER_TYPE", user.getString("user_type")) ; userParams.setProperty("LOGIN_TYPE", user.getLoginType()) ; //userParams.setProperty("LANG_ID", user.getString("lang_id")) ; // log("GetUserParameters: " + userParams.toString()) ; return userParams ; } /** Returns an user object. If an error occurs, an errorpage will be generated. */ protected imcode.server.User getUserObj(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if(checkSession(req,res) == true) { // Get the session HttpSession session = req.getSession(true); // Does the session indicate this user already logged in? Object done = session.getValue("logon.isDone"); // marker object imcode.server.User user = (imcode.server.User) done ; return user ; } else { String header = "Chat servlet." ; ChatError err = new ChatError(req,res,header, 2) ; log(err.getErrorMsg()) ; return null ; } } /** Collects the standard parameters from the session object **/ public Properties getSessionParameters( HttpServletRequest req) throws ServletException, IOException { // Get the session HttpSession session = req.getSession(true); String metaId = ( (String) session.getValue("Chat.meta_id")==null) ? "" : ((String) session.getValue("Chat.meta_id")) ; String parentId = ( (String) session.getValue("Chat.parent_meta_id")==null) ? "" : ((String) session.getValue("Chat.parent_meta_id")) ; String cookieId = ( (String) session.getValue("Chat.cookie_id")==null) ? "" : ((String) session.getValue("Chat.cookie_id")) ; Properties reqParams= new Properties() ; reqParams.setProperty("META_ID", metaId) ; reqParams.setProperty("PARENT_META_ID", parentId) ; reqParams.setProperty("COOKIE_ID", cookieId) ; return reqParams ; } /** Collects the EXTENDED parameters from the session object. As extended paramters are we counting: Chat.forum_id Chat.discussion_id @Parameter: Properties params, if a properties object is passed, we will fill the object with the extended paramters, otherwise we will create one. **/ public Properties getExtSessionParameters( HttpServletRequest req, Properties params) throws ServletException, IOException { // Get the session HttpSession session = req.getSession(true); String forumId = ( (String) session.getValue("Chat.forum_id")==null) ? "" : ((String) session.getValue("Chat.forum_id")) ; String discId = ( (String) session.getValue("Chat.disc_id")==null) ? "" : ((String) session.getValue("Chat.disc_id")) ; if( params == null) params = new Properties() ; params.setProperty("FORUM_ID", forumId) ; params.setProperty("DISC_ID", discId) ; return params ; } /** Verifies that the user has logged in. If he hasnt, he will be redirected to an url which we get from a init file name conference. */ protected boolean checkSession(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Get the session HttpSession session = req.getSession(true); // Does the session indicate this user already logged in? Object done = session.getValue("logon.isDone"); // marker object imcode.server.User user = (imcode.server.User) done ; // Lets get serverinformation String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; String ChatPoolServer = Utility.getDomainPref("chat_server",host) ; if (done == null) { // No logon.isDone means he hasn't logged in. // Save the request URL as the true target and redirect to the login page. session.putValue("login.target", HttpUtils.getRequestURL(req).toString()); String serverName = MetaInfo.getServerName(req) ; String startUrl = RmiConf.getLoginUrl(host) ; res.sendRedirect(serverName + startUrl) ; //this.log("Server: " + serverName) ; //this.log("startUrl: " + startUrl) ; //this.log("A user had not logged in. He was sent to " + serverName + startUrl) ; return false; } return true ; } /** Collects the parameters from the request object **/ public Properties getParameters( HttpServletRequest req) throws ServletException, IOException { MetaInfo mInfo = new MetaInfo() ; return mInfo.getParameters(req) ; } /** check the meta Parameters */ public boolean checkParameters(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { MetaInfo mInfo = new MetaInfo() ; Properties params = mInfo.getParameters(req) ; if( mInfo.checkParameters(params) == false) { String header = "Chat servlet." ; String msg = params.toString() ; ChatError err = new ChatError(req, res, header, msg, 1) ; return false; } return true ; } public boolean checkParameters(HttpServletRequest req,HttpServletResponse res, Properties params) throws ServletException, IOException { MetaInfo mInfo = new MetaInfo() ; if( mInfo.checkParameters(params) == false) { String header = "Chat servlet." ; String msg = params.toString() ; ChatError err = new ChatError(req, res, header, msg, 1) ; log(err.getErrorString()) ; return false; } return true ; } protected boolean getAdminRights(String server, String metaId, imcode.server.User user) { /* Rickards old style try { // Lets verify if the user has admin rights for the metaid RmiConf rmi = new RmiConf(user) ; return rmi.checkAdminRights( server, metaId , user ) ; } catch (Exception e) { log("GetAdminRights failed!!!") ; return false ; } */ try { return userHasAdminRights( server, Integer.parseInt( metaId ), user ); } catch ( IOException e ) { log("GetAdminRights failed!!!") ; return false ; } } // End GetAdminRights /** CheckAdminRights, returns true if the user is an superadmin. Only an superadmin is allowed to create new users False if the user isn't an administrator. 1 = administrator 0 = superadministrator */ protected boolean checkAdminRights(String server, imcode.server.User user) { try { // Lets verify that the user who tries to add a new user is an SUPERADMIN RmiLayer imc = new RmiLayer(user) ; int currUser_id = user.getInt("user_id") ; String checkAdminSql = "CheckAdminRights " + currUser_id ; String[] roles = imc.execSqlProcedure(server, checkAdminSql) ; for(int i = 0 ; i< roles.length; i++ ) { String aRole = roles[i] ; if(aRole.equalsIgnoreCase("0") ) return true ; } return false ; } catch (IOException e) { this.log("An error occured in CheckAdminRights") ; this.log(e.getMessage() ) ; } return false ; } // checkAdminRights /** CheckAdminRights, returns true if the user is an admin. False if the user isn't an administrator */ protected boolean checkAdminRights(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Lets get serverinformation String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; String ChatPoolServer = Utility.getDomainPref("chat_server",host) ; imcode.server.User user = getUserObj(req,res) ; if(user == null) { this.log("CheckadminRights: an error occured, getUserObj") ; return false ; } else return checkAdminRights(imcServer, user) ; } /** CheckAdminRights, returns true if the user is an admin. False if the user isn't an administrator */ protected boolean checkDocRights(String server, String meta_id, imcode.server.User user) throws ServletException, IOException { return RmiConf.checkDocRights(server, meta_id, user) ; } /** Gives the folder to the root external folder,Example /templates/se/102/ */ public String getExternalTemplateRootFolder (HttpServletRequest req) throws ServletException, IOException { // Lets get serverinformation String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; String ChatPoolServer = Utility.getDomainPref("chat_server",host) ; String externalTemplateLib = "" ; String metaId = this.getMetaId(req) ; if( metaId == null) { log("No meta_id could be found! Error in Chat.class") ; return "No meta_id could be found!" ; } externalTemplateLib = MetaInfo.getExternalTemplateFolder(imcServer, metaId) ; return externalTemplateLib ; } /** Gives the folder where All the html templates for a language are located. This method will call its helper method getTemplateLibName to get the name of the folder which contains the templates for a certain meta id */ public String getExternalTemplateFolder (HttpServletRequest req) throws ServletException, IOException { String externalTemplateLib = "" ; String metaId = this.getMetaId(req) ; if( metaId == null) { log("No meta_id could be found! Error in Chat.class") ; return "No meta_id could be found!" ; } // Lets get serverinformation String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; String confPoolServer = Utility.getDomainPref("chat_server",host) ; String extFolder = this.getExternalTemplateFolder(imcServer, metaId) ; return extFolder += this.getTemplateLibName(confPoolServer, metaId) ; // return this.getExternalTemplateFolder(imcServer, metaId) ; } /** Gives the folder where All the html templates for a language are located. This method will call its helper method getTemplateLibName to get the name of the folder which contains the templates for a certain meta id */ public String getExternalTemplateFolder (String server, String metaId ) throws ServletException, IOException { String externalTemplateLib = "" ; if( metaId == null) { log("No meta_id could be found! Error in Chat.class") ; return "No meta_id could be found!" ; } externalTemplateLib = MetaInfo.getExternalTemplateFolder(server, metaId) ; if(externalTemplateLib == null) log("Error!: getExternalTemplateFolder: " + externalTemplateLib) ; //externalTemplateLib += this.getTemplateLibName(server, metaId) ; // log("ExternalTemplateLib: " + externalTemplateLib) ; return externalTemplateLib ; } /** Returns the foldername where the templates are situated for a certain metaid. **/ protected String getTemplateLibName(String server, String meta_id) throws ServletException, IOException { // RmiConf aRmiObj = new RmiConf() ; String sqlQ = "GetTemplateLib " + meta_id ; String libName = RmiConf.execSqlProcedureStr(server, sqlQ) ; if( libName == null) { libName = "original" ; //log(sqlQ + ": fungerar inte!") ; } libName += "/" ; return libName ; } // End of getTemplateLibName /** Collects the parameters from the request object. This function will get all the possible parameters this servlet will be able to get. If a parameter wont be found, the session parameter will be used instead, or if no such parameter exist in the session object, a key with no value = "" will be used instead. Since this method is used. it means that this servlet will take more arguments than the standard ones. **/ public Properties getRequestParameters( HttpServletRequest req) throws ServletException, IOException { Properties reqParams = new Properties() ; // Lets get our own variables. We will first look for the discussion_id // in the request object, if not found, we will get the one from our session object String confForumId = req.getParameter("forum_id") ; // log("Nytt ForumId r: " + confForumId) ; if( confForumId == null ) { HttpSession session = req.getSession(false) ; if (session != null) { confForumId = (String) session.getValue("Chat.forum_id") ; } } reqParams.setProperty("FORUM_ID", confForumId) ; return reqParams ; } /** SendHtml. Generates the html page to the browser. Uses the templatefolder by taking the metaid from the request object to determind the templatefolder. Will by default handle maximum 3 servletadresses. */ public void sendHtml (HttpServletRequest req, HttpServletResponse res, VariableManager vm, String htmlFile) throws ServletException, IOException { imcode.server.User user = getUserObj(req,res) ; // RmiConf rmi = new RmiConf(user) ; String metaId = this.getMetaId(req) ; if (metaId == null) { log("NO metaid could be found in the passed request object") ; String header = "Chat servlet. " ; ChatError err = new ChatError(req,res,header,5) ; return ; } // Lets get serverinformation String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; String confPoolServer = Utility.getDomainPref("chat_server",host) ; // This is the old version, which was ok before the double server installation // Lets get the TemplateFolder and the foldername used for this certain metaid // String templateLib = this.getExternalTemplateFolder(imcServer, metaId) ; // log("TemplateLib: " + templateLib) ; // Lets get the path to the imagefolder. // String imagePath = servletPath + this.getExternalImageFolder(imcServer, metaId) ; // Lets get the TemplateFolder and the foldername used for this certain metaid String templateLib = this.getExternalTemplateFolder(req) ; //String templateLib = this.getExternalTemplateFolder(imcServer, metaId) ; //log("TemplateLib: " + templateLib) ; // Lets add 3 server hostadresses String servletPath = MetaInfo.getServletPath(req) ; // Lets get the path to the imagefolder. String imagePath = this.getExternalImageFolder(req) ; //log("ImagePath: " + imagePath) ; VariableManager adminButtonVM = new VariableManager(); adminButtonVM.addProperty( "IMAGE_URL", imagePath); adminButtonVM.addProperty( "SERVLET_URL", servletPath); adminButtonVM.addProperty( "ADMIN_LINK_HTML", vm.getProperty( "ADMIN_LINK_HTML" ) ); //log("vm: " + vm.toString()) ; VariableManager unAdminButtonVM = new VariableManager(); unAdminButtonVM.addProperty( "IMAGE_URL", imagePath); unAdminButtonVM.addProperty( "SERVLET_URL", servletPath); unAdminButtonVM.addProperty( "UNADMIN_LINK_HTML", vm.getProperty("UNADMIN_LINK_HTML")); vm.addProperty("IMAGE_URL", imagePath); vm.addProperty("SERVLET_URL", servletPath); //String adminBtn = this.getAdminButtonLink( req, user, adminButtonVM ) ; String adminBtn = this.getAdminButtonLink( req, user, adminButtonVM ) ; vm.addProperty("CONF_ADMIN_LINK", adminBtn); // log("before UNadminBUttonlink: " + imagePath) ; String unAdminBtn = this.getUnAdminButtonLink(req, user, unAdminButtonVM) ; vm.addProperty("CONF_UNADMIN_LINK", unAdminBtn); // log("Before HTmlgenerator: ") ; HtmlGenerator htmlObj = new HtmlGenerator(templateLib, htmlFile) ; String html = htmlObj.createHtmlString(vm,req) ; //log("Before sendToBrowser: ") ; htmlObj.sendToBrowser(req,res,html) ; //log("after sendToBrowser: ") ; } /** Log function. Logs the message to the log file and console */ public void log(String msg) { super.log(msg) ; System.out.println("Chat: " + msg) ; } /** Date function. Returns the current date and time in the swedish style */ public static String getDateToday() { java.util.Calendar cal = java.util.Calendar.getInstance() ; String year = Integer.toString(cal.get(Calendar.YEAR)) ; int month = Integer.parseInt(Integer.toString(cal.get(Calendar.MONTH))) + 1; int day = Integer.parseInt(Integer.toString(cal.get(Calendar.DAY_OF_MONTH))) ; int hour = Integer.parseInt(Integer.toString(cal.get(Calendar.HOUR_OF_DAY))) ; int min = Integer.parseInt(Integer.toString(cal.get(Calendar.MINUTE))) ; String dateToDay = year ; dateToDay += "-" ; dateToDay += month < 10 ? "0" + Integer.toString(month) : Integer.toString(month) ; dateToDay += "-" ; dateToDay += day < 10 ? "0" + Integer.toString(day) : Integer.toString(day) ; return dateToDay ; } /** Date function. Returns the current time in the swedish style */ public static String getTimeNow() { java.util.Calendar cal = java.util.Calendar.getInstance() ; int hour = Integer.parseInt(Integer.toString(cal.get(Calendar.HOUR_OF_DAY))) ; int min = Integer.parseInt(Integer.toString(cal.get(Calendar.MINUTE))) ; int sec = Integer.parseInt(Integer.toString(cal.get(Calendar.SECOND))) ; String timeNow = "" ; timeNow += hour < 10 ? "0" + Integer.toString(hour) : Integer.toString(hour) ; timeNow += ":" ; timeNow += min < 10 ? "0" + Integer.toString(min) : Integer.toString(min) ; timeNow += ":" ; timeNow += sec < 10 ? "0" + Integer.toString(sec) : Integer.toString(sec) ; // timeNow += ".000" ; return timeNow ; } /** Converts array to vector */ public Vector convert2Vector(String[] arr) { Vector rolesV = new Vector() ; for(int i = 0; i<arr.length; i++) rolesV.add(arr[i]) ; return rolesV ; } /** Creates Sql characters. Encapsulates a string with ' ' signs. And surrounding Space. Example. this.sqlChar("myString") --> " 'myString' " */ public static String sqlChar(String s) { return " '" + s + "' " ; } /** Creates Sql characters. Encapsulates a string with ' ' signs. + an comma. And surrounding space. Example. this.sqlP("myString") --> " 'myString', " */ public static String sqlPDelim(String s) { return " '" + s + "', " ; } /** Creates Sql characters. Encapsulates a string with ' ' signs. And surrounding Space. Example. this.sqlP("myString") --> " 'myString' " */ public static String sqlP(String s) { return " '" + s + "' " ; } /** Adds a delimiter to the end of the string. Example. this.sqlDelim("myString") --> "myString, " */ public static String sqlDelim(String s) { return s + ", " ; } /** Prepare user for the conference **/ public boolean prepareUserForChat(HttpServletRequest req, HttpServletResponse res, Properties params, String loginUserId) throws ServletException, IOException { // Lets get the user object imcode.server.User user = this.getUserObj(req,res) ; if(user == null) return false ; // Lets get userparameters Properties userParams = this.getUserParameters(user) ; String metaId = params.getProperty("META_ID") ; RmiConf rmi = new RmiConf(user) ; // Lets get serverinformation String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; String ChatPoolServer = Utility.getDomainPref("chat_server",host) ; // Ok, Lets prepare the user for the conference. // Lets get his lastLoginDate and update it to today String sqlStoredProc = "GetLastLoginDate2 " + metaId + ", " + loginUserId ; String lastLoginDate = rmi.execSqlProcedureStr(ChatPoolServer, sqlStoredProc) ; String firstName = "" ; String lastName = "" ; // Ok, if lastlogindate is null, then it has to be the a user who has logged in // to the system and comes here to the conference for the first time // Lets add the user to conference db. if(lastLoginDate == null) { log("Ok, det r frsta gngen anvndaren r hr.") ; firstName = userParams.getProperty("FIRST_NAME") ; lastName = userParams.getProperty("LAST_NAME") ; String firstTimeInChatSql = "ChatUsersAdd " + loginUserId + ", " + metaId + ", '"; firstTimeInChatSql += firstName + "', '" + lastName + "'" ; log("AddExistingUserToChat: " + firstTimeInChatSql) ; rmi.execSqlUpdateQuery(ChatPoolServer, firstTimeInChatSql) ; // Ok, try to get the lastLoginDate now and validate it log("Ok, nu frsker vi hmta lastlogindate igen") ; lastLoginDate = rmi.execSqlProcedureStr(ChatPoolServer, sqlStoredProc) ; if(lastLoginDate == null) { String header = "ChatManager servlet. " ; ChatError err = new ChatError(req,res,header,30) ; log(header + err.getErrorMsg()) ; return false; } // End lastLoginCheck // Exta add 2000-09-14, Lets set the lastlogindate in the users // object to an old date so all discussions will have a new flag // so all flags will be shown lastLoginDate = "1997-01-01 00:00" ; } else { // Ok, the user has logged in to the conference by the loginpage // for the conference, he has a logindate. Lets get his names // Lets get the users first and last names String sqlName = "GetChatLoginNames " + metaId +", "+ loginUserId +", "+ 1 ; firstName = (String) rmi.execSqlProcedureStr(ChatPoolServer, sqlName ) ; sqlName = "GetChatLoginNames " + metaId +", "+ loginUserId +", "+ 2 ; lastName = (String) rmi.execSqlProcedureStr(ChatPoolServer, sqlName ) ; } // end else // Lets update his logindate and usernames String sqlQuest = "ChatUsersUpdate " + metaId +", "+ loginUserId +", '" ; sqlQuest += firstName + "', '" + lastName + "'" ; // log("Update users info in db: " + sqlQuest) ; rmi.execSqlUpdateQuery(ChatPoolServer, sqlQuest) ; // Lets store some values in his session object HttpSession session = req.getSession(false) ; if (session != null) { session.putValue("Chat.meta_id", params.getProperty("META_ID")) ; session.putValue("Chat.parent_meta_id", params.getProperty("PARENT_META_ID")) ; session.putValue("Chat.cookie_id", params.getProperty("COOKIE_ID")) ; session.putValue("Chat.viewedDiscList", new Properties()) ; session.putValue("Chat.last_login_date", lastLoginDate); session.putValue("Chat.user_id", loginUserId) ; session.putValue("Chat.disc_index", "0"); // Ok, we need to catch a forum_id. Lets get the first one for this meta_id. // if not a forumid exists, the sp will return -1 rmi = new RmiConf(user) ; String aForumId = rmi.execSqlProcedureStr(ChatPoolServer, "GetFirstForum " + params.getProperty("META_ID")) ; session.putValue("Chat.forum_id", aForumId) ; // Ok, Lets get the last discussion in that forum String aDiscId = rmi.execSqlProcedureStr(ChatPoolServer, "GetLastDiscussionId " + params.getProperty("META_ID") + ", " + aForumId) ; // Lets get the lastdiscussionid for that forum // if not a aDiscId exists, then the sp will return -1 session.putValue("Chat.disc_id", aDiscId) ; String url = MetaInfo.getServletPath(req) ; url += "ChatViewer" ; // this.log("Redirects to:" + url) ; res.sendRedirect(url) ; return true; } return false ; } // End prepare user for conference /** Gives the folder where All the html templates for a language are located. This method will call its helper method getTemplateLibName to get the name of the folder which contains the templates for a certain meta id */ public String getExternalImageFolder (HttpServletRequest req) throws ServletException, IOException { String metaId = this.getMetaId(req) ; if( metaId == null) { log("No meta_id could be found! Error in Chat.class") ; return "No meta_id could be found!" ; } // Lets get serverinformation String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; String confPoolServer = Utility.getDomainPref("chat_server",host) ; String extFolder = this.getExternalImageFolder(imcServer, metaId) ; return extFolder += this.getTemplateLibName(confPoolServer, metaId) ; } /** Returns the folder where this templates are situated for a certain metaid. **/ protected String getExternalImageFolder(String server, String meta_id) throws ServletException, IOException { RmiConf rmi = new RmiConf() ; // Ok, Lets get the language for the system String imageLib = rmi.getExternalImageFolder(server, meta_id) ; // Lets get the foldername used for this meta id . Default is original //imageLib += this.getTemplateLibName(server, meta_id ) ; //log("ImageLib: " + imageLib) ; return imageLib ; } // End of getImageLibName /** Returns the foldername where the templates are situated for a certain metaid. **/ protected String getImageLibName(String server, String meta_id ) throws ServletException, IOException { String sqlQ = "GetTemplateLib " + meta_id ; String libName = "" + RmiConf.execSqlProcedureStr(server, sqlQ) + "/"; return libName ; } // End of getImageLibName /** Returns the foldername where the templates are situated for a certain metaid. **/ protected String getInternalImageFolder(String server) throws ServletException, IOException { return RmiConf.getInternalImageFolder(server) ; } // End of getInternalImageFolder /** * Checks whether or not the user is an administrator and * Creates the html code, used to view the adminimage and an appropriate link * to the adminservlet. * * @param reg requestobject * @param user userobject * @param adminButtonTags hashtabele of tags to replace * * @return returns string of html code for adminlink */ public String getAdminButtonLink(HttpServletRequest req,imcode.server.User user, VariableManager adminButtonVM ) throws ServletException, IOException { // Lets get serverinformation String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; String ChatPoolServer = Utility.getDomainPref("chat_server",host) ; String adminLink = "&nbsp;"; String metaId = getMetaId( req ); int intMetaId = Integer.parseInt( metaId ); //log("before getAdminRights") ; //lets generat adminbutton if user has administrator rights and rights to edit if ( userHasAdminRights( imcServer, intMetaId, user ) ) { //lets save tags we need later VariableManager adminLinkVM = new VariableManager(); adminLinkVM.addProperty( "SERVLET_URL", adminButtonVM.getProperty( "SERVLET_URL" ) ); String adminLinkFile = adminButtonVM.getProperty( "ADMIN_LINK_HTML" ); //lets create adminbuttonhtml String templateLib = this.getExternalTemplateFolder( req ); HtmlGenerator htmlObj = new HtmlGenerator( templateLib, this.ADMIN_BUTTON_TEMPLATE ); String adminBtn = htmlObj.createHtmlString( adminButtonVM, req ); //lets create adminlink adminLinkVM.addProperty( "ADMIN_BUTTON", adminBtn ); HtmlGenerator linkHtmlObj = new HtmlGenerator( templateLib, adminLinkFile ); adminLink = linkHtmlObj.createHtmlString( adminLinkVM, req ); } //log("After getAdminRights") ; return adminLink ; } // End CreateAdminHtml /** Checks whether or not the user is an administrator and Creates the html code, used to view the adminimage and an appropriate link to the adminservlet. */ public String getUnAdminButtonLink(HttpServletRequest req,imcode.server.User user, VariableManager unAdminButtonVM ) throws ServletException, IOException { // Lets get serverinformation String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; String ChatPoolServer = Utility.getDomainPref("conference_server",host) ; String unAdminLink = "&nbsp;"; String metaId = getMetaId(req); int intMetaId = Integer.parseInt( metaId ); //lets generat unadminbutton if user has administrator rights and rights to edit if ( userHasAdminRights( imcServer, intMetaId, user ) ) { //lets save tags we need later VariableManager unAdminLinkVM = new VariableManager(); unAdminLinkVM.addProperty( "SERVLET_URL", unAdminButtonVM.getProperty( "SERVLET_URL" ) ); String unAdminLinkFile = unAdminButtonVM.getProperty( "UNADMIN_LINK_HTML" ); //lets create unadminbuttonhtml String templateLib = this.getExternalTemplateFolder( req ); HtmlGenerator htmlObj = new HtmlGenerator( templateLib, this.UNADMIN_BUTTON_TEMPLATE ); String unAdminBtn = htmlObj.createHtmlString( unAdminButtonVM, req ); //lets create unadminlink unAdminLinkVM.addProperty( "UNADMIN_BUTTON", unAdminBtn ); HtmlGenerator linkHtmlObj = new HtmlGenerator( templateLib, unAdminLinkFile ); unAdminLink = linkHtmlObj.createHtmlString( unAdminLinkVM, req ); } return unAdminLink ; } // End CreateAdminHtml /** Examines a text, and watches for ' signs, which will extended with another ' sign */ public String verifySqlText(String str ) { StringBuffer buf = new StringBuffer(str) ; // log("Innan: " + str) ; char apostrof = '\'' ; for(int i = 0 ; i < buf.length() ; i++) { //log(""+ buf.charAt(i)) ; if (buf.charAt(i) == apostrof ) { buf.insert(i,apostrof) ; i+=1 ; } } str = buf.toString() ; // log("Efter: " + str) ; return str ; } // End CreateAdminHtml public Properties verifyForSql(Properties aPropObj) { // Ok, Lets find all apostrofes and if any,add another one Enumeration enumValues = aPropObj.elements() ; Enumeration enumKeys = aPropObj.keys() ; while((enumValues.hasMoreElements() && enumKeys.hasMoreElements())) { Object oKeys = (enumKeys.nextElement()) ; Object oValue = (enumValues.nextElement()) ; String theVal = oValue.toString() ; String theKey = oKeys.toString() ; aPropObj.setProperty(theKey, verifySqlText(theVal)) ; } // log(aPropObj.toString()) ; return aPropObj ; } // verifyForSql public String props2String(Properties p) { Enumeration enumValues = p.elements() ; Enumeration enumKeys = p.keys() ; String aLine = ""; while((enumValues.hasMoreElements() && enumKeys.hasMoreElements())) { String oKeys = (String) (enumKeys.nextElement()) ; String oValue = (String) (enumValues.nextElement()) ; if(oValue == null) { oValue = "NULL" ; } aLine += oKeys.toString() + "=" + oValue.toString() + '\n' ; } return aLine ; } /** * checks if user is authorized * @param req * @param res is used if error (send user to conference_starturl ) * @param user */ //anvnds av ChatViewer protected boolean isUserAuthorized( HttpServletRequest req, HttpServletResponse res, imcode.server.User user ) throws ServletException, IOException { // Lets get serverinformation String host = req.getHeader( "Host" ) ; String imcServer = Utility.getDomainPref( "userserver", host ) ; HttpSession session = req.getSession( true ); //lets get if user authorized or not boolean authorized = true; //OBS "Chat.meta_id" ska bytas ut mot en konstant senare String stringMetaId = (String)session.getValue( "Chat.meta_id" ); if ( stringMetaId == null ) { authorized = false; //lets send unauthorized users out String serverName = MetaInfo.getServerName(req) ; String startUrl = RmiConf.getLoginUrl(host) ; res.sendRedirect(serverName + startUrl) ; } else { int metaId = Integer.parseInt( stringMetaId ); authorized = isUserAuthorized( req, res, metaId, user ); } return authorized; } /** * checks if user is authorized * @param req is used for collecting serverinfo and session * @param res is used if error (send user to conference_starturl ) * @param metaId conference metaId * @param user */ protected boolean isUserAuthorized( HttpServletRequest req, HttpServletResponse res, int metaId, imcode.server.User user ) throws ServletException, IOException { // Lets get serverinformation String host = req.getHeader( "Host" ) ; String imcServer = Utility.getDomainPref( "userserver", host ) ; HttpSession session = req.getSession( true ); //is user authorized? boolean authorized = IMCServiceRMI.checkDocRights( imcServer, metaId, user ); //lets send unauthorized users out if ( !authorized ) { String serverName = MetaInfo.getServerName(req) ; String startUrl = RmiConf.getLoginUrl(host) ; res.sendRedirect(serverName + startUrl) ; } return authorized; } /** * check if user has right to edit * @param imcServer rmi * @param metaId metaId for conference * @param user */ protected boolean userHasRightToEdit( String imcServer, int metaId, imcode.server.User user ) throws java.io.IOException { return ( IMCServiceRMI.checkDocRights( imcServer, metaId, user ) && IMCServiceRMI.checkDocAdminRights( imcServer, metaId, user ) ); } /** * check if user is admin and has rights to edit * @param imcServer rmi * @param metaId metaId for conference * @param user */ protected boolean userHasAdminRights( String imcServer, int metaId, imcode.server.User user ) throws java.io.IOException { return ( IMCServiceRMI.checkDocAdminRights( imcServer, metaId, user ) && IMCServiceRMI.checkDocAdminRights( imcServer, metaId, user, 65536 ) ); } /** *checks if the chatobject exists or if it has to bee created *@param chatId - the key to identify the chat *@return true if one exists */ public boolean checkChat(String chatId) { return _allChats.containsKey(chatId); } /** *adds a chatobject into a global HashMap *@param chatId - a string representation of the key *@param theChat - the chat object too be stored *@return true if ok, if there is a key whit the key false is returned */ public boolean addChat(String chatId, Chat theChat) { if ( !checkChat(chatId)) { _allChats.put(chatId, theChat); return true; }else { return false; } } /** *removes a chat object *@param chatId - the key of the chat to remove */ public void removeChat(String chatId) { _allChats.remove(chatId); } /** *gets a chat *@param chatId - the key of the chat to get *@return The wanted Chat or null if there isn't anyone found */ public Chat getChat(String chatId) { return (Chat) _allChats.get(chatId); } } // End class
package to.etc.domui.component.lookup; import to.etc.domui.component.input.*; import to.etc.domui.component.meta.*; import to.etc.domui.dom.html.*; import to.etc.webapp.query.*; @SuppressWarnings("unchecked") final class LookupFactoryString implements ILookupControlFactory { @Override public <X extends IInputNode< ? >> int accepts(final SearchPropertyMetaModel spm, final X control) { if(control != null) { if(!(control instanceof Text< ? >)) return -1; Text< ? > t = (Text< ? >) control; if(t.getInputClass() != String.class) return -1; } return 1; // Accept all properties (will fail on incompatible ones @ input time) } @SuppressWarnings("rawtypes") @Override public <X extends IInputNode< ? >> ILookupControlInstance createControl(final SearchPropertyMetaModel spm, final X control) { final PropertyMetaModel pmm = MetaUtils.getLastProperty(spm); Class< ? > iclz = pmm.getActualType(); //-- Boolean/boolean types? These need a tri-state checkbox if(iclz == Boolean.class || iclz == Boolean.TYPE) { throw new IllegalStateException("I need a tri-state checkbox component to handle boolean lookup thingies."); } //-- Treat everything else as a String using a converter. final Text< ? > txt = new Text(iclz); if(pmm.getDisplayLength() > 0) { int sz = pmm.getDisplayLength(); if(sz > 40) sz = 40; txt.setSize(sz); } else { //-- We must decide on a length.... int sz = 0; if(pmm.getLength() > 0) { sz = pmm.getLength(); if(sz > 40) sz = 40; } if(sz != 0) txt.setSize(sz); } if(pmm.getConverter() != null) txt.setConverter(pmm.getConverter()); if(pmm.getLength() > 0) txt.setMaxLength(pmm.getLength()); String hint = MetaUtils.findHintText(spm); if(hint != null) txt.setTitle(hint); //-- Converter thingy is known. Now add a return new AbstractLookupControlImpl(txt) { @Override public AppendCriteriaResult appendCriteria(QCriteria crit) throws Exception { Object value = null; try { value = txt.getValue(); } catch(Exception x) { return AppendCriteriaResult.INVALID; // Has validation error -> exit. } if(value == null || (value instanceof String && ((String) value).trim().length() == 0)) return AppendCriteriaResult.EMPTY; // Is okay but has no data // FIXME Handle minimal-size restrictions on input (search field metadata //-- Put the value into the criteria.. if(value instanceof String) { String str = (String) value; str = str.trim().replace("*", "%") + "%"; crit.ilike(spm.getPropertyName(), str); } else { crit.eq(spm.getPropertyName(), value); // property == value } return AppendCriteriaResult.VALID; } }; } }
package io.lumify.reindexmr; import io.lumify.core.util.LumifyLogger; import io.lumify.core.util.LumifyLoggerFactory; import org.apache.hadoop.mapreduce.Mapper; import org.securegraph.Authorizations; import org.securegraph.Element; import org.securegraph.GraphFactory; import org.securegraph.accumulo.AccumuloAuthorizations; import org.securegraph.accumulo.AccumuloGraph; import org.securegraph.accumulo.mapreduce.SecureGraphMRUtils; import org.securegraph.util.MapUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class ReindexMRMapper extends Mapper<String, Element, Object, Element> { private static final LumifyLogger LOGGER = LumifyLoggerFactory.getLogger(ReindexMRMapper.class); private static final int BATCH_SIZE = 100; private AccumuloGraph graph; private Authorizations authorizations; private List<Element> elementCache = new ArrayList<Element>(BATCH_SIZE); @Override protected void setup(Context context) throws IOException, InterruptedException { super.setup(context); LOGGER.info("setup: " + toString(context.getInputSplit().getLocations())); Map configurationMap = SecureGraphMRUtils.toMap(context.getConfiguration()); this.graph = (AccumuloGraph) new GraphFactory().createGraph(MapUtils.getAllWithPrefix(configurationMap, "graph")); this.authorizations = new AccumuloAuthorizations(context.getConfiguration().getStrings(SecureGraphMRUtils.CONFIG_AUTHORIZATIONS)); } private String toString(String[] locations) { StringBuilder result = new StringBuilder(); for (int i = 0; i < locations.length; i++) { if (i > 0) { result.append(", "); } result.append(locations[i]); } return result.toString(); } @Override protected void cleanup(Context context) throws IOException, InterruptedException { writeCache(); LOGGER.info("cleanup"); graph.shutdown(); super.cleanup(context); } @Override protected void map(String rowKey, Element element, Context context) throws IOException, InterruptedException { if (element == null) { return; } context.setStatus("Element Id: " + element.getId()); elementCache.add(element); if (elementCache.size() >= BATCH_SIZE) { writeCache(); } } private void writeCache() { if (elementCache.size() == 0) { return; } try { graph.getSearchIndex().addElements(graph, elementCache, authorizations); } catch (Throwable ex) { LOGGER.error("Could not add elements", ex); } elementCache.clear(); } }
public class Hello { // TODO: no code for initialize variables private int i = maybe("i") {1, 2, 3}; private Hello self = maybe("self") {new Hello()}; public static String getLabel(String label) { return "" + label; } public static void maybeVariable() { // DONE: can indentify below. // DONE: implement this. // int b = maybe("b") {10, 2, 3}, c = maybe("c") {3, 2, 1}, d = maybe("d") {4, 5, 6}, e = 2; // int b = maybe ("b") {1, 2, 3}; // // TODO: pass init checker // System.out.println(b); // DONE: implement mechanism // DONE: fix bug, maybe expression can't be visitChild int a = 1; String label = "a"; // DONE: fix edu.buffalo.cse.blue.maybe.ast.MaybeLocalAssign_c cannot be cast to polyglot.ast.Assign a = maybe(label) {1, 2, 3}; a = maybe(getLabel(label)) {1, 2, 3}; a = maybe(label + label) {1, 2, 3}; a = maybe(label + "a") {1, 2, 3}; // DONE: syntax error prompt // a = maybe(label) {}; System.out.println(a); String str = ""; str = maybe("str") {"1", "2"}; a = maybe("a") {1, 2, 3}; // DONE: fix edu.buffalo.cse.blue.maybe.ast.MaybeLocalAssign_c cannot be cast to polyglot.ast.Assign // DONE: The += operator must have numeric operands. // DONE: use real typeCheck in MaybeAssignExt a *= maybe("a") {1, 2, 3}; a /= maybe("a") {1, 2, 3}; a %= maybe("a") {1, 2, 3}; a += maybe("a") {1, 2, 3}; a -= maybe("a") {1, 2, 3}; a <<= maybe("a") {1, 2, 3}; a >>= maybe("a") {1, 2, 3}; a >>>= maybe("a") {1, 2, 3}; a &= maybe("a") {1, 2, 3}; a ^= maybe("a") {1, 2, 3}; a |= maybe("a") {1, 2, 3}; int[] array = new int[3]; array = new int[]{1, 2, 3}; // TODO: syntax error // array = maybe("array") {{1}, {2}, {3}}; // TODO: error below array[0] = maybe("array") {1, 2, 3}; } public static void main(String[] args) { maybeVariable(); String label = "one alternative "; maybe (label) { System.out.println(label); } label = "Two alternatives "; maybe (label) { System.out.println(label + "0"); } or { System.out.println(label + "1"); } label = "Multiple alternatives "; maybe (label) { System.out.println(label + "0"); } or { System.out.println(label + "1"); } or { System.out.println(label + "2"); } or { System.out.println(label + "3"); } or { System.out.println(label + "4"); } label = "Nested maybe statements "; String level = "levels "; int l = 0; maybe (label) { maybe (level) { System.out.println(label + level + l + " 0"); } or { System.out.println(label + level + l + " 1"); } } or { l++; maybe (level) { System.out.println(label + level + l + " 0"); } or { System.out.println(label + level + l + " 1"); } } // if (false) { // } else { // maybe ("3") { // int a = 0; // int b = 1; // int c = 2; System.out.println("Hello world!"); } }
package credentials.idemix; import java.math.BigInteger; import java.util.HashMap; import java.util.Iterator; import java.util.List; import net.sourceforge.scuba.smartcards.CardService; import net.sourceforge.scuba.smartcards.CardServiceException; import service.IdemixService; import service.IdemixSmartcard; import service.ProtocolCommand; import service.ProtocolResponses; import com.ibm.zurich.idmx.issuance.Issuer; import com.ibm.zurich.idmx.issuance.Message; import com.ibm.zurich.idmx.showproof.Proof; import com.ibm.zurich.idmx.showproof.Verifier; import com.ibm.zurich.idmx.utils.SystemParameters; import credentials.Attributes; import credentials.BaseCredentials; import credentials.CredentialsException; import credentials.Nonce; import credentials.idemix.spec.IdemixIssueSpecification; import credentials.idemix.spec.IdemixVerifySpecification; import credentials.spec.IssueSpecification; import credentials.spec.VerifySpecification; /** * An Idemix specific implementation of the credentials interface. */ public class IdemixCredentials extends BaseCredentials { IdemixService service = null; public IdemixCredentials() { // TODO } public IdemixCredentials(CardService cs) { super(cs); } /** * Issue a credential to the user according to the provided specification * containing the specified values. * * @param specification of the issuer and the credential to be issued. * @param values to be stored in the credential. * @throws CredentialsException if the issuance process fails. */ @Override public void issue(IssueSpecification specification, Attributes values) throws CredentialsException { IdemixIssueSpecification spec = castIssueSpecification(specification); // Initialise the issuer Issuer issuer = new Issuer(spec.getIssuerKey(), spec.getIssuanceSpec(), null, null, spec.getValues(values)); // Initialise the recipient try { service.open(); service.setIssuanceSpecification(spec.getIssuanceSpec()); service.setAttributes(spec.getIssuanceSpec(), spec.getValues(values)); } catch (CardServiceException e) { throw new CredentialsException("Failed to issue the credential (SCUBA)"); } // Issue the credential Message msgToRecipient1 = issuer.round0(); if (msgToRecipient1 == null) { throw new CredentialsException("Failed to issue the credential (0)"); } Message msgToIssuer1 = service.round1(msgToRecipient1); if (msgToIssuer1 == null) { throw new CredentialsException("Failed to issue the credential (1)"); } Message msgToRecipient2 = issuer.round2(msgToIssuer1); if (msgToRecipient2 == null) { throw new CredentialsException("Failed to issue the credential (2)"); } service.round3(msgToRecipient2); } /** * Get a blank IssueSpecification matching this Credentials provider. * * @return a blank specification matching this provider. */ public IssueSpecification issueSpecification() { return new IdemixIssueSpecification(); } /** * Verify a number of attributes listed in the specification. * * @param specification of the credential and attributes to be verified. * @return the attributes disclosed during the verification process or null * if verification failed * @throws CredentialsException */ public Attributes verify(VerifySpecification specification) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); setupService(spec); // Get a nonce from the verifier BigInteger nonce = Verifier.getNonce( spec.getProofSpec().getGroupParams().getSystemParams()); // Initialise the prover try { service.open(); } catch (CardServiceException e) { throw new CredentialsException("Failed to verify the attributes (SCUBA)"); } // Construct the proof Proof proof = service.buildProof(nonce, spec.getProofSpec()); // Initialise the verifier and verify the proof Verifier verifier = new Verifier(spec.getProofSpec(), proof, nonce); if (!verifier.verify()) { return null; } // Return the attributes that have been revealed during the proof Attributes attributes = new Attributes(); HashMap<String, BigInteger> values = verifier.getRevealedValues(); Iterator<String> i = values.keySet().iterator(); while (i.hasNext()) { String id = i.next(); attributes.add(id, values.get(id).toByteArray()); } return attributes; } /** * Get a blank VerifySpecification matching this Credentials provider. * TODO: proper implementation or remove it * * @return a blank specification matching this provider. */ @Override public VerifySpecification verifySpecification() { return null; } @Override public List<ProtocolCommand> requestProofCommands( VerifySpecification specification, Nonce nonce) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); IdemixNonce n = castNonce(nonce); return IdemixSmartcard.buildProofCommands(n.getNonce(), spec.getProofSpec(), spec.getIdemixId()); } @Override public Attributes verifyProofResponses(VerifySpecification specification, Nonce nonce, ProtocolResponses responses) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); IdemixNonce n = castNonce(nonce); // Create the proof Proof proof = IdemixSmartcard.processBuildProofResponses(responses, spec.getProofSpec()); // Initialize the verifier and verify the proof Verifier verifier = new Verifier(spec.getProofSpec(), proof, n.getNonce()); if (!verifier.verify()) { return null; } // Return the attributes that have been revealed during the proof Attributes attributes = new Attributes(); HashMap<String, BigInteger> values = verifier.getRevealedValues(); Iterator<String> i = values.keySet().iterator(); while (i.hasNext()) { String id = i.next(); attributes.add(id, values.get(id).toByteArray()); } return attributes; } @Override public Nonce generateNonce(VerifySpecification specification) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); SystemParameters sp = spec.getProofSpec().getGroupParams().getSystemParams(); BigInteger nonce = Verifier.getNonce(sp); return new IdemixNonce(nonce); } private static IdemixVerifySpecification castVerifySpecification( VerifySpecification spec) throws CredentialsException { if (!(spec instanceof IdemixVerifySpecification)) { throw new CredentialsException( "specification is not an IdemixVerifySpecification"); } return (IdemixVerifySpecification) spec; } private static IdemixIssueSpecification castIssueSpecification( IssueSpecification spec) throws CredentialsException { if (!(spec instanceof IdemixIssueSpecification)) { throw new CredentialsException( "specification is not an IdemixVerifySpecification"); } return (IdemixIssueSpecification) spec; } private static IdemixNonce castNonce(Nonce nonce) throws CredentialsException { if (!(nonce instanceof IdemixNonce)) { throw new CredentialsException("nonce is not an IdemixNonce"); } return (IdemixNonce) nonce; } private void setupService(IdemixVerifySpecification spec) { service = new IdemixService(cs, spec.getIdemixId()); } }
package credentials.idemix; import java.math.BigInteger; import java.util.HashMap; import java.util.Iterator; import org.ru.irma.api.tests.idemix.TestSetup; import net.sourceforge.scuba.smartcards.CardService; import net.sourceforge.scuba.smartcards.CardServiceException; import service.IdemixService; import service.IdemixSmartcard; import service.ProtocolCommands; import service.ProtocolResponses; import com.ibm.zurich.idmx.issuance.Issuer; import com.ibm.zurich.idmx.issuance.Message; import com.ibm.zurich.idmx.showproof.Proof; import com.ibm.zurich.idmx.showproof.Verifier; import com.ibm.zurich.idmx.utils.SystemParameters; import credentials.Attributes; import credentials.BaseCredentials; import credentials.CredentialsException; import credentials.Nonce; import credentials.idemix.spec.IdemixIssueSpecification; import credentials.idemix.spec.IdemixVerifySpecification; import credentials.keys.PrivateKey; import credentials.spec.IssueSpecification; import credentials.spec.VerifySpecification; import credentials.util.Timestamp; /** * An Idemix specific implementation of the credentials interface. */ public class IdemixCredentials extends BaseCredentials { IdemixService service = null; public IdemixCredentials() { // TODO } public IdemixCredentials(CardService cs) { super(cs); } /** * Issue a credential to the user according to the provided specification * containing the specified values. * * @param specification * of the issuer and the credential to be issued. * @param values * to be stored in the credential. * @throws CredentialsException * if the issuance process fails. */ @Override public void issue(IssueSpecification specification, PrivateKey sk, Attributes values) throws CredentialsException { IdemixIssueSpecification spec = castIssueSpecification(specification); IdemixPrivateKey isk = castIdemixPrivateKey(sk); values.add("expiry", BigInteger.valueOf(Timestamp.getWeekOffset(52)).toByteArray()); setupService(spec); // Initialise the issuer Issuer issuer = new Issuer(isk.getIssuerKeyPair(), spec.getIssuanceSpec(), null, null, spec.getValues(values)); // Initialise the recipient try { service.open(); // FIXME: Change this! service.sendPin(TestSetup.DEFAULT_PIN); service.setIssuanceSpecification(spec.getIssuanceSpec()); service.setAttributes(spec.getIssuanceSpec(), spec.getValues(values)); } catch (CardServiceException e) { throw new CredentialsException( "Failed to issue the credential (SCUBA)"); } // Issue the credential Message msgToRecipient1 = issuer.round0(); if (msgToRecipient1 == null) { throw new CredentialsException("Failed to issue the credential (0)"); } Message msgToIssuer1 = service.round1(msgToRecipient1); if (msgToIssuer1 == null) { throw new CredentialsException("Failed to issue the credential (1)"); } Message msgToRecipient2 = issuer.round2(msgToIssuer1); if (msgToRecipient2 == null) { throw new CredentialsException("Failed to issue the credential (2)"); } service.round3(msgToRecipient2); } /** * Get a blank IssueSpecification matching this Credentials provider. * TODO: Proper implementation or remove it. * * @return a blank specification matching this provider. */ public IssueSpecification issueSpecification() { return null; } /** * Verify a number of attributes listed in the specification. * * @param specification * of the credential and attributes to be verified. * @return the attributes disclosed during the verification process or null * if verification failed * @throws CredentialsException */ public Attributes verify(VerifySpecification specification) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); setupService(spec); // Get a nonce from the verifier BigInteger nonce = Verifier.getNonce(spec.getProofSpec() .getGroupParams().getSystemParams()); // Initialise the prover try { service.open(); } catch (CardServiceException e) { throw new CredentialsException( "Failed to verify the attributes (SCUBA)"); } // Construct the proof Proof proof = service.buildProof(nonce, spec.getProofSpec()); if (proof == null) { throw new CredentialsException("Failed to generate proof."); } // Initialise the verifier and verify the proof Verifier verifier = new Verifier(spec.getProofSpec(), proof, nonce); if (!verifier.verify()) { return null; } // Return the attributes that have been revealed during the proof Attributes attributes = new Attributes(); HashMap<String, BigInteger> values = verifier.getRevealedValues(); Iterator<String> i = values.keySet().iterator(); while (i.hasNext()) { String id = i.next(); attributes.add(id, values.get(id).toByteArray()); } long expiryWeek = new BigInteger(1, attributes.get("expiry")).longValue(); if (expiryWeek <= Timestamp.getWeek()) { throw new CredentialsException("The credential has expired."); } return attributes; } /** * Get a blank VerifySpecification matching this Credentials provider. TODO: * proper implementation or remove it * * @return a blank specification matching this provider. */ @Override public VerifySpecification verifySpecification() { return null; } @Override public ProtocolCommands requestProofCommands( VerifySpecification specification, Nonce nonce) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); IdemixNonce n = castNonce(nonce); return IdemixSmartcard.buildProofCommands(n.getNonce(), spec.getProofSpec(), spec.getIdemixId()); } @Override public Attributes verifyProofResponses(VerifySpecification specification, Nonce nonce, ProtocolResponses responses) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); IdemixNonce n = castNonce(nonce); // Create the proof Proof proof = IdemixSmartcard.processBuildProofResponses(responses, spec.getProofSpec()); if (proof == null) { throw new CredentialsException("Failed to generate proof."); } // Initialize the verifier and verify the proof Verifier verifier = new Verifier(spec.getProofSpec(), proof, n.getNonce()); if (!verifier.verify()) { return null; } // Return the attributes that have been revealed during the proof Attributes attributes = new Attributes(); HashMap<String, BigInteger> values = verifier.getRevealedValues(); Iterator<String> i = values.keySet().iterator(); while (i.hasNext()) { String id = i.next(); attributes.add(id, values.get(id).toByteArray()); } return attributes; } /** * First part of issuance protocol. Not yet included in the interface as * this is subject to change. Most notably * - How do we integrate the issuer in this, I would guess the only state * in fact the nonce, so we could handle that a bit cleaner. Carrying around * the issuer object may not be the best solution * - We need to deal with the selectApplet and sendPinCommands better. * @throws CredentialsException */ public ProtocolCommands requestIssueRound1Commands( IssueSpecification ispec, Attributes attributes, Issuer issuer) throws CredentialsException { ProtocolCommands commands = new ProtocolCommands(); IdemixIssueSpecification spec = castIssueSpecification(ispec); commands.addAll(IdemixSmartcard.setIssuanceSpecificationCommands( spec.getIssuanceSpec(), spec.getIdemixId())); commands.addAll(IdemixSmartcard.setAttributesCommands( spec.getIssuanceSpec(), spec.getValues(attributes))); // Issue the credential Message msgToRecipient1 = issuer.round0(); if (msgToRecipient1 == null) { throw new CredentialsException("Failed to issue the credential (0)"); } commands.addAll(IdemixSmartcard.round1Commands(spec.getIssuanceSpec(), msgToRecipient1)); return commands; } /** * Second part of issuing. Just like the first part still in flux. Note how * we can immediately process the responses as well as create new commands. * * @throws CredentialsException */ public ProtocolCommands requestIssueRound3Commands(IssueSpecification ispec, Attributes attributes, Issuer issuer, ProtocolResponses responses) throws CredentialsException { IdemixIssueSpecification spec = castIssueSpecification(ispec); Message msgToIssuer = IdemixSmartcard.processRound1Responses(responses); Message msgToRecipient2 = issuer.round2(msgToIssuer); return IdemixSmartcard.round3Commands(spec.getIssuanceSpec(), msgToRecipient2); } @Override public Nonce generateNonce(VerifySpecification specification) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); SystemParameters sp = spec.getProofSpec().getGroupParams() .getSystemParams(); BigInteger nonce = Verifier.getNonce(sp); return new IdemixNonce(nonce); } private static IdemixVerifySpecification castVerifySpecification( VerifySpecification spec) throws CredentialsException { if (!(spec instanceof IdemixVerifySpecification)) { throw new CredentialsException( "specification is not an IdemixVerifySpecification"); } return (IdemixVerifySpecification) spec; } private static IdemixIssueSpecification castIssueSpecification( IssueSpecification spec) throws CredentialsException { if (!(spec instanceof IdemixIssueSpecification)) { throw new CredentialsException( "specification is not an IdemixVerifySpecification"); } return (IdemixIssueSpecification) spec; } private static IdemixNonce castNonce(Nonce nonce) throws CredentialsException { if (!(nonce instanceof IdemixNonce)) { throw new CredentialsException("nonce is not an IdemixNonce"); } return (IdemixNonce) nonce; } private IdemixPrivateKey castIdemixPrivateKey(PrivateKey sk) throws CredentialsException { if (!(sk instanceof IdemixPrivateKey)) { throw new CredentialsException( "PrivateKey is not an IdemixPrivateKey"); } return (IdemixPrivateKey) sk; } private void setupService(IdemixVerifySpecification spec) { service = new IdemixService(cs, spec.getIdemixId()); } private void setupService(IdemixIssueSpecification spec) { service = new IdemixService(cs, spec.getIdemixId()); } }
package de.onvif.soap.devices; import java.net.ConnectException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import javax.xml.soap.SOAPException; import org.onvif.ver10.device.wsdl.GetCapabilities; import org.onvif.ver10.device.wsdl.GetCapabilitiesResponse; import org.onvif.ver10.device.wsdl.GetDeviceInformation; import org.onvif.ver10.device.wsdl.GetDeviceInformationResponse; import org.onvif.ver10.device.wsdl.GetHostname; import org.onvif.ver10.device.wsdl.GetHostnameResponse; import org.onvif.ver10.device.wsdl.GetScopes; import org.onvif.ver10.device.wsdl.GetScopesResponse; import org.onvif.ver10.device.wsdl.GetServices; import org.onvif.ver10.device.wsdl.GetServicesResponse; import org.onvif.ver10.device.wsdl.GetSystemDateAndTime; import org.onvif.ver10.device.wsdl.GetSystemDateAndTimeResponse; import org.onvif.ver10.device.wsdl.GetUsers; import org.onvif.ver10.device.wsdl.GetUsersResponse; import org.onvif.ver10.device.wsdl.Service; import org.onvif.ver10.device.wsdl.SetHostname; import org.onvif.ver10.device.wsdl.SetHostnameResponse; import org.onvif.ver10.device.wsdl.SystemReboot; import org.onvif.ver10.device.wsdl.SystemRebootResponse; import org.onvif.ver10.media.wsdl.CreateProfile; import org.onvif.ver10.media.wsdl.CreateProfileResponse; import org.onvif.ver10.media.wsdl.GetProfile; import org.onvif.ver10.media.wsdl.GetProfileResponse; import org.onvif.ver10.media.wsdl.GetProfiles; import org.onvif.ver10.media.wsdl.GetProfilesResponse; import org.onvif.ver10.schema.Capabilities; import org.onvif.ver10.schema.Date; import org.onvif.ver10.schema.Profile; import org.onvif.ver10.schema.Scope; import org.onvif.ver10.schema.Time; import org.onvif.ver10.schema.User; import de.onvif.soap.OnvifDevice; import de.onvif.soap.SOAP; public class InitialDevices { private SOAP soap; private OnvifDevice onvifDevice; public InitialDevices(OnvifDevice onvifDevice) { this.onvifDevice = onvifDevice; this.soap = onvifDevice.getSoap(); } public java.util.Date getDate() { Calendar cal = null; GetSystemDateAndTimeResponse response = new GetSystemDateAndTimeResponse(); try { response = (GetSystemDateAndTimeResponse) soap.createSOAPDeviceRequest(new GetSystemDateAndTime(), response, false); } catch (SOAPException | ConnectException e) { e.printStackTrace(); return null; } Date date = response.getSystemDateAndTime().getUTCDateTime().getDate(); Time time = response.getSystemDateAndTime().getUTCDateTime().getTime(); cal = new GregorianCalendar(date.getYear(), date.getMonth() - 1, date.getDay(), time.getHour(), time.getMinute(), time.getSecond()); return cal.getTime(); } public GetDeviceInformationResponse getDeviceInformation() { GetDeviceInformation getHostname = new GetDeviceInformation(); GetDeviceInformationResponse response = new GetDeviceInformationResponse(); try { response = (GetDeviceInformationResponse) soap.createSOAPDeviceRequest(getHostname, response, true); } catch (SOAPException | ConnectException e) { e.printStackTrace(); return null; } return response; } public String getHostname() { GetHostname getHostname = new GetHostname(); GetHostnameResponse response = new GetHostnameResponse(); try { response = (GetHostnameResponse) soap.createSOAPDeviceRequest(getHostname, response, true); } catch (SOAPException | ConnectException e) { e.printStackTrace(); return null; } return response.getHostnameInformation().getName(); } public boolean setHostname(String hostname) { SetHostname setHostname = new SetHostname(); setHostname.setName(hostname); SetHostnameResponse response = new SetHostnameResponse(); try { response = (SetHostnameResponse) soap.createSOAPDeviceRequest(setHostname, response, true); } catch (SOAPException | ConnectException e) { e.printStackTrace(); return false; } return true; } public List<User> getUsers() { GetUsers getUsers = new GetUsers(); GetUsersResponse response = new GetUsersResponse(); try { response = (GetUsersResponse) soap.createSOAPDeviceRequest(getUsers, response, true); } catch (SOAPException | ConnectException e) { e.printStackTrace(); return null; } if (response == null) { return null; } return response.getUser(); } public Capabilities getCapabilities() throws ConnectException, SOAPException { GetCapabilities getCapabilities = new GetCapabilities(); GetCapabilitiesResponse response = new GetCapabilitiesResponse(); try { response = (GetCapabilitiesResponse) soap.createSOAPRequest(getCapabilities, response, onvifDevice.getDeviceUri(), false); } catch (SOAPException e) { throw e; } if (response == null) { return null; } return response.getCapabilities(); } public List<Profile> getProfiles() { GetProfiles request = new GetProfiles(); GetProfilesResponse response = new GetProfilesResponse(); try { response = (GetProfilesResponse) soap.createSOAPMediaRequest(request, response, true); } catch (SOAPException | ConnectException e) { e.printStackTrace(); return null; } if (response == null) { return null; } return response.getProfiles(); } public Profile getProfile(String profileToken) { GetProfile request = new GetProfile(); GetProfileResponse response = new GetProfileResponse(); request.setProfileToken(profileToken); try { response = (GetProfileResponse) soap.createSOAPMediaRequest(request, response, true); } catch (SOAPException | ConnectException e) { e.printStackTrace(); return null; } if (response == null) { return null; } return response.getProfile(); } public Profile createProfile(String name) { CreateProfile request = new CreateProfile(); CreateProfileResponse response = new CreateProfileResponse(); request.setName(name); try { response = (CreateProfileResponse) soap.createSOAPMediaRequest(request, response, true); } catch (SOAPException | ConnectException e) { e.printStackTrace(); return null; } if (response == null) { return null; } return response.getProfile(); } public List<Service> getServices(boolean includeCapability) { GetServices request = new GetServices(); GetServicesResponse response = new GetServicesResponse(); request.setIncludeCapability(includeCapability); try { response = (GetServicesResponse) soap.createSOAPDeviceRequest(request, response, true); } catch (SOAPException | ConnectException e) { e.printStackTrace(); return null; } if (response == null) { return null; } return response.getService(); } public List<Scope> getScopes() { GetScopes request = new GetScopes(); GetScopesResponse response = new GetScopesResponse(); try { response = (GetScopesResponse) soap.createSOAPMediaRequest(request, response, true); } catch (SOAPException | ConnectException e) { e.printStackTrace(); return null; } if (response == null) { return null; } return response.getScopes(); } public String reboot() { SystemReboot request = new SystemReboot(); SystemRebootResponse response = new SystemRebootResponse(); try { response = (SystemRebootResponse) soap.createSOAPMediaRequest(request, response, true); } catch (SOAPException | ConnectException e) { e.printStackTrace(); return null; } if (response == null) { return null; } return response.getMessage(); } }
package org.fusesource.tools.messaging.cnf.ui; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.fusesource.tools.messaging.IConstants; import org.fusesource.tools.messaging.MessageEvent; import org.fusesource.tools.messaging.cnf.model.BaseComponent; import org.fusesource.tools.messaging.cnf.model.BaseGroupComponent; import org.fusesource.tools.messaging.cnf.model.DataModelManager; import org.fusesource.tools.messaging.cnf.model.IModelConstants; import org.fusesource.tools.messaging.cnf.model.ListenerComponent; import org.fusesource.tools.messaging.cnf.model.Listeners; import org.fusesource.tools.messaging.cnf.model.ListenersRootComponent; import org.fusesource.tools.messaging.cnf.model.SenderComponent; import org.fusesource.tools.messaging.cnf.model.Senders; import org.fusesource.tools.messaging.cnf.model.SendersRootComponent; import org.fusesource.tools.messaging.core.IListener; import org.fusesource.tools.messaging.core.IMessageChangeListener; import org.fusesource.tools.messaging.core.ISender; /** * Content provider implementation for Messaging Project * * @author kiranb * */ public class MsgProjectContentProvider implements ITreeContentProvider { public static String SENDERS_TEXT = "Producers"; public static String LISTENERS_TEXT = "Consumers"; private StructuredViewer viewer; private MsgProjectChangeHandler changeHandler; private MessageChangeListener msgChangeListener; public MsgProjectContentProvider() { changeHandler = new MsgProjectChangeHandler(); msgChangeListener = new MessageChangeListener(); } public Object[] getChildren(Object parentElement) { if (parentElement instanceof IProject) { return getRootNodes((IProject) parentElement); } else if (parentElement instanceof SendersRootComponent) { return getSenderNodes((SendersRootComponent) parentElement); } else if (parentElement instanceof ListenersRootComponent) { return getListenerNodes((ListenersRootComponent) parentElement); } return IConstants.NO_CHILDREN; } private Object[] getRootNodes(IProject parentElement) { IFile sendersFile = ((IProject) parentElement) .getFile(IModelConstants.SENDERS_FILE_PATH); IFile listenersFile = ((IProject) parentElement) .getFile(IModelConstants.LISTENERS_FILE_PATH); return new Object[] { new SendersRootComponent(SENDERS_TEXT, sendersFile), new ListenersRootComponent(LISTENERS_TEXT, listenersFile) }; } private Object[] getSenderNodes(SendersRootComponent root) { Senders senders = (Senders) DataModelManager.getInstance().getModel( root.getFile()); if (senders == null) return IConstants.NO_CHILDREN; List<SenderComponent> senderNodes = new ArrayList<SenderComponent>(); for (Object object : senders.getChildren()) { senderNodes.add(new SenderComponent(root, (ISender) object)); } return senderNodes.toArray(); } private Object[] getListenerNodes(ListenersRootComponent root) { Listeners listeners = (Listeners) DataModelManager.getInstance() .getModel(root.getFile()); if (listeners == null) return IConstants.NO_CHILDREN; List<ListenerComponent> listenerNodes = new ArrayList<ListenerComponent>(); for (Object object : listeners.getChildren()) { IListener listener = (IListener) object; listenerNodes.add(new ListenerComponent(root, listener)); // TODO remove the old one?? listener.getMessagesManager().removeMessageChangeListener( msgChangeListener); listener.getMessagesManager().addMessageChangeListener( msgChangeListener); } root.setChildren(listenerNodes.toArray()); return listenerNodes.toArray(); } public Object getParent(Object element) { if (element instanceof BaseComponent) return ((BaseComponent) element).getParent(); else if (element instanceof BaseGroupComponent) { return ((BaseGroupComponent) element).getFile().getProject(); } return null; } public boolean hasChildren(Object element) { if (element instanceof SendersRootComponent || element instanceof ListenersRootComponent) { return true; } else if (element instanceof SenderComponent || element instanceof ListenerComponent) { return false; } return false; } public Object[] getElements(Object inputElement) { return IConstants.NO_CHILDREN; } public void dispose() { changeHandler.cleanUp(); } public void inputChanged(Viewer aViewer, Object oldInput, Object newInput) { viewer = (TreeViewer) aViewer; changeHandler.initViewer(viewer); } public Viewer getViewer() { return viewer; } class MessageChangeListener implements IMessageChangeListener { public void messageChangeEvent(MessageEvent me, int kind) { if (me != null) changeHandler.updateUI(me.getSource()); } public void messagesClearedEvent(List<MessageEvent> clearedMsgs) { if (clearedMsgs == null || clearedMsgs.size() == 0) return; MessageEvent messageEvent = clearedMsgs.get(0); changeHandler.updateUI(messageEvent.getSource()); } } }
package org.lamport.tla.toolbox.tool.tlc.ui.editor.page; import java.text.SimpleDateFormat; import java.util.List; import java.util.Vector; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.events.IHyperlinkListener; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.forms.widgets.TableWrapData; import org.eclipse.ui.forms.widgets.TableWrapLayout; import org.lamport.tla.toolbox.tool.tlc.output.data.CoverageInformationItem; import org.lamport.tla.toolbox.tool.tlc.output.data.ITLCModelLaunchDataPresenter; import org.lamport.tla.toolbox.tool.tlc.output.data.StateSpaceInformationItem; import org.lamport.tla.toolbox.tool.tlc.output.data.TLCModelLaunchDataProvider; import org.lamport.tla.toolbox.tool.tlc.output.source.TLCOutputSourceRegistry; import org.lamport.tla.toolbox.tool.tlc.ui.TLCUIActivator; import org.lamport.tla.toolbox.tool.tlc.ui.editor.part.ValidateableSectionPart; import org.lamport.tla.toolbox.tool.tlc.ui.preference.ITLCPreferenceConstants; import org.lamport.tla.toolbox.tool.tlc.ui.util.ActionClickListener; import org.lamport.tla.toolbox.tool.tlc.ui.util.DirtyMarkingListener; import org.lamport.tla.toolbox.tool.tlc.ui.util.FormHelper; import org.lamport.tla.toolbox.tool.tlc.ui.view.TLCErrorView; import org.lamport.tla.toolbox.tool.tlc.util.ModelHelper; import org.lamport.tla.toolbox.util.FontPreferenceChangeListener; import org.lamport.tla.toolbox.util.IHelpConstants; import org.lamport.tla.toolbox.util.UIHelper; /** * A page to display results of model checking (the "third tab" * of the model editor). * @author Simon Zambrovski * @version $Id$ */ public class ResultPage extends BasicFormPage implements ITLCModelLaunchDataPresenter { public static final String ID = "resultPage"; private static final String TOOLTIP = "Click on a row to go to action."; private Hyperlink errorStatusHyperLink; /** * UI elements */ private SourceViewer userOutput; private SourceViewer progressOutput; private SourceViewer expressionEvalResult; private SourceViewer expressionEvalInput; private Text startTimestampText; // startTime is provided by the TLCModelLaunchDataProvider's getStartTime() // method. private long startTime = 0; private Text finishTimestampText; private Text lastCheckpointTimeText; private Text coverageTimestampText; private Text currentStatusText; private Text fingerprintCollisionProbabilityText; private TableViewer coverage; private TableViewer stateSpace; // listener on changes to the tlc output font preference private FontPreferenceChangeListener fontChangeListener; // hyper link listener activated in case of errors protected IHyperlinkListener errorHyperLinkListener = new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { if (getConfig() != null) { try { ModelHelper.setOriginalTraceShown(getConfig(), true); } catch (CoreException e1) { TLCUIActivator.logError("Error setting the original trace to be shown.", e1); } TLCErrorView.updateErrorView(getConfig()); } } }; /** * Constructor for the page * @param editor */ public ResultPage(FormEditor editor) { super(editor, ID, "Model Checking Results"); this.helpId = IHelpConstants.RESULT_MODEL_PAGE; this.imagePath = "icons/full/choice_sc_obj.gif"; } /** * Will be called by the provider on data changes */ public void modelChanged(final TLCModelLaunchDataProvider dataProvider, final int fieldId) { UIHelper.runUIAsync(new Runnable() { public void run() { switch (fieldId) { case USER_OUTPUT: ResultPage.this.userOutput.setDocument(dataProvider.getUserOutput()); break; case PROGRESS_OUTPUT: ResultPage.this.progressOutput.setDocument(dataProvider.getProgressOutput()); break; case CONST_EXPR_EVAL_OUTPUT: ResultPage.this.expressionEvalResult.getTextWidget().setText(dataProvider.getCalcOutput()); break; case START_TIME: ResultPage.this.startTimestampText.setText(dataProvider.getStartTimestamp()); ResultPage.this.startTime = dataProvider.getStartTime(); break; case END_TIME: ResultPage.this.finishTimestampText.setText(dataProvider.getFinishTimestamp()); break; case LAST_CHECKPOINT_TIME: ResultPage.this.lastCheckpointTimeText.setText(dataProvider.getLastCheckpointTimeStamp()); break; case CURRENT_STATUS: ResultPage.this.currentStatusText.setText(dataProvider.getCurrentStatus()); break; case FINGERPRINT_COLLISION_PROBABILITY: ResultPage.this.fingerprintCollisionProbabilityText.setText(dataProvider.getFingerprintCollisionProbability()); break; case COVERAGE_TIME: ResultPage.this.coverageTimestampText.setText(dataProvider.getCoverageTimestamp()); break; case COVERAGE: ResultPage.this.coverage.setInput(dataProvider.getCoverageInfo()); break; case PROGRESS: ResultPage.this.stateSpace.setInput(dataProvider.getProgressInformation()); // The following code finds all the graph windows (shells) for this // model and calls redraw() and update() on them, which apparently is the // magic incantation to cause its listener to be called to issue the // necessary commands to redraw the data and then displays the result. String suffix = getGraphTitleSuffix(ResultPage.this); Shell[] shells = UIHelper.getCurrentDisplay().getShells(); for (int i = 0; i < shells.length; i++) { if (shells[i].getText().endsWith(suffix)) { shells[i].redraw(); shells[i].update(); System.out.println("Called redraw/update on shell number" + i); } } break; case ERRORS: String text; Color color; int errorCount = dataProvider.getErrors().size(); switch (errorCount) { case 0: text = TLCModelLaunchDataProvider.NO_ERRORS; color = TLCUIActivator.getColor(SWT.COLOR_BLACK); ResultPage.this.errorStatusHyperLink .removeHyperlinkListener(ResultPage.this.errorHyperLinkListener); break; case 1: text = "1 Error"; ResultPage.this.errorStatusHyperLink .addHyperlinkListener(ResultPage.this.errorHyperLinkListener); color = TLCUIActivator.getColor(SWT.COLOR_RED); break; default: text = String.valueOf(errorCount) + " Errors"; ResultPage.this.errorStatusHyperLink .addHyperlinkListener(ResultPage.this.errorHyperLinkListener); color = TLCUIActivator.getColor(SWT.COLOR_RED); break; } ResultPage.this.errorStatusHyperLink.setText(text); ResultPage.this.errorStatusHyperLink.setForeground(color); // update the error view TLCErrorView.updateErrorView(dataProvider.getConfig()); break; default: break; } // ResultPage.this.refresh(); } }); } /** * Gets the data provider for the current page */ public void loadData() throws CoreException { TLCModelLaunchDataProvider provider = TLCOutputSourceRegistry.getModelCheckSourceRegistry().getProvider( getConfig()); if (provider != null) { provider.setPresenter(this); } else { // no data provider reinit(); } // constant expression String expression = getConfig().getAttribute(MODEL_EXPRESSION_EVAL, EMPTY_STRING); expressionEvalInput.setDocument(new Document(expression)); } /** * Reinitialize the fields * has to be run in the UI thread */ private synchronized void reinit() { // TLCUIActivator.logDebug("Entering reinit()"); this.startTimestampText.setText(""); this.startTime = 0; this.finishTimestampText.setText(""); this.lastCheckpointTimeText.setText(""); this.currentStatusText.setText(TLCModelLaunchDataProvider.NOT_RUNNING); this.errorStatusHyperLink.setText(TLCModelLaunchDataProvider.NO_ERRORS); this.coverage.setInput(new Vector()); this.stateSpace.setInput(new Vector()); this.progressOutput.setDocument(new Document(TLCModelLaunchDataProvider.NO_OUTPUT_AVAILABLE)); this.userOutput.setDocument(new Document(TLCModelLaunchDataProvider.NO_OUTPUT_AVAILABLE)); // TLCUIActivator.logDebug("Exiting reinit()"); } /** * Dispose the page */ public void dispose() { /* * Remove graph windows raised for the page. */ String suffix = getGraphTitleSuffix(this); Shell[] shells = UIHelper.getCurrentDisplay().getShells(); for (int i = 0; i < shells.length; i++) { if (shells[i].getText().endsWith(suffix)) { shells[i].dispose(); } } JFaceResources.getFontRegistry().removeListener(fontChangeListener); TLCModelLaunchDataProvider provider = TLCOutputSourceRegistry.getModelCheckSourceRegistry().getProvider( getConfig()); if (provider != null) { provider.setPresenter(null); } super.dispose(); } protected void createBodyContent(IManagedForm managedForm) { int sectionFlags = Section.TITLE_BAR | Section.DESCRIPTION | Section.TREE_NODE | Section.EXPANDED | SWT.WRAP; int textFieldFlags = SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY | SWT.FULL_SELECTION | SWT.WRAP; FormToolkit toolkit = managedForm.getToolkit(); Composite body = managedForm.getForm().getBody(); TableWrapLayout layout = new TableWrapLayout(); layout.numColumns = 1; body.setLayout(layout); TableWrapData twd; Section section; GridData gd; // general section // There is no description line for this section, so it is // necessary to eliminate that bit in the style flags that // are passed in. If the bit were not changed to 0, an // extra empty line would appear below the title. section = FormHelper.createSectionComposite(body, "General", "" /* "The current progress of model-checking"*/, toolkit, sectionFlags & ~Section.DESCRIPTION, getExpansionListener()); twd = new TableWrapData(TableWrapData.FILL); twd.colspan = 1; section.setLayoutData(twd); Composite generalArea = (Composite) section.getClient(); generalArea.setLayout(new GridLayout()); Composite statusComposite = toolkit.createComposite(generalArea); statusComposite.setLayout(new GridLayout(2, false)); // start this.startTimestampText = FormHelper.createTextLeft("Start time:", statusComposite, toolkit); this.startTimestampText.setEditable(false); // elapsed time this.finishTimestampText = FormHelper.createTextLeft("End time:", statusComposite, toolkit); this.finishTimestampText.setEditable(false); // last checkpoint time this.lastCheckpointTimeText = FormHelper.createTextLeft("Last checkpoint time:", statusComposite, toolkit); this.lastCheckpointTimeText.setEditable(false); // current status this.currentStatusText = FormHelper.createTextLeft("Current status:", statusComposite, toolkit); this.currentStatusText.setEditable(false); this.currentStatusText.setText(TLCModelLaunchDataProvider.NOT_RUNNING); // errors // Label createLabel = // toolkit.createLabel(statusComposite, "Errors detected:"); // this.errorStatusHyperLink = toolkit.createHyperlink(statusComposite, "", SWT.RIGHT); this.errorStatusHyperLink = FormHelper.createHyperlinkLeft("Errors detected:", statusComposite, toolkit); // fingerprint collision probability this.fingerprintCollisionProbabilityText = FormHelper.createTextLeft("Fingerprint collision probability:", statusComposite, toolkit); this.fingerprintCollisionProbabilityText.setEditable(false); this.fingerprintCollisionProbabilityText.setText(""); // statistics section // There is no description line for this section, so it is // necessary to eliminate that bit in the style flags that // are passed in. If the bit were not changed to 0, an // extra empty line would appear below the title. section = FormHelper.createSectionComposite(body, "Statistics", "", /*"The current progress of model-checking",*/ toolkit, (sectionFlags | Section.COMPACT) & ~Section.DESCRIPTION, getExpansionListener()); twd = new TableWrapData(TableWrapData.FILL); twd.colspan = 1; section.setLayoutData(twd); Composite statArea = (Composite) section.getClient(); RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL); // rowLayout.numColumns = 2; statArea.setLayout(rowLayout); // progress stats createAndSetupStateSpace("State space progress (click column header for graph)", statArea, toolkit); // coverage stats createAndSetupCoverage("Coverage at", statArea, toolkit); // Calculator section // There is no description line for this section, so it is // necessary to eliminate that bit in the style flags that // are passed in. If the bit were not changed to 0, an // extra empty line would appear below the title. section = FormHelper.createSectionComposite(body, "Evaluate Constant Expression", "", toolkit, sectionFlags & ~Section.DESCRIPTION, getExpansionListener()); Composite resultArea = (Composite) section.getClient(); GridLayout gLayout = new GridLayout(2, false); gLayout.marginHeight = 0; resultArea.setLayout(gLayout); Composite expressionComposite = toolkit.createComposite(resultArea); expressionComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); gLayout = new GridLayout(1, false); gLayout.marginHeight = 0; gLayout.marginBottom = 5; expressionComposite.setLayout(gLayout); toolkit.createLabel(expressionComposite, "Expression: "); expressionEvalInput = FormHelper.createFormsSourceViewer(toolkit, expressionComposite, textFieldFlags); // We want the value section to get larger as the window // gets larger but not the expression section. Composite valueComposite = toolkit.createComposite(resultArea); valueComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); valueComposite.setLayout(gLayout); toolkit.createLabel(valueComposite, "Value: "); expressionEvalResult = FormHelper.createFormsOutputViewer(toolkit, valueComposite, textFieldFlags); // We dont want these items to fill excess // vertical space because then in some cases // this causes the text box to be extremely // tall instead of having a scroll bar. gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.minimumWidth = 500; gd.heightHint = 80; expressionEvalResult.getTextWidget().setLayoutData(gd); // The expression section should not grab excess horizontal // space because if this flag is set to true and the length // of the expression causes a vertical scroll bar to appear, // then when the model is run, the expression text box // will get wide enough to fit the entire expression on // one line instead of wrapping the text. gd = new GridData(SWT.FILL, SWT.FILL, false, false); gd.widthHint = 500; gd.heightHint = 80; expressionEvalInput.getTextWidget().setLayoutData(gd); // We want this font to be the same as the input. // If it was not set it would be the same as the font // in the module editor. expressionEvalResult.getTextWidget().setFont(JFaceResources.getTextFont()); expressionEvalInput.getTextWidget().setFont(JFaceResources.getTextFont()); // This is required to paint the borders of the text boxes // it must be called on the direct parent of the widget // with a border. There is a call of this methon in // FormHelper.createSectionComposite, but that is called // on the section which is not a direct parent of the // text box widget. toolkit.paintBordersFor(expressionComposite); toolkit.paintBordersFor(valueComposite); ValidateableSectionPart calculatorSectionPart = new ValidateableSectionPart(section, this, SEC_EXPRESSION); // This ensures that when the part is made dirty, the model // appears unsaved. managedForm.addPart(calculatorSectionPart); // This makes the widget unsaved when text is entered. expressionEvalInput.getTextWidget().addModifyListener(new DirtyMarkingListener(calculatorSectionPart, false)); getDataBindingManager().bindAttribute(MODEL_EXPRESSION_EVAL, expressionEvalInput, calculatorSectionPart); getDataBindingManager().bindSection(calculatorSectionPart, SEC_EXPRESSION, getId()); // output section section = FormHelper.createSectionComposite(body, "User Output", "TLC output generated by evaluating Print and PrintT expressions.", toolkit, sectionFlags, getExpansionListener()); Composite outputArea = (Composite) section.getClient(); outputArea.setLayout(new GridLayout()); // output viewer userOutput = FormHelper.createFormsOutputViewer(toolkit, outputArea, textFieldFlags); // We dont want this item to fill excess // vertical space because then in some cases // this causes the text box to be extremely // tall instead of having a scroll bar. gd = new GridData(SWT.FILL, SWT.LEFT, true, false); gd.heightHint = 300; gd.minimumWidth = 300; userOutput.getControl().setLayoutData(gd); userOutput.getControl().setFont(JFaceResources.getFont(ITLCPreferenceConstants.I_TLC_OUTPUT_FONT)); // progress section // There is no description line for this section, so it is // necessary to eliminate that bit in the style flags that // are passed in. If the bit were not changed to 0, an // extra empty line would appear below the title. section = FormHelper.createSectionComposite(body, "Progress Output", "", /* "The current progress of model-checking",*/ toolkit, sectionFlags & ~Section.DESCRIPTION, getExpansionListener()); section.setExpanded(false); Composite progressArea = (Composite) section.getClient(); progressArea = (Composite) section.getClient(); progressArea.setLayout(new GridLayout()); progressOutput = FormHelper.createFormsOutputViewer(toolkit, progressArea, textFieldFlags); // We dont want this item to fill excess // vertical space because then in some cases // this causes the text box to be extremely // tall instead of having a scroll bar. gd = new GridData(SWT.FILL, SWT.LEFT, true, false); gd.heightHint = 300; gd.minimumWidth = 300; progressOutput.getControl().setLayoutData(gd); progressOutput.getControl().setFont(JFaceResources.getFont(ITLCPreferenceConstants.I_TLC_OUTPUT_FONT)); Vector controls = new Vector(); controls.add(userOutput.getControl()); controls.add(progressOutput.getControl()); fontChangeListener = new FontPreferenceChangeListener(controls, ITLCPreferenceConstants.I_TLC_OUTPUT_FONT); JFaceResources.getFontRegistry().addListener(fontChangeListener); } /** * Save data back to model */ public void commit(boolean onSave) { String expression = this.expressionEvalInput.getDocument().get(); getConfig().setAttribute(MODEL_EXPRESSION_EVAL, expression); super.commit(onSave); } /** * Creates the state space table (initializes the {@link stateSpace} variable) * @param label * @param parent * @param toolkit * @return the constructed composite */ private Composite createAndSetupStateSpace(String label, Composite parent, FormToolkit toolkit) { Composite statespaceComposite = toolkit.createComposite(parent, SWT.WRAP); statespaceComposite.setLayout(new GridLayout(1, false)); toolkit.createLabel(statespaceComposite, label); Table stateTable = toolkit.createTable(statespaceComposite, SWT.MULTI | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.BORDER); GridData gd = new GridData(StateSpaceLabelProvider.MIN_WIDTH, 100); stateTable.setLayoutData(gd); stateTable.setHeaderVisible(true); stateTable.setLinesVisible(true); StateSpaceLabelProvider.createTableColumns(stateTable, this); // create the viewer this.stateSpace = new TableViewer(stateTable); // create list-based content provider this.stateSpace.setContentProvider(new IStructuredContentProvider() { public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public void dispose() { } public Object[] getElements(Object inputElement) { if (inputElement != null && inputElement instanceof List) { return ((List) inputElement).toArray(new Object[((List) inputElement).size()]); } return null; } }); this.stateSpace.setLabelProvider(new StateSpaceLabelProvider()); return statespaceComposite; } /** * Creates the coverage table (initializes the {@link coverageTimestamp} and {@link coverage} variables) * @param label * @param parent * @param toolkit * @return returns the containing composite */ private Composite createAndSetupCoverage(String label, Composite parent, FormToolkit toolkit) { Composite coverageComposite = toolkit.createComposite(parent, SWT.WRAP); coverageComposite.setLayout(new GridLayout(2, false)); GridData gd = new GridData(); toolkit.createLabel(coverageComposite, label); this.coverageTimestampText = toolkit.createText(coverageComposite, "", SWT.FLAT); this.coverageTimestampText.setEditable(false); gd = new GridData(); gd.minimumWidth = 200; gd.grabExcessHorizontalSpace = true; this.coverageTimestampText.setLayoutData(gd); final Table stateTable = toolkit.createTable(coverageComposite, SWT.MULTI | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.BORDER | SWT.VIRTUAL); gd = new GridData(CoverageLabelProvider.MIN_WIDTH, 100); gd.horizontalSpan = 2; stateTable.setLayoutData(gd); stateTable.setHeaderVisible(true); stateTable.setLinesVisible(true); stateTable.setToolTipText(TOOLTIP); CoverageLabelProvider.createTableColumns(stateTable); // create the viewer this.coverage = new TableViewer(stateTable); coverage.addSelectionChangedListener(new ActionClickListener()); // create list-based content provider this.coverage.setContentProvider(new IStructuredContentProvider() { public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public void dispose() { } public Object[] getElements(Object inputElement) { if (inputElement != null && inputElement instanceof List) { return ((List) inputElement).toArray(new Object[((List) inputElement).size()]); } return null; } }); this.coverage.setLabelProvider(new CoverageLabelProvider()); return coverageComposite; } /** * Returns the StateSpaceInformationItem objects currently being displayed in * the "State space progress" area, except in temporal order--that is, in the * opposite order from which they are displayed. * * @return */ public StateSpaceInformationItem[] getStateSpaceInformation() { List infoList = (List) stateSpace.getInput(); StateSpaceInformationItem[] result = new StateSpaceInformationItem[infoList.size()]; for (int i = 0; i < result.length; i++) { result[i] = (StateSpaceInformationItem) infoList.get(result.length - i - 1); } return result; } /** * Provides labels for the state space table */ static class StateSpaceLabelProvider extends LabelProvider implements ITableLabelProvider { public final static String[] columnTitles = new String[] { "Time", "Diameter", "States Found", "Distinct States", "Queue Size" }; public final static int[] columnWidths = { 120, 60, 80, 100, 80 }; public static final int MIN_WIDTH = columnWidths[0] + columnWidths[1] + columnWidths[2] + columnWidths[3] + columnWidths[4]; public final static int COL_TIME = 0; public final static int COL_DIAMETER = 1; public final static int COL_FOUND = 2; public final static int COL_DISTINCT = 3; public final static int COL_LEFT = 4; private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // $NON-NLS-1$ /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int) */ public Image getColumnImage(Object element, int columnIndex) { return null; } /** * @param stateTable */ public static void createTableColumns(Table stateTable, ResultPage page) { // create table headers for (int i = 0; i < columnTitles.length; i++) { TableColumn column = new TableColumn(stateTable, SWT.NULL); column.setWidth(columnWidths[i]); column.setText(columnTitles[i]); // The following statement attaches a listener to the column // header. See the ResultPageColumnListener comments. column.addSelectionListener(new ResultPageColumnListener(i, page)); } } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int) */ public String getColumnText(Object element, int columnIndex) { if (element instanceof StateSpaceInformationItem) { // the "N/A" values are used for simulation mode StateSpaceInformationItem item = (StateSpaceInformationItem) element; switch (columnIndex) { case COL_TIME: return sdf.format(item.getTime()); case COL_DIAMETER: if (item.getDiameter() >= 0) { return String.valueOf(item.getDiameter()); } else { return " } case COL_FOUND: return String.valueOf(item.getFoundStates()); case COL_DISTINCT: if (item.getDistinctStates() >= 0) { return String.valueOf(item.getDistinctStates()); } else { return " } case COL_LEFT: if (item.getLeftStates() >= 0) { return String.valueOf(item.getLeftStates()); } else { return " } } } return null; } } /** * Provides labels for the coverage table */ static class CoverageLabelProvider extends LabelProvider implements ITableLabelProvider { public final static String[] columnTitles = new String[] { "Module", "Location", "Count" }; public final static int[] columnWidths = { 80, 200, 80 }; public static final int MIN_WIDTH = columnWidths[0] + columnWidths[1] + columnWidths[2]; public final static int COL_MODULE = 0; public final static int COL_LOCATION = 1; public final static int COL_COUNT = 2; /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int) */ public Image getColumnImage(Object element, int columnIndex) { return null; } /** * @param stateTable */ public static void createTableColumns(Table stateTable) { // create table headers for (int i = 0; i < columnTitles.length; i++) { TableColumn column = new TableColumn(stateTable, SWT.NULL); column.setWidth(columnWidths[i]); column.setText(columnTitles[i]); column.setToolTipText(TOOLTIP); } } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int) */ public String getColumnText(Object element, int columnIndex) { if (element instanceof CoverageInformationItem) { CoverageInformationItem item = (CoverageInformationItem) element; switch (columnIndex) { case COL_MODULE: return item.getModule(); case COL_LOCATION: return item.getLocation(); case COL_COUNT: return String.valueOf(item.getCount()); } } return null; } } /** * A ResultPageColumnListener is a listener that handles clicks on * the column headers of the "State space progress" region of the * Result Page. The same class is used for all the column * headers, with the column number indicating which column header * was clicked on. * * @author lamport * */ static class ResultPageColumnListener implements SelectionListener { private int columnNumber; private ResultPage resultPage; public ResultPageColumnListener(int columnNumber, ResultPage resultPage) { super(); this.columnNumber = columnNumber; this.resultPage = resultPage; } { // TODO Auto-generated constructor stub } public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } /** * This is called when the user clicks on the header of a column * of the "State space progress" region of the ResultsPage. It * raises a window with a graph of the specified column. */ public void widgetSelected(SelectionEvent e) { UIHelper.runUIAsync(new DataDisplay(resultPage, columnNumber)); } } /** * The run method of this class creates a shell (a window) to display * a graph of the appropriate State Space Progress information when the user clicks on * a column heading. It then adds a PaintListener to that shell, and that * listener draws the graph initially and whenever the window is resized or * some other event requires it to be redrawn. * * The constructor is used to pass the arguments needed by the run method to * display the data. * * Note: The location at which the shells are displayed is fixed in code * buried deeply. There should probably be some thought given to where to * pop up the window, and perhaps a window should be popped up in the same * place as the last such window was popped--perhaps with a bit of random * variation to prevent them all from piling up. * * @author lamport * */ static class DataDisplay implements Runnable { int columnNumber; ResultPage resultPage; /** * The constructor returns an object with null data and times arrays * if there are not at least two data points. * * @param ssInfo * @param columnNumber */ public DataDisplay(ResultPage resultPage, int columnNumber) { this.resultPage = resultPage; this.columnNumber = columnNumber; } /** * Much of the stuff in this run() method was copied, without much * understanding from Snippet245.java in the Eclipse examples. */ public void run() { /* * The data and times arrays are set to contain the data items to be displayed * and the elapsed time (in milliseconds) at which each item was posted. * The data is obtained from the appropriate column of the ssInfo items. * For the Time column, the number of reports is graphed. */ // The following method for getting the current display was // copied without understanding from someplace or other. String title = getGraphTitle(columnNumber, resultPage); // We check if a shell exists with this title, and use it if // it does. Otherwise, we get a new shell. Display display = UIHelper.getCurrentDisplay(); boolean shellExists = false; Shell theShell = null; Shell[] shells = display.getShells(); for (int i = 0; i < shells.length; i++) { if (shells[i].getText().equals(title)) { theShell = shells[i]; shellExists = true; break; } } if (!shellExists) { theShell = new Shell(display, SWT.SHELL_TRIM); } final Shell shell = theShell; shell.setText(title); shell.setActive(); // should cause it to pop up to the top. if (shellExists) { shell.redraw(); shell.update(); } else { shell.addPaintListener(new PaintListener() { public void paintControl(PaintEvent event) { StateSpaceInformationItem[] ssInfo = resultPage.getStateSpaceInformation(); if (ssInfo.length < 2) { return; } long[] data = new long[ssInfo.length + 1]; long[] times = new long[ssInfo.length + 1]; data[0] = 0; times[0] = 0; long startTime = resultPage.startTime; System.out.println("first reported time - starttime = " + (ssInfo[0].getTime().getTime() - startTime)); if (startTime > ssInfo[0].getTime().getTime() - 1000) { startTime = ssInfo[0].getTime().getTime() - 1000; } for (int i = 1; i < data.length; i++) { switch (columnNumber) { case StateSpaceLabelProvider.COL_TIME: data[i] = i - 1; break; case StateSpaceLabelProvider.COL_DIAMETER: data[i] = ssInfo[i - 1].getDiameter(); break; case StateSpaceLabelProvider.COL_FOUND: data[i] = ssInfo[i - 1].getFoundStates(); break; case StateSpaceLabelProvider.COL_DISTINCT: data[i] = ssInfo[i - 1].getDistinctStates(); break; case StateSpaceLabelProvider.COL_LEFT: data[i] = ssInfo[i - 1].getLeftStates(); break; default: return; } times[i] = ssInfo[i - 1].getTime().getTime() - startTime; } if (data == null) { return; } Rectangle rect = shell.getClientArea(); // Set maxData to the largest data value; long maxData = 0; for (int i = 0; i < data.length; i++) { if (data[i] > maxData) { maxData = data[i]; } } long maxTime = times[times.length - 1]; // event.gc.drawOval(0, 0, rect.width - 1, rect.height - 1); if (maxTime > 0) { int[] pointArray = new int[2 * data.length]; for (int i = 0; i < data.length; i++) { pointArray[2 * i] = (int) ((times[i] * rect.width) / maxTime); pointArray[(2 * i) + 1] = (int) (rect.height - ((data[i] * rect.height) / maxData)); } event.gc.drawPolyline(pointArray); } String stringTime = "Time: "; long unreportedTime = maxTime; long days = maxTime / (1000 * 60 * 60 * 24); if (days > 0) { unreportedTime = unreportedTime - days * (1000 * 60 * 60 * 24); stringTime = stringTime + days + ((days == 1) ? (" day ") : (" days ")); } long hours = unreportedTime / (1000 * 60 * 60); if (hours > 0) { unreportedTime = unreportedTime - hours * (1000 * 60 * 60); stringTime = stringTime + hours + ((hours == 1) ? (" hour ") : (" hours ")); } unreportedTime = (unreportedTime + (1000 * 26)) / (1000 * 60); stringTime = stringTime + unreportedTime + ((unreportedTime == 1) ? (" minute ") : (" minutes ")); event.gc.drawString(stringTime, 0, 0); event.gc.drawString("Current: " + data[data.length - 1], 0, 15); if (maxData != data[data.length - 1]) { event.gc.drawString("Maximum: " + maxData, 0, 30); } } }); } ; if (!shellExists) { shell.setBounds(100 + 30 * columnNumber, 100 + 30 * columnNumber, 400, 300); } shell.open(); // The following code from the Eclipse example was eliminated. // It seems to cause the shell to survive after the Toolbox is // killed. // while (!shell.isDisposed()) { // if (!display.readAndDispatch()) display.sleep(); } } /** * The title of a graph consists of two parts: the prefix, which * identifies the column, and the suffix, which identifies the model. * When we dispose of the ResultPage, we must dispose of all graph * window (shells) for that model. * * @param resultPage * @return */ private static String getGraphTitleSuffix(ResultPage resultPage) { return "(" + ModelHelper.getModelName(resultPage.getConfig().getFile()) + ")"; } private static String getGraphTitle(int columnNumber, ResultPage resultPage) { String title = StateSpaceLabelProvider.columnTitles[columnNumber]; if (columnNumber == StateSpaceLabelProvider.COL_TIME) { title = "Number of Progress Reports"; } return title + " " + getGraphTitleSuffix(resultPage); } }
package org.lamport.tla.toolbox.tool.tlc.launch; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.model.ILaunchConfigurationDelegate; import org.eclipse.jface.dialogs.MessageDialog; import org.lamport.tla.toolbox.spec.parser.ParseResult; import org.lamport.tla.toolbox.tool.IParseResult; import org.lamport.tla.toolbox.tool.ToolboxHandle; import org.lamport.tla.toolbox.tool.tlc.TLCActivator; import org.lamport.tla.toolbox.tool.tlc.job.TLCJob; import org.lamport.tla.toolbox.tool.tlc.job.TLCProcessJob; import org.lamport.tla.toolbox.tool.tlc.job.TraceExplorerJob; import org.lamport.tla.toolbox.tool.tlc.model.Assignment; import org.lamport.tla.toolbox.tool.tlc.model.Model; import org.lamport.tla.toolbox.tool.tlc.model.ModelWriter; import org.lamport.tla.toolbox.tool.tlc.model.TypedSet; import org.lamport.tla.toolbox.tool.tlc.traceexplorer.SimpleTLCState; import org.lamport.tla.toolbox.tool.tlc.util.ModelHelper; import org.lamport.tla.toolbox.util.ResourceHelper; import org.lamport.tla.toolbox.util.TLAMarkerInformationHolder; import org.lamport.tla.toolbox.util.UIHelper; import tla2sany.semantic.OpDefNode; /** * Methods in this class are executed when the user clicks the explore * button on the trace explorer. It extends {@link TLCModelLaunchDelegate} in order * to have the methods {@link TLCModelLaunchDelegate#getLaunch(ILaunchConfiguration, String)} and * {@link TLCModelLaunchDelegate#preLaunchCheck(ILaunchConfiguration, String, IProgressMonitor)}. This class * overrides the other methods in {@link TLCModelLaunchDelegate}. * * In particular, it overrides buildForLaunch(), finalLaunchCheck(), and launch(). * * When a user clicks the explore button and there is an error trace, the method * doExplore() in TraceExplorerComposite is called. This method launches an ILaunchConfiguration * in the mode that corresponds to this delegate (as specified in the plugin.xml file for this plugin). * * Eventually, the methods buildForLaunch(), finalLaunchCheck(), and launch() are called, in that order. * * The first method, buildForLaunch() writes data to TE.tla so that SANY can be run on that module in the next * method, finalLaunchCheck(). buildForLaunch() also copies spec modules to the model directory if the model is not * locked. * * The second method, finalLaunchCheck(), calls SANY on TE.tla. If there are parse errors, these errors are presented * to the user, and the launch terminates. If there are not parse errors, this method uses the {@link ParseResult} object * to determine the level of each trace explorer expression. It is necessary to determine if each expression contains * primed variables or not. This is explained later in these comments. Once the level of each expression is determined, * finalLaunchCheck() rewrites contents to TE.tla and writes contents to TE.cfg. Also, TE.out is redundantly cleared (it * is also cleared in buildForLaunch()). * * The third method, launch(), is called if and only if finalLaunchCheck() returns true. It creates an instance of * {@link TLCProcessJob} which launches TLC. */ public class TraceExplorerDelegate extends TLCModelLaunchDelegate implements ILaunchConfigurationDelegate, IModelConfigurationConstants, IConfigurationConstants { public static final String MODE_TRACE_EXPLORE = "exploreTrace"; private static final String EMPTY_STRING = ""; private TraceExpressionInformationHolder[] traceExpressionData; private IFile tlaFile; private IFile cfgFile; private IFile outFile; private List<SimpleTLCState> trace; private String initId; private String nextId; public boolean buildForLaunch(ILaunchConfiguration config, String mode, IProgressMonitor monitor) throws CoreException { final Model model = config.getAdapter(Model.class); final IProject project = model.getSpec().getProject(); int STEP = 100; // retrieve the project containing the specification final IFolder modelFolder = model.getFolder(); if (!modelFolder.exists()) { throw new CoreException(new Status(IStatus.ERROR, TLCActivator.PLUGIN_ID, "Trace explorer was run and the model folder does not exist. This is a bug.")); } IPath targetFolderPath = modelFolder.getProjectRelativePath().addTrailingSeparator(); // create the handles: TE.tla, TE.cfg and TE.out tlaFile = project.getFile(targetFolderPath.append(ModelHelper.TE_FILE_TLA)); cfgFile = project.getFile(targetFolderPath.append(ModelHelper.TE_FILE_CFG)); outFile = project.getFile(targetFolderPath.append(ModelHelper.TE_FILE_OUT)); TLCActivator.logDebug("Writing files to: " + targetFolderPath.toOSString()); IFile[] files = new IFile[] { tlaFile, cfgFile, outFile }; /* * We want to copy spec files to the model folder only if * the model is not locked. Before copying, the previous spec * files must be deleted. */ if (!model.isLocked()) { final IResource[] members = modelFolder.members(); // erase everything inside if (members.length == 0) { monitor.worked(STEP); } else { // Get the checkpoint folder in order to avoid // deleting that folder. // This ModelHelper method should return an array of // size one because there should only be one checkpoint // folder. final IResource[] checkpoints = model.getCheckpoints(false); ISchedulingRule deleteRule = ResourceHelper.getDeleteRule(members); // delete files ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { monitor.beginTask("Deleting files", members.length); // delete the members of the target // directory for (int i = 0; i < members.length; i++) { try { if ((checkpoints.length > 0 && checkpoints[0].equals(members[i])) || members[i].getName().equals(ModelHelper.FILE_CFG) || members[i].getName().equals(ModelHelper.FILE_TLA) || members[i].getName().equals(ModelHelper.FILE_OUT) || members[i].getName().equals(ModelHelper.TE_TRACE_SOURCE) // Iff the model has been run with a module // override, then there is a .class (and // optionally a .java) file in the folder. // We must not delete the .class file. // The TraceExplorer won't work unless // the module overrides also come with a // pure TLA+ implementation. || members[i].getName().endsWith(".class") || members[i].getName().endsWith(".java")) { // We don't want to delete the checkpoints folder // or any of the MC files or the MC_TE.out file. continue; } members[i].delete(IResource.FORCE, new SubProgressMonitor(monitor, 1)); } catch (CoreException e) { // catch the exception if // deletion failed, and just // ignore this fact // FIXME this should be fixed at // some later point in time TLCActivator.logError("Error deleting a file " + members[i].getLocation(), e); } } monitor.done(); } }, deleteRule, IWorkspace.AVOID_UPDATE, new SubProgressMonitor(monitor, STEP)); } monitor.subTask("Copying files"); // retrieve the root file IFile specRootFile = ResourceHelper.getLinkedFile(project, specRootFilename, false); if (specRootFile == null) { // root module file not found throw new CoreException(new Status(IStatus.ERROR, TLCActivator.PLUGIN_ID, "Error accessing the root module " + specRootFilename)); } // copy specRootFile.copy(targetFolderPath.append(specRootFile.getProjectRelativePath()), IResource.DERIVED | IResource.FORCE, new SubProgressMonitor(monitor, 1)); // find the result IResource specRootFileCopy = modelFolder.findMember(specRootFile.getProjectRelativePath()); // react if no result if (specRootFileCopy == null) { throw new CoreException(new Status(IStatus.ERROR, TLCActivator.PLUGIN_ID, "Error copying " + specRootFilename + " into " + targetFolderPath.toOSString())); } ModelHelper.copyExtendedModuleFiles(specRootFile, targetFolderPath, monitor, STEP, project); } ModelHelper.createOrClearFiles(files, monitor); monitor.worked(STEP); monitor.subTask("Creating contents"); // retrieve the trace produced by running the model checker on the // config // trace = TLCErrorTraceRegistry.getErrorTraceRegistry().getTrace(config); trace = model.getErrorTrace(); ModelWriter writer = new ModelWriter(); // add extend primer writer.addPrimer(ModelHelper.TE_MODEL_NAME, ResourceHelper.getModuleName(specRootFilename)); writeModelInfo(config, writer); /* * The following writes variable declarations and identifier definitions * for the trace explorer expressions. It also stores information about * each expression in traceExpressionData. In particular, it stores the variable * name, identifier, and expression string for each expression. This is used * in finalLaunchCheck() for re-writing contents to TE.tla and TE.cfg, if parsing * succeeds. This is necessary for two reasons: * * 1.) We want to use the same variable name prior to running SANY as we do for * the TE.tla file that is to be run by TLC. The SANY run is used to determine if * those variable names are already declared in the spec, so if parsing succeeds, * we know that those variable names can be used again with TLC. * * 2.) We use the identifier assigned to each expression to determine the level * of each expression. This is done in finalLaunchCheck() using the ParseResult * object returned by SANY. */ traceExpressionData = writer.createAndAddTEVariablesAndDefinitions(ModelHelper.deserializeFormulaList(config .getAttribute(IModelConfigurationConstants.TRACE_EXPLORE_EXPRESSIONS, new Vector<String>())), TRACE_EXPLORE_EXPRESSIONS); // add the initial state predicate and next state action without // the trace exploration expressions in order to determine if they parse // initNext[0] is the identifier for init, initNext[1] is the identifier for next String[] initNext = writer.addInitNextForTE(trace, null); if (initNext != null) { initId = initNext[0]; nextId = initNext[1]; } monitor.worked(STEP); monitor.subTask("Writing contents"); // Write the contents to the files writer.writeFiles(tlaFile, cfgFile, monitor); // do not want to rebuild the workspace return false; } /** * We use this method to check for parsing errors and to determine the level * of each trace explorer expression, i.e. whether there are primed variables or not. * If an expression is a temporal formula, this should show an error to the user. */ public boolean finalLaunchCheck(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException { monitor.beginTask("Verifying model files", 4); IProject project = ResourceHelper.getProject(specName); IFolder launchDir = project.getFolder(modelName); IFile rootModule = launchDir.getFile(ModelHelper.TE_FILE_TLA); monitor.worked(1); // parse the TE.tla file IParseResult parseResult = ToolboxHandle.parseModule(rootModule, new SubProgressMonitor(monitor, 1), false, false); Assert .isTrue(parseResult instanceof ParseResult, "Object returned by parsing the module is not an instance of ParseResult. This is not expected by the toolbox."); if (parseResult.getDetectedErrors().size() > 0) { /* * This displays the parse errors to the user in an error * dialog. It attempts to replace messages containing references * to locations to module TE with the string from that location. */ final StringBuffer errorMessage = new StringBuffer(); Iterator<TLAMarkerInformationHolder> it = parseResult.getDetectedErrors().iterator(); while (it.hasNext()) { TLAMarkerInformationHolder errorInfo = it.next(); errorMessage.append(errorInfo.getMessage() + "\n"); } UIHelper.runUIAsync(new Runnable() { public void run() { MessageDialog.openError(UIHelper.getShellProvider().getShell(), "Parsing error when running trace explorer", errorMessage.toString()); } }); return false; } /* * First get the OpDefNodes for the root module TE.tla * Put them in a hashtable for efficiency in retrieving them. */ OpDefNode[] opDefNodes = ((ParseResult) parseResult).getSpecObj().getExternalModuleTable().getRootModule() .getOpDefs(); Hashtable<String, OpDefNode> nodeTable = new Hashtable<String, OpDefNode>(opDefNodes.length); Assert.isNotNull(opDefNodes, "OpDefNodes[] from parsing TE.tla is null. This is a bug."); for (int j = 0; j < opDefNodes.length; j++) { String key = opDefNodes[j].getName().toString(); nodeTable.put(key, opDefNodes[j]); } /* * Set the level for each trace expression using the corresponding OpDefNode * * We use the following object to collect level three expressions in order to display * these in a message to the user. */ Vector<TraceExpressionInformationHolder> levelThreeExpressions = new Vector<TraceExpressionInformationHolder>(); for (int i = 0; i < traceExpressionData.length; i++) { OpDefNode opDefNode = (OpDefNode) nodeTable.get(traceExpressionData[i].getIdentifier()); int level = opDefNode.getBody().getLevel(); traceExpressionData[i].setLevel(level); if (level == 3) { levelThreeExpressions.add(traceExpressionData[i]); } } // check if there are level three expressions // display them to the user if found and return false // the launch should not proceed if (!levelThreeExpressions.isEmpty()) { final StringBuffer errorBuffer = new StringBuffer(); errorBuffer .append("The trace explorer cannot evaluate temporal formulas. The following expressions are temporal formulas:\n\n"); Iterator<TraceExpressionInformationHolder> it = levelThreeExpressions.iterator(); while (it.hasNext()) { TraceExpressionInformationHolder expressionInfo = it.next(); errorBuffer.append(expressionInfo.getExpression() + "\n\n"); } UIHelper.runUIAsync(new Runnable() { public void run() { MessageDialog.openError(UIHelper.getShellProvider().getShell(), "Temporal formulas found", errorBuffer .toString()); } }); return false; } ModelHelper.createOrClearFiles(new IFile[] { tlaFile, cfgFile, outFile }, monitor); monitor.subTask("Creating contents"); ModelWriter writer = new ModelWriter(); // add comments giving information about the level of each expression and // which variable corresponds to which expression writer.addTraceExplorerExpressionInfoComments(traceExpressionData); // add extend primer writer.addPrimer(ModelHelper.TE_MODEL_NAME, ResourceHelper.getModuleName(specRootFilename)); // write constants, model values, new definitions, definition overrides writeModelInfo(configuration, writer); // variables declarations for trace explorer expressions writer.addTEVariablesAndDefinitions(traceExpressionData, TRACE_EXPLORE_EXPRESSIONS, false); // add init and next writer.addInitNextForTE(trace, traceExpressionData, initId, nextId); SimpleTLCState finalState = (SimpleTLCState) trace.get(trace.size() - 1); boolean isBackToState = finalState.isBackToState(); boolean isStuttering = finalState.isStuttering(); // add temporal property or invariant depending on type of trace // read the method comments to see the form of the invariant or property if (isStuttering) { writer.addStutteringPropertyForTraceExplorer((SimpleTLCState) trace.get(trace.size() - 2)); } else if (isBackToState) { writer.addBackToStatePropertyForTraceExplorer((SimpleTLCState) trace.get(trace.size() - 2), (SimpleTLCState) trace.get(finalState.getStateNumber() - 1)); } else { // checking deadlock eliminates the need for the following // writer.addInvariantForTraceExplorer(finalState); } writer.writeFiles(tlaFile, cfgFile, monitor); // retrieve the model folder IFolder modelFolder = project.getFolder(modelName); // refresh the model folder modelFolder.refreshLocal(IResource.DEPTH_ONE, new SubProgressMonitor(monitor, 100)); // set the model to have the trace with trace explorer expression shown configuration.getAdapter(Model.class).setOriginalTraceShown(false); // launch should proceed return true; } public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { TLCActivator.logDebug("launch called"); // check the modes if (!MODE_TRACE_EXPLORE.equals(mode)) { throw new CoreException( new Status(IStatus.ERROR, TLCActivator.PLUGIN_ID, "Unsupported launch mode " + mode)); } // retrieve the project containing the specification IProject project = ResourceHelper.getProject(specName); if (project == null) { // project could not be found throw new CoreException(new Status(IStatus.ERROR, TLCActivator.PLUGIN_ID, "Error accessing the spec project " + specName)); } TLCJob tlcjob = new TraceExplorerJob(specName, modelName, launch, 1); tlcjob.setPriority(Job.SHORT); tlcjob.setUser(true); // The TLC job itself does not do any file IO tlcjob.setRule(mutexRule); tlcjob.schedule(); } /** * Writes constants, model values, new definitions, and overrides to the model writer. * * For a more detailed description of what the calls in this method do, see the * corresponding part of TLCModelLaunchDelegate.buildForLaunch. * * @param config * @param writer * @throws CoreException */ private void writeModelInfo(ILaunchConfiguration config, ModelWriter writer) throws CoreException { // constants list final List<Assignment> constants = ModelHelper.deserializeAssignmentList(config.getAttribute(MODEL_PARAMETER_CONSTANTS, new Vector<String>()), true); // the advanced model values TypedSet modelValues = TypedSet.parseSet(config.getAttribute(MODEL_PARAMETER_MODEL_VALUES, EMPTY_STRING)); // add constants and model values writer.addConstants(constants, modelValues, MODEL_PARAMETER_CONSTANTS, MODEL_PARAMETER_MODEL_VALUES); // new definitions from Advanced Model page. writer.addNewDefinitions(config.getAttribute(MODEL_PARAMETER_NEW_DEFINITIONS, EMPTY_STRING), MODEL_PARAMETER_NEW_DEFINITIONS); // add definitions for CONSTANT parameters instantiated by ordinary values. writer.addConstantsBis(constants, MODEL_PARAMETER_CONSTANTS); // definition overrides list List<Assignment> overrides = ModelHelper.deserializeAssignmentList(config.getAttribute(MODEL_PARAMETER_DEFINITIONS, new Vector<String>())); writer.addFormulaList(ModelWriter.createOverridesContent(overrides, ModelWriter.DEFOV_SCHEME), "CONSTANT", MODEL_PARAMETER_DEFINITIONS); } }
package org.strategoxt.imp.metatooling.building; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.imp.language.Language; import org.eclipse.imp.language.LanguageRegistry; import org.spoofax.interpreter.terms.IStrategoString; import org.strategoxt.imp.editors.spoofax.generated.build_spoofaxlang_jvm_0_0; import org.strategoxt.imp.editors.spoofax.generated.spoofaxlang; import org.strategoxt.imp.runtime.Environment; import org.strategoxt.imp.runtime.dynamicloading.BadDescriptorException; import org.strategoxt.imp.runtime.dynamicloading.Descriptor; import org.strategoxt.imp.runtime.parser.SGLRParseController; import org.strategoxt.imp.runtime.services.StrategoObserver; import org.strategoxt.imp.runtime.stratego.EditorIOAgent; import org.strategoxt.imp.runtime.stratego.IMPLibrary; import org.strategoxt.lang.Context; import org.strategoxt.lang.StrategoErrorExit; import org.strategoxt.lang.StrategoException; import org.strategoxt.lang.StrategoExit; import org.strategoxt.stratego_lib.dr_scope_all_end_0_0; import org.strategoxt.stratego_lib.dr_scope_all_start_0_0; /** * Triggers spoofaxlang building and loading from an Ant build file. */ public class AntSpxGenerateArtefacts { //TODO : Set Derived Resources //TODO : Adding auto-generating the derived entries private static volatile boolean active; public static boolean isActive() { return active; } private static void refresh(IResource workingdir) throws Exception { final int depthArg = IResource.DEPTH_INFINITE; final IResource file = workingdir; Job job = new Job("Refresh") { @Override protected IStatus run(IProgressMonitor monitor) { try { file.touch(monitor); file.refreshLocal(depthArg, monitor); } catch (Exception e) { Environment.logWarning("Could not refresh file", e); } return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(5000); } public static void main(String[] args) throws Exception{ if (args == null || args.length == 0) throw new IllegalArgumentException("Project Work Directory is missing. "); final String workingDirectoryArg = args[0]; final IResource file = EditorIOAgent.getResource(new File(workingDirectoryArg)); String buildStrategy = "-i"; if (args.length >1) buildStrategy = args[1]; Environment.getStrategoLock().lock(); try { if (!isActive()) { active = true; try { if (!file.exists()) { Environment.logException("Could not find project at following location :" + file.getLocation(), new FileNotFoundException(file.getFullPath().toOSString())); System.err.println("Build failed: could not find project at following location :" + file.getLocation()); System.exit(1); } IPath absolutePath = file.getLocation(); //StrategoObserver observer = newStrategoObserverOf(SpoofaxLangParseController.LANGUAGE); boolean success = generateArtefacts(file, new NullProgressMonitor() , newEditorIOAgent(absolutePath, null), buildStrategy); if (!success) { System.err.println("Build failed; see error log."); System.exit(1); } } finally { active = false; } } } finally { Environment.getStrategoLock().unlock(); refresh(file); } } private static StrategoObserver newStrategoObserverOf(String languageName) throws BadDescriptorException{ // Get descriptor Language lang = LanguageRegistry.findLanguage(languageName); Descriptor descriptor = Environment.getDescriptor(lang); // Get parse controller SGLRParseController parseController = descriptor.createService(SGLRParseController.class, null); StrategoObserver observer = descriptor.createService(StrategoObserver.class, parseController); return observer; } private static EditorIOAgent newEditorIOAgent(IPath location , StrategoObserver observer) throws FileNotFoundException, IOException{ EditorIOAgent agent = new EditorIOAgent(); agent.setAlwaysActivateConsole(true); agent.setWorkingDir(location.toOSString()); agent.setProjectPath(location.toOSString()); // TODO FIX : imploder attachment is null while project is built from ant script. // hence, adding an stratego observer is not adding any value // observer.getRuntime().setIOAgent(agent); // ((EditorIOAgent)observer.getRuntime().getIOAgent()).setJob(new StrategoObserverUpdateJob(observer)); return agent; } public static boolean generateArtefacts(IResource file, IProgressMonitor monitor , EditorIOAgent agent, String buildStrategy) { IPath absoluteProjectLocation = file.getLocation(); if (absoluteProjectLocation == null) return false; try { monitor.setTaskName("Generating artefacts for following spx project: " + file.getName()); if (file.exists() ) { Context contextSpoofaxLang = new Context(Environment.getTermFactory(), agent); contextSpoofaxLang.addOperatorRegistry(new IMPLibrary()); spoofaxlang.init(contextSpoofaxLang); IStrategoString input = contextSpoofaxLang.getFactory().makeString(file.getLocation().toOSString()); IStrategoString buildStrategyTerm = contextSpoofaxLang.getFactory().makeString(buildStrategy); dr_scope_all_start_0_0.instance.invoke(contextSpoofaxLang, input); try { System.out.println("Compiling SPX files and generating intermediate artefacts."); System.out.println("Invoking build-spoofaxlang-jvm."); build_spoofaxlang_jvm_0_0.instance.invoke( contextSpoofaxLang , contextSpoofaxLang.getFactory().makeTuple(input, buildStrategyTerm)); System.out.println("Intermediate artefacts have been generated successfully."); } catch (StrategoErrorExit e) { Environment.logException(e); throw new StrategoException("Project builder failed: " + e.getMessage() + "\nLog follows:\n\n" + agent.getLog(), e); } catch (StrategoExit e) { if (e.getValue() != 0) { throw new StrategoException("Project builder failed.\nLog follows:\n\n" + agent.getLog(), e); } } finally { dr_scope_all_end_0_0.instance.invoke(contextSpoofaxLang, input); } monitor.setTaskName(null); } return true; } catch (Exception e) { Environment.logException("Project builder failed: to generate artefacts" + file, e); return false; } } }
package sk.henrichg.phoneprofilesplus; import android.annotation.SuppressLint; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Handler; import android.os.PowerManager; import android.os.SystemClock; import com.google.gson.Gson; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import static android.content.Context.POWER_SERVICE; public class BluetoothConnectionBroadcastReceiver extends BroadcastReceiver { private static List<BluetoothDeviceData> connectedDevices = null; @Override public void onReceive(Context context, Intent intent) { PPApplication.logE(" CallsCounter.logCounter(context, "BluetoothConnectionBroadcastReceiver.onReceive", "BluetoothConnectionBroadcastReceiver_onReceive"); final Context appContext = context.getApplicationContext(); if (!PPApplication.getApplicationStarted(appContext, true)) // application is not started return; if (intent == null) return; final String action = intent.getAction(); if (action == null) return; //PPApplication.logE("BluetoothConnectionBroadcastReceiver.onReceive", "action=" + action); if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED) || action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED) || action.equals(BluetoothDevice.ACTION_NAME_CHANGED)/* || action.equals(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED)*/) { // BluetoothConnectionBroadcastReceiver final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device == null) return; final boolean connected = action.equals(BluetoothDevice.ACTION_ACL_CONNECTED); final String newName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME); if (action.equals(BluetoothDevice.ACTION_NAME_CHANGED)) { if (newName == null) { PPApplication.logE("$$$ BluetoothConnectionBroadcastReceiver.onReceive", "action=" + action + " with newName == null"); return; } if (newName.equals(device.getName())) { PPApplication.logE("$$$ BluetoothConnectionBroadcastReceiver.onReceive", "action=" + action + " with not changed name"); return; } } PPApplication.startHandlerThread("BluetoothConnectionBroadcastReceiver.onReceive"); final Handler handler = new Handler(PPApplication.handlerThread.getLooper()); handler.post(new Runnable() { @Override public void run() { PowerManager powerManager = (PowerManager) appContext.getSystemService(POWER_SERVICE); PowerManager.WakeLock wakeLock = null; try { if (powerManager != null) { wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":BluetoothConnectionBroadcastReceiver_onReceive"); wakeLock.acquire(10 * 60 * 1000); } PPApplication.logE("PPApplication.startHandlerThread", "START run - from=BluetoothConnectionBroadcastReceiver.onReceive"); getConnectedDevices(appContext); if (device != null) { PPApplication.logE("$$$ BluetoothConnectionBroadcastReceiver.onReceive", "action=" + action); try { //if (!action.equals(BluetoothDevice.ACTION_NAME_CHANGED)) { PPApplication.logE("$$$ BluetoothConnectionBroadcastReceiver.onReceive", "connected=" + connected); PPApplication.logE("$$$ BluetoothConnectionBroadcastReceiver.onReceive", "device.getName()=" + device.getName()); PPApplication.logE("$$$ BluetoothConnectionBroadcastReceiver.onReceive", "device.getAddress()=" + device.getAddress()); switch (action) { case BluetoothDevice.ACTION_ACL_CONNECTED: addConnectedDevice(device); break; case BluetoothDevice.ACTION_NAME_CHANGED: //noinspection ConstantConditions if (newName != null) { PPApplication.logE("$$$ BluetoothConnectionBroadcastReceiver.onReceive", "newName=" + newName); changeDeviceName(device, newName); } break; default: removeConnectedDevice(device); break; } } catch (Exception ignored) { } saveConnectedDevices(appContext); if (Event.getGlobalEventsRunning(appContext)) { //if (lastState != currState) if (!(BluetoothScanWorker.getScanRequest(appContext) || BluetoothScanWorker.getLEScanRequest(appContext) || BluetoothScanWorker.getWaitForResults(appContext) || BluetoothScanWorker.getWaitForLEResults(appContext) || BluetoothScanWorker.getBluetoothEnabledForScan(appContext))) { // bluetooth is not scanned PPApplication.logE("@@@ BluetoothConnectionBroadcastReceiver.onReceive", "start EventsHandler"); /*DataWrapper dataWrapper = new DataWrapper(appContext, false, false, 0); boolean bluetoothEventsExists = dataWrapper.getDatabaseHandler().getTypeEventsCount(DatabaseHandler.ETYPE_BLUETOOTHCONNECTED) > 0; dataWrapper.invalidateDataWrapper(); if (bluetoothEventsExists) { */ // start events handler EventsHandler eventsHandler = new EventsHandler(appContext); eventsHandler.handleEvents(EventsHandler.SENSOR_TYPE_BLUETOOTH_CONNECTION); } else PPApplication.logE("@@@ BluetoothConnectionBroadcastReceiver.onReceive", "not start EventsHandler, scanner is running"); } } PPApplication.logE("PPApplication.startHandlerThread", "END run - from=BluetoothConnectionBroadcastReceiver.onReceive"); } finally { if ((wakeLock != null) && wakeLock.isHeld()) { try { wakeLock.release(); } catch (Exception ignored) {} } } } }); } } private static final String CONNECTED_DEVICES_COUNT_PREF = "count"; private static final String CONNECTED_DEVICES_DEVICE_PREF = "device"; static void getConnectedDevices(Context context) { synchronized (PPApplication.bluetoothConnectionChangeStateMutex) { if (connectedDevices == null) connectedDevices = new ArrayList<>(); connectedDevices.clear(); SharedPreferences preferences = context.getSharedPreferences(PPApplication.BLUETOOTH_CONNECTED_DEVICES_PREFS_NAME, Context.MODE_PRIVATE); int count = preferences.getInt(CONNECTED_DEVICES_COUNT_PREF, 0); Gson gson = new Gson(); int gmtOffset = 0; //TimeZone.getDefault().getRawOffset(); for (int i = 0; i < count; i++) { String json = preferences.getString(CONNECTED_DEVICES_DEVICE_PREF + i, ""); if (!json.isEmpty()) { BluetoothDeviceData device = gson.fromJson(json, BluetoothDeviceData.class); if (PPApplication.logEnabled()) { @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S"); PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "device.name=" + device.getName()); PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "device.address=" + device.getAddress()); PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "device.timestamp=" + sdf.format(device.timestamp)); } //long bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime() - gmtOffset; Calendar calendar = Calendar.getInstance(); long bootTime = calendar.getTimeInMillis() - SystemClock.elapsedRealtime() - gmtOffset; if (PPApplication.logEnabled()) { @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S"); PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "bootTime=" + sdf.format(bootTime)); } if (device.timestamp >= bootTime) { PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "added"); connectedDevices.add(device); } else PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "not added"); } } PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "connectedDevices.size()=" + connectedDevices.size()); } } static void saveConnectedDevices(Context context) { synchronized (PPApplication.bluetoothConnectionChangeStateMutex) { if (connectedDevices == null) connectedDevices = new ArrayList<>(); SharedPreferences preferences = context.getSharedPreferences(PPApplication.BLUETOOTH_CONNECTED_DEVICES_PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.putInt(CONNECTED_DEVICES_COUNT_PREF, connectedDevices.size()); Gson gson = new Gson(); for (int i = 0; i < connectedDevices.size(); i++) { String json = gson.toJson(connectedDevices.get(i)); editor.putString(CONNECTED_DEVICES_DEVICE_PREF + i, json); } editor.apply(); } } private static void addConnectedDevice(BluetoothDevice device) { synchronized (PPApplication.bluetoothConnectionChangeStateMutex) { PPApplication.logE("BluetoothConnectionBroadcastReceiver.addConnectedDevice","device.name="+device.getName()); PPApplication.logE("BluetoothConnectionBroadcastReceiver.addConnectedDevice","device.address="+device.getAddress()); boolean found = false; for (BluetoothDeviceData _device : connectedDevices) { if (_device.address.equals(device.getAddress())) { found = true; break; } } if (!found) { for (BluetoothDeviceData _device : connectedDevices) { if (_device.getName().equalsIgnoreCase(device.getName())) { found = true; break; } } } PPApplication.logE("BluetoothConnectionBroadcastReceiver.addConnectedDevice","found="+found); if (!found) { int gmtOffset = 0; //TimeZone.getDefault().getRawOffset(); Calendar now = Calendar.getInstance(); long timestamp = now.getTimeInMillis() - gmtOffset; connectedDevices.add(new BluetoothDeviceData(device.getName(), device.getAddress(), BluetoothScanWorker.getBluetoothType(device), false, timestamp, false, false)); } } } private static void removeConnectedDevice(BluetoothDevice device) { synchronized (PPApplication.bluetoothConnectionChangeStateMutex) { PPApplication.logE("BluetoothConnectionBroadcastReceiver.removeConnectedDevice","device.name="+device.getName()); PPApplication.logE("BluetoothConnectionBroadcastReceiver.removeConnectedDevice","device.address="+device.getAddress()); int index = 0; boolean found = false; for (BluetoothDeviceData _device : connectedDevices) { if (_device.address.equals(device.getAddress())) { found = true; break; } ++index; } if (!found) { index = 0; for (BluetoothDeviceData _device : connectedDevices) { if (_device.getName().equalsIgnoreCase(device.getName())) { found = true; break; } ++index; } } PPApplication.logE("BluetoothConnectionBroadcastReceiver.removeConnectedDevice","found="+found); if (found) connectedDevices.remove(index); } } static void clearConnectedDevices(Context context, boolean onlyOld) { PPApplication.logE("BluetoothConnectionBroadcastReceiver.clearConnectedDevices","onlyOld="+onlyOld); if (onlyOld) { getConnectedDevices(context); } synchronized (PPApplication.bluetoothConnectionChangeStateMutex) { if (connectedDevices != null) { if (onlyOld) { int gmtOffset = 0; //TimeZone.getDefault().getRawOffset(); for (BluetoothDeviceData device : connectedDevices) { if (PPApplication.logEnabled()) { @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S"); PPApplication.logE("BluetoothConnectionBroadcastReceiver.clearConnectedDevices", "device.name=" + device.name); PPApplication.logE("BluetoothConnectionBroadcastReceiver.clearConnectedDevices", "device.timestamp=" + sdf.format(device.timestamp)); } //long bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime() - gmtOffset; Calendar calendar = Calendar.getInstance(); long bootTime = calendar.getTimeInMillis() - SystemClock.elapsedRealtime() - gmtOffset; if (PPApplication.logEnabled()) { @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S"); PPApplication.logE("BluetoothConnectionBroadcastReceiver.clearConnectedDevices", "bootTime=" + sdf.format(bootTime)); } if (device.timestamp < bootTime) connectedDevices.remove(device); } } else connectedDevices.clear(); } } } private static void changeDeviceName(BluetoothDevice device, String deviceName) { synchronized (PPApplication.bluetoothConnectionChangeStateMutex) { boolean found = false; for (BluetoothDeviceData _device : connectedDevices) { if (_device.address.equals(device.getAddress()) && !deviceName.isEmpty()) { _device.setName(deviceName); found = true; break; } } if (!found) { for (BluetoothDeviceData _device : connectedDevices) { if (_device.getName().equalsIgnoreCase(device.getName()) && !deviceName.isEmpty()) { _device.setName(deviceName); break; } } } } } static void addConnectedDeviceData(List<BluetoothDeviceData> detectedDevices) { synchronized (PPApplication.bluetoothConnectionChangeStateMutex) { for (BluetoothDeviceData device : detectedDevices) { PPApplication.logE("BluetoothConnectionBroadcastReceiver.addConnectedDeviceData", "device.name=" + device.getName()); PPApplication.logE("BluetoothConnectionBroadcastReceiver.addConnectedDeviceData", "device.address=" + device.getAddress()); boolean found = false; for (BluetoothDeviceData _device : connectedDevices) { if (_device.getAddress().equals(device.getAddress())) { found = true; break; } } if (!found) { for (BluetoothDeviceData _device : connectedDevices) { if (_device.getName().equalsIgnoreCase(device.getName())) { found = true; break; } } } PPApplication.logE("BluetoothConnectionBroadcastReceiver.addConnectedDeviceData", "found=" + found); if (!found) { connectedDevices.add(device); } } } } static boolean isBluetoothConnected(BluetoothDeviceData deviceData, String sensorDeviceName) { synchronized (PPApplication.bluetoothConnectionChangeStateMutex) { if ((deviceData == null) && sensorDeviceName.isEmpty()) return (connectedDevices != null) && (connectedDevices.size() > 0); else { if (connectedDevices != null) { if (deviceData != null) { boolean found = false; for (BluetoothDeviceData _device : connectedDevices) { if (_device.address.equals(deviceData.getAddress())) { found = true; break; } } if (!found) { for (BluetoothDeviceData _device : connectedDevices) { String _deviceName = _device.getName().trim(); String deviceDataName = deviceData.getName().trim(); if (_deviceName.equalsIgnoreCase(deviceDataName)) { found = true; break; } } } return found; } else { for (BluetoothDeviceData _device : connectedDevices) { String device = _device.getName().trim().toUpperCase(); String _adapterName = sensorDeviceName.trim().toUpperCase(); if (Wildcard.match(device, _adapterName, '_', '%', true)) { return true; } } } } return false; } } } }
package com.intellij.internal.statistic.eventLog; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import org.apache.log4j.FileAppender; import org.apache.log4j.Layout; import org.apache.log4j.helpers.CountingQuietWriter; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.spi.LoggingEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; import java.io.Writer; import java.nio.file.Path; import java.util.List; import java.util.UUID; import java.util.function.Supplier; public class StatisticsEventLogFileAppender extends FileAppender { protected long maxFileAge = 14 * 24 * 60 * 60 * 1000; protected long maxFileSize = 10 * 1024 * 1024; private long nextRollover = 0; protected long oldestExistingFile = -1; private final Path myLogDirectory; private final Supplier<List<File>> myFilesProducer; @TestOnly public StatisticsEventLogFileAppender(@NotNull Path path, @NotNull List<File> files) { myLogDirectory = path; myFilesProducer = () -> files; } public StatisticsEventLogFileAppender(@NotNull Layout layout, @NotNull Path dir, @NotNull String filename) throws IOException { super(layout, filename); myLogDirectory = dir; myFilesProducer = () -> { final File[] files = dir.toFile().listFiles(); return files == null || files.length == 0 ? ContainerUtil.emptyList() : ContainerUtil.newArrayList(files); }; cleanUpOldFiles(); } public static StatisticsEventLogFileAppender create(@NotNull Layout layout, @NotNull Path dir) throws IOException { final File file = nextFile(dir); return new StatisticsEventLogFileAppender(layout, dir, file.getPath()); } @NotNull public String getActiveLogName() { return StringUtil.isNotEmpty(fileName) ? PathUtil.getFileName(fileName) : ""; } public void setMaxFileAge(long maxAge) { maxFileAge = maxAge; } public void setMaxFileSize(String value) { maxFileSize = OptionConverter.toFileSize(value, maxFileSize + 1); } @NotNull protected CountingQuietWriter getQuietWriter() { return (CountingQuietWriter)this.qw; } @Override protected void setQWForFiles(Writer writer) { this.qw = new CountingQuietWriter(writer, errorHandler); } @Override public synchronized void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize) throws IOException { super.setFile(fileName, append, bufferedIO, bufferSize); if (append && qw instanceof CountingQuietWriter) { File f = new File(fileName); getQuietWriter().setCount(f.length()); } } @Override protected void subAppend(LoggingEvent event) { super.subAppend(event); if (fileName != null && qw != null) { long size = getQuietWriter().getCount(); if (size >= maxFileSize && size >= nextRollover) { rollOver(); cleanUpOldFiles(); } } } public void rollOver() { nextRollover = getQuietWriter().getCount() + maxFileSize; try { final File file = nextFile(myLogDirectory); setFile(file.getPath(), false, bufferedIO, bufferSize); nextRollover = 0; } catch (InterruptedIOException e) { Thread.currentThread().interrupt(); } catch (Exception e) { LogLog.error("setFile(" + fileName + ", false) call failed.", e); } } protected void cleanUpOldFiles() { long oldestAcceptable = System.currentTimeMillis() - maxFileAge; if (oldestExistingFile != -1 && oldestAcceptable < oldestExistingFile) { return; } cleanUpOldFiles(oldestAcceptable); } protected void cleanUpOldFiles(long oldestAcceptable) { final List<File> logs = myFilesProducer.get(); if (logs == null || logs.isEmpty()) { return; } final String activeLog = getActiveLogName(); long oldestFile = -1; for (File file : logs) { if (StringUtil.equals(file.getName(), activeLog)) continue; final long lastModified = file.lastModified(); if (lastModified < oldestAcceptable) { if (!file.delete()) { LogLog.error("Failed deleting old file " + file); } } else if (lastModified < oldestFile || oldestFile == -1) { oldestFile = lastModified; } } oldestExistingFile = oldestFile; } public void cleanUp() { final List<File> logs = myFilesProducer.get(); if (logs == null || logs.isEmpty()) { return; } for (File file : logs) { if (!file.delete()) { LogLog.error("Failed deleting old file " + file); } } rollOver(); } @NotNull private static File nextFile(@NotNull Path dir) { File file = dir.resolve(UUID.randomUUID() + ".log").toFile(); while (file.exists()) { file = dir.resolve(UUID.randomUUID() + ".log").toFile(); } return file; } }
package org.hawk.service.servlet.config; import java.io.File; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.thrift.TException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Platform; import org.hawk.core.IVcsManager; import org.hawk.osgiserver.HManager; import org.hawk.osgiserver.HModel; import org.hawk.service.api.Hawk.Iface; import org.hawk.service.servlet.config.ConfigFileParser; import org.hawk.service.servlet.config.DerivedAttributeParameters; import org.hawk.service.servlet.config.HawkInstanceConfig; import org.hawk.service.servlet.config.IndexedAttributeParameters; import org.hawk.service.servlet.config.RepositoryParameters; import org.xml.sax.InputSource; public class HawkServerConfigurator { List<HawkInstanceConfig> hawkInstanceConfigs; Iface iface; HManager manager; ConfigFileParser parser; public HawkServerConfigurator(Iface iface) { this.iface = iface; hawkInstanceConfigs = new ArrayList<HawkInstanceConfig>(); manager = HManager.getInstance(); parser = new ConfigFileParser(); } public void loadHawkServerConfigurations() { for (File file : getHawkServerConfigurationFiles()) { configureHawkInstance(file); } // test saveHawkServerConfigurations(); } public void saveHawkServerConfigurations() { for(HawkInstanceConfig config : hawkInstanceConfigs) { saveHawkInstanceConfig(config); } } private List<File> getHawkServerConfigurationFiles() { URL installURL = Platform.getConfigurationLocation().getURL(); // installURL = Platform.getInstallLocation().getURL(); // installURL = Platform.getInstanceLocation().getURL(); // installURL = Platform.g().getURL(); String protocol; try { protocol = FileLocator.toFileURL(installURL).getProtocol(); String path = FileLocator.toFileURL(installURL).getPath(); System.err.println(path + " " + protocol); File configurationFolder = new File(path + "\\configuration"); FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".xml")) { return true; } else { return false; } } }; if (configurationFolder.exists() && configurationFolder.isDirectory()) { // get all files return new ArrayList<File>(Arrays.asList(configurationFolder .listFiles(filter))); } else { configurationFolder.mkdir(); } } catch (IOException e) { e.printStackTrace(); } return Collections.emptyList(); } private void configureHawkInstance(File file) { try { File xsdFile = Platform.getBundle("org.hawk.service.servlet").getDataFile("HawkServerConfigurationSchema.xsd"); HawkInstanceConfig config = parser.parse(xsdFile, file); if(config == null) { return; } // add to list hawkInstanceConfigs.add(config); HModel hawkInstance = manager.getHawkByName( config.getName()); // create a new instance it is not present if (hawkInstance == null) { // create new instance hawkInstance = createHawkInstance(config); } // apply configuration if (hawkInstance != null) { // check parameters and if different change hawkInstance.configurePolling(config.getDelayMin(), config.getDelayMax()); // add new plugins, don't delete addMissingPlugins(hawkInstance, config); // set Db //hawkInstance.getHawk().setDbtype(config.getBackend()); manager.saveHawkToMetadata(hawkInstance); //manager.getHawks(); // start instance hawkInstance.start(manager); while(!hawkInstance.isRunning()); // add metamodels, Do it first before adding attributes or repositories addMetamodels(hawkInstance, config); // add repositories, don't delete any addMissingRepositories(hawkInstance, config); // derived Attributes addMissingDerivedAttributes(hawkInstance, config); // indexed Attributes addMissingIndexedAttributes(hawkInstance, config); } } catch (Exception e) { e.printStackTrace(); } } private HModel createHawkInstance(HawkInstanceConfig config) throws TException { HModel hawkInstance; iface.createInstance(config.getName(), config.getBackend(), config.getDelayMin(), config.getDelayMax(), config.getPlugins()); hawkInstance = manager.getHawkByName( config.getName()); return hawkInstance; } private void addMissingDerivedAttributes(HModel hawkInstance, HawkInstanceConfig config) { Collection<String> existingDerivedAttributes = hawkInstance.getDerivedAttributes(); List<String> metamodels = hawkInstance.getRegisteredMetamodels(); for (DerivedAttributeParameters params : config.getDerivedAttributes()) { String derivedParameterString = attributeToString(params); if (!existingDerivedAttributes.contains(derivedParameterString)) { try { // check metamodel exist if(metamodels.contains(params.getMetamodelUri())){ hawkInstance.addDerivedAttribute(params.getMetamodelUri(), params.getTypeName(), params.getAttributeName(), params.getAttributeType(), params.isMany(), params.isOrdered(), params.isUnique(), params.getDerivationLanguage(), params.getDerivationLogic()); } else { System.err.println("HawkServerConfigurator.addMissingDerivedAttributes: metamodel " + params.getMetamodelUri() + " is not registered!"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private void addMissingIndexedAttributes(HModel hawkInstance, HawkInstanceConfig config) { List<String> metamodels = hawkInstance.getRegisteredMetamodels(); Collection<String> existingIndexedAttributes = hawkInstance .getIndexedAttributes(); for (IndexedAttributeParameters params : config.getIndexedAttributes()) { String indexedParameterString = attributeToString(params); if (!existingIndexedAttributes.contains(indexedParameterString)) { try { // check metamodel exist if(metamodels.contains(params.getMetamodelUri())) { hawkInstance.addIndexedAttribute(params.getMetamodelUri(), params.getTypeName(), params.getAttributeName()); } else { System.err.println("HawkServerConfigurator.addMissingIndexedAttributes: metamodel " + params.getMetamodelUri() + " is not registered!"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private String attributeToString(IndexedAttributeParameters params) { String indexedParameterString = String.format("%s::%s::%s", params.getMetamodelUri(), params.getTypeName(), params.getAttributeName()); return indexedParameterString; } private IndexedAttributeParameters stringToAttribute(String string) { String[] data = string.split("::"); if(data.length == 3) { return (new IndexedAttributeParameters(data[0], data[1], data[2])); } return null; } private void addMissingRepositories(HModel hawkInstance, HawkInstanceConfig config) { Collection<String> existingLocations = hawkInstance.getLocations(); for (RepositoryParameters params : config.getRepositories()) { if (!existingLocations.contains(params.getLocation())) { hawkInstance.addVCS(params.getLocation(), params.getType(), params.getUser(), params.getPass(), params.isFrozen()); } } } private void addMetamodels(HModel hawkInstance, HawkInstanceConfig config) { for (MetamodelParameters params : config.getMetamodels()) { if(params.getLocation() != null && !params.getLocation().isEmpty()) { File file = new File(params.getLocation()); try { hawkInstance.registerMeta(file); } catch (Exception e) { System.err.println("HawkServerConfigurator.addMetamodels: metamodel " + params.getLocation() + " failed!"); e.printStackTrace(); } } } } private void addMissingPlugins(HModel hawkInstance, HawkInstanceConfig config) { List<String> availableplugins = manager.getAvailablePlugins(); List<String> existingplugins = hawkInstance.getEnabledPlugins(); List<String> missingPlugins = new ArrayList<String>(); for (String plugin : config.getPlugins()) { // check plugin is available if(availableplugins.contains(plugin)) { if (!existingplugins.contains(plugin)) { missingPlugins.add(plugin); } } else { System.err.println("HawkServerConfigurator.addMissingPlugins: plugin " + plugin + " is not available!"); // TODO list available plugins } } if (!missingPlugins.isEmpty()) { try { hawkInstance.addPlugins(missingPlugins); } catch (Exception e) { System.err.println("HawkServerConfigurator.addMissingPlugins: plugin Failed!"); e.printStackTrace(); } } } private void saveHawkInstanceConfig(HawkInstanceConfig config) { // find file or create one and save all info HModel hawkInstance = manager.getHawkByName(config.getName()); // there are no way to change delay backend and plugins, but save it anyway config.setBackend(hawkInstance.getDbType()); if(hawkInstance.getEnabledPlugins() != null) { // overwrite all config.setPlugins(hawkInstance.getEnabledPlugins()); } // what is the point of saving these values , they are saved in the instance anyways and no need to store // save registered metamodels if(hawkInstance.getRegisteredMetamodels() != null) { addNewMetaodelsUriToConfig(hawkInstance, config); //config.getMetamodels().addAll(hawkInstance.getRegisteredMetamodels()); } // save all derived attributes, cannot get derivation language and logic addNewDerivedAttributesToConfig(hawkInstance.getDerivedAttributes(), config.getDerivedAttributes()); // save all indexed attributes addNewIndexedAttributesToConfig(hawkInstance.getIndexedAttributes(), config.getIndexedAttributes()); // save all Repositories addNewRepositoriesToConfig(hawkInstance, config); parser.saveConfigAsXml(config); } private void addNewMetaodelsUriToConfig(HModel hawkInstance, HawkInstanceConfig config) { List<MetamodelParameters> newMetamodels = new ArrayList<MetamodelParameters>(); for (String metamodelUri : hawkInstance.getRegisteredMetamodels()) { boolean isNew = true; for(MetamodelParameters params : config.getMetamodels()) { if(params.getUri().equals(metamodelUri)) { isNew = false; break; } } if(isNew) { newMetamodels.add(new MetamodelParameters(metamodelUri, null)); } } if(!newMetamodels.isEmpty()) { config.getMetamodels().addAll(newMetamodels); } } private void addNewDerivedAttributesToConfig(Collection<String> instanceAttributes, List<DerivedAttributeParameters> configAttributes) { List<DerivedAttributeParameters> newAttrs = new ArrayList<DerivedAttributeParameters>(); for(String indexedAttribute : instanceAttributes) { boolean isNew = true; for(IndexedAttributeParameters params : configAttributes) { if(indexedAttribute.equals(attributeToString(params))) { isNew = false; break; } } if(isNew) { DerivedAttributeParameters params = (DerivedAttributeParameters) stringToAttribute(indexedAttribute); if(params != null) newAttrs.add(params); } } if(!newAttrs.isEmpty()) { configAttributes.addAll(newAttrs); } } private void addNewIndexedAttributesToConfig(Collection<String> instanceAttributes, List<IndexedAttributeParameters> configAttributes) { List<IndexedAttributeParameters> newAttrs = new ArrayList<IndexedAttributeParameters>(); for(String indexedAttribute : instanceAttributes) { boolean isNew = true; for(IndexedAttributeParameters params : configAttributes) { if(indexedAttribute.equals(attributeToString(params))) { isNew = false; break; } } if(isNew) { IndexedAttributeParameters params = stringToAttribute(indexedAttribute); if(params != null) newAttrs.add(params); } } if(!newAttrs.isEmpty()) { configAttributes.addAll(newAttrs); } } private void addNewRepositoriesToConfig(HModel hawkInstance, HawkInstanceConfig config) { List<RepositoryParameters> newRepos = new ArrayList<RepositoryParameters>(); for (IVcsManager vcsManager : hawkInstance.getRunningVCSManagers()) { boolean isNew = true; for(RepositoryParameters repos : config.getRepositories()) { if(repos.getType().equals(vcsManager.getType()) && repos.getLocation().equals(vcsManager.getLocation())) { repos.setFrozen(vcsManager.isFrozen()); repos.setUser(vcsManager.getUsername()); repos.setPass(vcsManager.getPassword()); isNew = false; break; } } if(isNew) { RepositoryParameters newRepo = new RepositoryParameters(vcsManager.getType(), vcsManager.getLocation(), vcsManager.getUsername(), vcsManager.getPassword(), vcsManager.isFrozen()); newRepos.add(newRepo); } } if(!newRepos.isEmpty()) { config.getRepositories().addAll(newRepos); } } }
package com.redhat.ceylon.eclipse.core.debug; import java.lang.annotation.Annotation; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.model.IProcess; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.debug.core.IEvaluationRunnable; import org.eclipse.jdt.debug.core.IJavaClassObject; import org.eclipse.jdt.debug.core.IJavaDebugTarget; import org.eclipse.jdt.debug.core.IJavaObject; import org.eclipse.jdt.debug.core.IJavaReferenceType; import org.eclipse.jdt.debug.core.IJavaStackFrame; import org.eclipse.jdt.debug.core.IJavaThread; import org.eclipse.jdt.debug.core.IJavaType; import org.eclipse.jdt.debug.core.IJavaValue; import org.eclipse.jdt.internal.debug.core.model.JDIDebugTarget; import org.eclipse.jdt.internal.debug.core.model.JDINullValue; import org.eclipse.jdt.internal.debug.core.model.JDIObjectValue; import org.eclipse.jdt.internal.debug.core.model.JDIThread; import org.eclipse.jdt.internal.debug.ui.JDIModelPresentation; import com.sun.jdi.ObjectCollectedException; import com.sun.jdi.ThreadReference; import com.sun.jdi.VirtualMachine; public class CeylonJDIDebugTarget extends JDIDebugTarget { private IProject project = null; public CeylonJDIDebugTarget(ILaunch launch, VirtualMachine jvm, String name, boolean supportTerminate, boolean supportDisconnect, IProcess process, boolean resume) { super(launch, jvm, name, supportTerminate, supportDisconnect, process, resume); try { ILaunchConfiguration config = launch.getLaunchConfiguration(); String projectName; projectName = config.getAttribute("org.eclipse.jdt.launching.PROJECT_ATTR", ""); if (projectName != null) { IProject theProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); if (theProject.exists()) { project = theProject; } } } catch (CoreException e) { e.printStackTrace(); } } @Override protected JDIThread newThread(ThreadReference reference) { try { return new CeylonJDIThread(this, reference); } catch (ObjectCollectedException exception) { // ObjectCollectionException can be thrown if the thread has already // completed (exited) in the VM. } return null; } public IProject getProject() { return project; } private static final String getAnnotationMethodSignature = "(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;"; private static final String getAnnotationMethodName = "getAnnotation"; public IJavaValue getAnnotation(IJavaStackFrame frame, IJavaReferenceType valueType, final Class<? extends Annotation> annotationClass, final String parameter) { IJavaClassObject annotationClassObject = null; try { // TODO : The searched annotationClassObject should be cached inside the debugTarget // but the cache should be cleaned in case of hot code replace IJavaType[] jts = getJavaTypes(annotationClass.getName()); if (jts.length > 0) { if (jts[0] instanceof IJavaReferenceType) { annotationClassObject = ((IJavaReferenceType) jts[0]) .getClassObject(); } } if (annotationClassObject != null) { final IJavaClassObject ceylonAnnotationClass = annotationClassObject; final IJavaClassObject theClassObject = valueType.getClassObject(); class Listener { boolean finished = false; IJavaValue annotation = null; synchronized public void finished( IJavaValue annotation) { this.annotation = annotation; finished = true; notifyAll(); } synchronized IJavaValue waitForAnnotation() { if (!finished) { try { wait(5000); } catch (InterruptedException e1) { e1.printStackTrace(); // Fall through } } return annotation; } }; final Listener listener = new Listener(); final IJavaThread evaluationThread = JDIModelPresentation .getEvaluationThread((IJavaDebugTarget) theClassObject .getDebugTarget()); if (evaluationThread == null) { listener.finished(null); } else { evaluationThread .queueRunnable(new Runnable() { public void run() { if (evaluationThread == null || !evaluationThread.isSuspended()) { listener.finished(null); System.err.println("Annotation retrieval cancelled : thread is not suspended"); return; } IEvaluationRunnable eval = new IEvaluationRunnable() { public void run( IJavaThread innerThread, IProgressMonitor monitor) throws DebugException { try { IJavaValue result = theClassObject.sendMessage( getAnnotationMethodName, getAnnotationMethodSignature, new IJavaValue[] { ceylonAnnotationClass }, evaluationThread, (String) null); if (parameter == null) { listener.finished(result); } else { if (result instanceof JDINullValue) { listener.finished(null); } else { IJavaObject annotationObject = (IJavaObject)result; result = null; String annotationParameterMethodSignature = null; //TODO : the signatures for the annotation parameters should // be cached definitively inside the debug target. try { IJavaProject javaProject = JavaCore .create(getProject()); IType annotationType = javaProject .findType(annotationClass.getName()); IMethod method = annotationType.getMethod(parameter, new String[0]); if (method != null) { annotationParameterMethodSignature = method.getSignature(); } } catch (JavaModelException e) { e.printStackTrace(); } if (annotationParameterMethodSignature != null) { result = ((IJavaObject) annotationObject).sendMessage( parameter, annotationParameterMethodSignature, new IJavaValue[] { }, evaluationThread, (String) null); } listener.finished(result); } } } catch(Throwable t) { t.printStackTrace(); listener.finished(null); } } }; try { evaluationThread.runEvaluation( eval, null, DebugEvent.EVALUATION_IMPLICIT, false); } catch (DebugException e) { e.printStackTrace(); listener.finished(null); } } }); } return listener.waitForAnnotation(); } } catch (DebugException e) { e.printStackTrace(); } return null; } public boolean isAnnotationPresent(IJavaStackFrame frame, IJavaReferenceType valueType, final Class<? extends Annotation> annotationClass) { IJavaValue annotation = getAnnotation(frame, valueType, annotationClass, null); return annotation instanceof JDIObjectValue && !(annotation instanceof JDINullValue); } }
package org.obeonetwork.m2doc.genconf; import com.google.common.collect.Lists; import com.google.common.io.Files; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.acceleo.query.runtime.IQueryEnvironment; import org.eclipse.acceleo.query.runtime.IReadOnlyQueryEnvironment; import org.eclipse.core.runtime.Status; import org.eclipse.emf.common.util.BasicMonitor; import org.eclipse.emf.common.util.Monitor; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.URIConverter; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; import org.obeonetwork.m2doc.POIServices; import org.obeonetwork.m2doc.genconf.provider.ConfigurationProviderService; import org.obeonetwork.m2doc.genconf.provider.IConfigurationProvider; import org.obeonetwork.m2doc.genconf.util.ConfigurationServices; import org.obeonetwork.m2doc.generator.DocumentGenerationException; import org.obeonetwork.m2doc.parser.DocumentParserException; import org.obeonetwork.m2doc.parser.ValidationMessageLevel; import org.obeonetwork.m2doc.properties.TemplateCustomProperties; import org.obeonetwork.m2doc.template.DocumentTemplate; import org.obeonetwork.m2doc.util.M2DocUtils; /** * This class can be used to generate documents from {@link Generation} configuration elements. * * @author Romain Guider * @author <a href="mailto:[email protected]">Nathalie Lepine</a> */ public class GenconfToDocumentGenerator { /** * The {@link ConfigurationServices}. */ private final ConfigurationServices configurationServices = new ConfigurationServices(); /** * Generate a document from the specified generation configuration. * * @param generation * the generation configuration * @return generated file * @throws DocumentGenerationException * DocumentGenerationException * @throws DocumentParserException * DocumentParserException * @throws IOException * IOException * @deprecated the method with a monitor parameter should be prefered. */ @Deprecated public List<URI> generate(Generation generation) throws DocumentGenerationException, IOException, DocumentParserException { return generate(generation, new BasicMonitor()); } /** * Generate a document from the specified generation configuration. * * @param generation * the generation configuration * @param monitor * used to track the progress will generating. * @return generated file * @throws DocumentGenerationException * DocumentGenerationException * @throws DocumentParserException * DocumentParserException * @throws IOException * IOException */ public List<URI> generate(Generation generation, Monitor monitor) throws DocumentGenerationException, IOException, DocumentParserException { if (generation == null) { throw new IllegalArgumentException("Null configuration object passed."); } // get the template path and parses it. String templateFilePath = generation.getTemplateFileName(); if (templateFilePath == null) { throw new DocumentGenerationException("The template file path isn't set in the provided configuration"); } // get the result path and parses it. String resultFilePath = generation.getResultFileName(); if (resultFilePath == null) { throw new DocumentGenerationException("The result file path isn't set in the provided configuration"); } // get template and result file URI templateFile = createURIStartingFromCurrentModel(generation, generation.getTemplateFileName()); URI generatedFile = createURIStartingFromCurrentModel(generation, generation.getResultFileName()); if (!URIConverter.INSTANCE.exists(templateFile, Collections.EMPTY_MAP)) { throw new DocumentGenerationException("The template file doest not exist " + templateFilePath); } // generate result file. return generate(generation, templateFile, generatedFile, monitor); } /** * Creates {@link URI} starting from the current model. * * @param generation * the {@link Generation} * @param relativePath * the relative path * @return the created {@link URI} starting from the current model */ public static URI createURIStartingFromCurrentModel(Generation generation, String relativePath) { URI generationURI = generation.eResource().getURI(); URI relativeURI = URI.createURI(relativePath); return relativeURI.resolve(generationURI); } /** * Launch the documentation generation. * * @param generation * the generation configuration object * @param templateURI * the template {@link URI} * @param generatedURI * the generated docx {@link URI} * @return generated file and validation file if exists * @throws IOException * if an I/O problem occurs * @throws DocumentParserException * if the document coulnd'nt be parsed. * @throws DocumentGenerationException * if the document couldn't be generated * @deprecated the method with a monitor parameter should be preferred. */ @Deprecated public List<URI> generate(Generation generation, URI templateURI, URI generatedURI) throws IOException, DocumentParserException, DocumentGenerationException { return generate(generation, templateURI, generatedURI, new BasicMonitor()); } /** * Launch the documentation generation. * * @param generation * the generation configuration object * @param templateURI * the template {@link URI} * @param generatedURI * the generated docx {@link URI} * @param monitor * used to track the progress will generating. * @return generated file and validation file if exists * @throws IOException * if an I/O problem occurs * @throws DocumentParserException * if the document coulnd'nt be parsed. * @throws DocumentGenerationException * if the document couldn't be generated */ public List<URI> generate(Generation generation, URI templateURI, URI generatedURI, Monitor monitor) throws IOException, DocumentParserException, DocumentGenerationException { // pre generation preGenerate(generation, templateURI, generatedURI, monitor); IQueryEnvironment queryEnvironment = configurationServices.initAcceleoEnvironment(generation); monitor.beginTask("Loading models.", 2); ResourceSet resourceSetForModels = createResourceSetForModels(generation); monitor.worked(1); // create definitions Map<String, Object> definitions = configurationServices.createDefinitions(generation, resourceSetForModels); monitor.done(); // create generated file try (DocumentTemplate template = M2DocUtils.parse(templateURI, queryEnvironment, this.getClass().getClassLoader())) { // validate template monitor.beginTask("Validating template.", 1); boolean inError = validate(generatedURI, template, queryEnvironment, generation); monitor.done(); // add providers variables definitions.putAll(configurationServices.getProviderVariables(generation)); // launch generation M2DocUtils.generate(template, queryEnvironment, resourceSetForModels, definitions, URIConverter.INSTANCE, generatedURI, monitor); List<URI> generatedFiles = Lists.newArrayList(generatedURI); if (inError) { URI validationFile = getValidationLogFile(generatedURI); generatedFiles.add(validationFile); } // post generation generatedFiles.addAll(postGenerate(generation, templateURI, generatedURI, template, monitor)); return generatedFiles; } } /** * Pre generation. * * @param generation * Generation * @param templateURI * the template {@link URI} * @param generatedURI * the generated docx {@link URI} * @param monitor * used to track the progress will generating. */ public void preGenerate(Generation generation, URI templateURI, URI generatedURI, Monitor monitor) { List<IConfigurationProvider> providers = ConfigurationProviderService.getInstance().getProviders(); monitor.beginTask("Preparign document generation", providers.size()); for (IConfigurationProvider configurationProvider : providers) { if (!monitor.isCanceled()) { configurationProvider.preGenerate(generation, templateURI, generatedURI); monitor.worked(1); } } monitor.done(); } /** * Create a new resourceSet suitable for loading the models specified in the Generation objects. * * @param generation * the generation object. * @return a resourceset suitable for loading the models specified in the Generation object. */ public ResourceSet createResourceSetForModels(Generation generation) { ResourceSet created = null; Iterator<IConfigurationProvider> it = ConfigurationProviderService.getInstance().getProviders().iterator(); while (created == null && it.hasNext()) { IConfigurationProvider cur = it.next(); created = cur.createResourceSetForModels(generation); } if (created == null) { created = new ResourceSetImpl(); created.getPackageRegistry().put(GenconfPackage.eNS_URI, GenconfPackage.eINSTANCE); created.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl()); } return created; } /** * Post generation. * * @param generation * Generation * @param templateURI * the template {@link URI} * @param generatedURI * the generated docx {@link URI} * @param template * DocumentTemplate * @param monitor * used to track the progress will generating. * @return File list to return after the generation. Generation result and validation log are already in there. */ public List<URI> postGenerate(Generation generation, URI templateURI, URI generatedURI, DocumentTemplate template, Monitor monitor) { List<URI> files = Lists.newArrayList(); List<IConfigurationProvider> providers = ConfigurationProviderService.getInstance().getProviders(); monitor.beginTask("Launching post-generation tasks.", providers.size()); for (IConfigurationProvider configurationProvider : providers) { if (!monitor.isCanceled()) { List<URI> postGenerateFiles = configurationProvider.postGenerate(generation, templateURI, generatedURI, template); monitor.worked(1); if (postGenerateFiles != null) { files.addAll(postGenerateFiles); } } } monitor.done(); return files; } /** * Create genconf model from templateInfo information. * * @param templateURI * the template {@link URI} * @return configuration model * @throws InvalidFormatException * InvalidFormatException * @throws IOException * IOException */ public Resource createConfigurationModel(URI templateURI) throws IOException { Resource resource = null; TemplateCustomProperties templateProperties = POIServices.getInstance() .getTemplateCustomProperties(URIConverter.INSTANCE, templateURI); // create genconf model if (templateProperties != null) { resource = createConfigurationModel(templateProperties, templateURI); } return resource; } /** * Create genconf model from templateInfo information. * * @param templateProperties * TemplateInfo * @param templateURI * File * @return configuration model */ public Resource createConfigurationModel(TemplateCustomProperties templateProperties, final URI templateURI) { // pre model creation: by default nothing. preCreateConfigurationModel(templateProperties, templateURI); // create genconf resource. URI genConfURI = templateURI.trimFileExtension() .appendFileExtension(ConfigurationServices.GENCONF_EXTENSION_FILE); Resource resource = M2DocUtils.createResource(templateURI, genConfURI); // create initial model content. Generation rootObject = configurationServices.createInitialModel(genConfURI.trimFileExtension().lastSegment(), templateURI.deresolve(genConfURI).toString()); // add docx properties TemplateConfigurationServices.getInstance().addProperties(rootObject, templateProperties); if (rootObject != null) { resource.getContents().add(rootObject); } // Save the contents of the resource to the file system. try { M2DocUtils.saveResource(resource); } catch (IOException e) { GenconfPlugin.INSTANCE .log(new Status(Status.ERROR, GenconfPlugin.PLUGIN_ID, Status.ERROR, e.getMessage(), e)); } // post model creation: by default nothing. postCreateConfigurationModel(templateProperties, templateURI, rootObject); // Save the contents of the resource to the file system. try { M2DocUtils.saveResource(resource); } catch (IOException e) { GenconfPlugin.INSTANCE .log(new Status(Status.ERROR, GenconfPlugin.PLUGIN_ID, Status.ERROR, e.getMessage(), e)); } return resource; } /** * Post configuration model creation. * * @param templateProperties * TemplateInfo * @param templateURI * the template {@link URI} * @param generation * Generation */ public void postCreateConfigurationModel(TemplateCustomProperties templateProperties, URI templateURI, Generation generation) { for (IConfigurationProvider configurationProvider : ConfigurationProviderService.getInstance().getProviders()) { configurationProvider.postCreateConfigurationModel(templateProperties, templateURI, generation); } } /** * Pre configuration model creation. * * @param templateProperties * TemplateInfo * @param templateURI * the template {@link URI} */ public void preCreateConfigurationModel(TemplateCustomProperties templateProperties, URI templateURI) { for (IConfigurationProvider configurationProvider : ConfigurationProviderService.getInstance().getProviders()) { configurationProvider.preCreateConfigurationModel(templateProperties, templateURI); } } /** * Validate templateInfo information. * * @param generation * Generation * @return if template contains errors. * @throws IOException * IOException * @throws DocumentParserException * DocumentParserException * @throws DocumentGenerationException * DocumentGenerationException */ public boolean validate(Generation generation) throws IOException, DocumentParserException, DocumentGenerationException { final boolean res; // get the template path and parses it. String templateFilePath = generation.getTemplateFileName(); if (templateFilePath == null) { throw new DocumentGenerationException("The template file path isn't set in the provided configuration"); } URI generationURI = generation.eResource().getURI(); // get template and result file URI templateURI = URI.createFileURI(generation.getTemplateFileName()).resolve(generationURI); if (!URIConverter.INSTANCE.exists(templateURI, Collections.EMPTY_MAP)) { throw new DocumentGenerationException("The template file does not exist " + templateFilePath); } // get acceleo environment IQueryEnvironment queryEnvironment = configurationServices.initAcceleoEnvironment(generation); // parse template try (DocumentTemplate template = M2DocUtils.parse(templateURI, queryEnvironment, this.getClass().getClassLoader())) { // validate template if (template != null) { res = validate(templateURI, template, queryEnvironment, generation); } else { res = true; } } return res; } /** * Validate template with templateInfo information. * * @param templateURI * the template {@link URI} * @param documentTemplate * DocumentTemplate * @param queryEnvironment * the {@link IReadOnlyQueryEnvironment} * @param generation * Generation * @return if template contains errors/warnings/info * @throws DocumentGenerationException * DocumentGenerationException * @throws IOException * IOException */ public boolean validate(URI templateURI, DocumentTemplate documentTemplate, IReadOnlyQueryEnvironment queryEnvironment, Generation generation) throws DocumentGenerationException, IOException { URI validationFile = getValidationLogFile(templateURI); final ValidationMessageLevel validationResult = M2DocUtils.validate(documentTemplate, queryEnvironment); M2DocUtils.serializeValidatedDocumentTemplate(documentTemplate, validationFile); return validationResult == ValidationMessageLevel.ERROR && postValidateTemplate(templateURI, documentTemplate, generation); } /** * Post template validation. * * @param templateURI * the template {@link URI} * @param template * DocumentTemplate * @param generation * Generation * @return validation result. */ public boolean postValidateTemplate(URI templateURI, DocumentTemplate template, Generation generation) { boolean validate = true; for (IConfigurationProvider configurationProvider : ConfigurationProviderService.getInstance().getProviders()) { validate = validate && configurationProvider.postValidateTemplate(templateURI, template, generation); } return validate; } /** * Pre template validation. * * @param templateURI * the template URI * @param template * DocumentTemplate * @param generation * Generation */ public void preValidateTemplate(URI templateURI, DocumentTemplate template, Generation generation) { for (IConfigurationProvider configurationProvider : ConfigurationProviderService.getInstance().getProviders()) { configurationProvider.preValidateTemplate(templateURI, template, generation); } } /** * Gets the log {@link URI} for the given template {@link URI}. * * @param templateURI * the template {@link URI} * @return validation log file. */ public URI getValidationLogFile(URI templateURI) { URI validationFile = templateURI.trimSegments(1) .appendSegment(Files.getNameWithoutExtension(templateURI.lastSegment()) + "-error"); if (URI.validSegment(templateURI.fileExtension())) { validationFile = validationFile.appendFileExtension(templateURI.fileExtension()); } return validationFile; } }
package gov.nih.nci.cabig.caaers.rules.business.service; import gov.nih.nci.cabig.caaers.CaaersSystemException; import gov.nih.nci.cabig.caaers.dao.ExpeditedAdverseEventReportDao; import gov.nih.nci.cabig.caaers.dao.OrganizationDao; import gov.nih.nci.cabig.caaers.dao.report.ReportDefinitionDao; import gov.nih.nci.cabig.caaers.domain.AdverseEvent; import gov.nih.nci.cabig.caaers.domain.AdverseEventReportingPeriod; import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyOrganization; import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment; import gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection; import gov.nih.nci.cabig.caaers.domain.report.Report; import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition; import gov.nih.nci.cabig.caaers.domain.repository.ReportRepository; import gov.nih.nci.cabig.caaers.service.EvaluationService; import gov.nih.nci.cabig.caaers.service.ReportSubmittability; import gov.nih.nci.cabig.caaers.validation.ValidationErrors; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.transaction.annotation.Transactional; @Transactional(readOnly = true) public class EvaluationServiceImpl implements EvaluationService { private AdverseEventEvaluationService adverseEventEvaluationService; private static final Log log = LogFactory.getLog(EvaluationServiceImpl.class); private ReportDefinitionDao reportDefinitionDao; private ExpeditedAdverseEventReportDao expeditedAdverseEventReportDao; private ReportRepository reportRepository; private OrganizationDao organizationDao; /** * @return true if the given adverse event is severe in the context of the provided study, site, * and participant */ public boolean isSevere(StudyParticipantAssignment assignment, AdverseEvent adverseEvent) { boolean isSevere = false; try { String msg = adverseEventEvaluationService.assesAdverseEvent(adverseEvent, assignment .getStudySite().getStudy()); if ("SERIOUS_ADVERSE_EVENT".equals(msg)) { isSevere = true; } } catch (Exception e) { throw new CaaersSystemException("Could not assess the given AE", e); } return isSevere; } /** * This method will return a Map, whose keys are the {@link ReportDefinition} and values are the {@link AdverseEvent} that caused the {@link ReportDefinition}. * Note:- For every AdverseEvent, the list of report definition is obtained. A map is created with ReportDefinition as key and AdverseEvent as value. * @param reportingPeriod * @return */ public Map<ReportDefinition, List<AdverseEvent>> findRequiredReportDefinitions(AdverseEventReportingPeriod reportingPeriod){ Map<ReportDefinition, List<AdverseEvent>> map = new HashMap<ReportDefinition, List<AdverseEvent>>(); for(AdverseEvent ae : reportingPeriod.getReportableAdverseEvents()){ List<ReportDefinition> reportDefs = findRequiredReportDefinitions(null, Arrays.asList(ae), reportingPeriod.getStudy()); for(ReportDefinition reportDef : reportDefs){ if(map.containsKey(reportDef)){ map.get(reportDef).add(ae); }else { List<AdverseEvent> aeList = new ArrayList<AdverseEvent>(); aeList.add(ae); map.put(reportDef, aeList); } } } // Now we will filter out the amenable ReportDefinitions. // Prepare the Map needed for filterAmenableReportDefinitions method in EvaluationServiceImpl Map<String, List<String>> repDefinitionNamesMap = new HashMap<String,List<String>>(); List<String> repDefnNames = new ArrayList<String>(); for(ReportDefinition rDef: map.keySet()){ if(rDef != null) repDefnNames.add(rDef.getName()); } repDefinitionNamesMap.put("RepDefnNames", repDefnNames); // Call filterAmenableReportDefinitions in EvaluationServiceImpl passing repDefinitionNamesMap // The List returned is a list of ReportDefinitions with the earliest amenable reportDefinition List<ReportDefinition> amenableFilterRepDefn = filterAmenableReportDefinitions(repDefinitionNamesMap); Map<ReportDefinition, List<AdverseEvent>> filteredRepDefnToAeMap = updateReportDefnAesMap(map, amenableFilterRepDefn); return map; } /** * The report definitions that are marked as mandatory at rules engine. Bug fix : 12770, will * filter already instantiated reports (that are not in WITHDRAWN) status. * * @param expeditedData - * The {@link ExpeditedAdverseEventReport} * @return - The list of {@link ReportDefinition} objects, that are associated to this report. */ public List<ReportDefinition> findRequiredReportDefinitions( ExpeditedAdverseEventReport expeditedData, List<AdverseEvent> aeList, Study study) { Map<String, List<String>> map; List<ReportDefinition> defList = new ArrayList<ReportDefinition>(); try { map = adverseEventEvaluationService.evaluateSAEReportSchedule(expeditedData, aeList, study); } catch (Exception e) { throw new CaaersSystemException( "Could not determine the reports necessary for the given expedited adverse event data", e); } defList = filterAmenableReportDefinitions(map); List<ReportDefinition> filterdReportDefs = new ArrayList<ReportDefinition>(); // Bug fix - 12770 if(expeditedData != null){ if (defList.isEmpty() || expeditedData.getNonWithdrawnReports().isEmpty()) return defList; // Will filter already instantiated reports. for (Report report : expeditedData.getNonWithdrawnReports()) { for (ReportDefinition def : defList) { if (!def.getId().equals(report.getReportDefinition().getId())) { filterdReportDefs.add(def); } } } return filterdReportDefs; } return defList; } /** * This method received a map of the reportDefinitions that are triggered by the rules for aes provided. * It in turns filters out the amenable reportDefinitions retaining the one with shortest time-frame. * It returns a list of reportDefinitions. * @params Map<String, List<String>> * @return */ public List<ReportDefinition> filterAmenableReportDefinitions(Map<String,List<String>> map){ List<ReportDefinition> defList = new ArrayList<ReportDefinition>(); // this comparator is used to find the highest ranked report definition Comparator<ReportDefinition> c = new ReportDefinitionComparator(); Set<String> keys = map.keySet(); for (String key : keys) { List<String> reportDefNames = map.get(key); if (reportDefNames == null) continue; TreeSet<ReportDefinition> reportDefTreeSet = new TreeSet<ReportDefinition>(c); for (String reportDefName : reportDefNames) { ReportDefinition reportDef = reportDefinitionDao.getByName(reportDefName); if (reportDef.getAmendable()) { reportDefTreeSet.add(reportDef); } else { defList.add(reportDef); } } if (!reportDefTreeSet.isEmpty()) { defList.add(reportDefTreeSet.last()); } } return defList; } /** * Filter the ReportDefinition - Ae Map so that only the earliest Amendabe ReportDefinition is retained in the map. * * @param map, the initial ReportDefinition to AdverseEvent List Map. * @param repDefnList, the list containing the ReportDefinition to be retained. * @return map, the final ReportDefinition to AdverseEvent List Map which has only one (earliest) amendable ReportDefinition. */ public Map<ReportDefinition, List<AdverseEvent>>updateReportDefnAesMap(Map<ReportDefinition, List<AdverseEvent>> map , List<ReportDefinition> repDefnList){ Map<ReportDefinition, Boolean> retainedDefns = new HashMap<ReportDefinition, Boolean>(); for(ReportDefinition rd: repDefnList){ retainedDefns.put(rd, Boolean.TRUE); } // Create a list of AdverseEvents that will be migrated to the only amenable reportDefinition retained in the result map List<AdverseEvent> aeList = new ArrayList<AdverseEvent>(); List<ReportDefinition> removeRepDefn = new ArrayList<ReportDefinition>(); // This will have the list of reportDefinition // that are to be removed from the map. for(ReportDefinition rd: map.keySet()){ if(!retainedDefns.containsKey(rd)){ for(AdverseEvent ae: map.get(rd)) aeList.add(ae); removeRepDefn.add(rd); } } // Now remove the ReportDefinitions in the list removeRepDefn from the map for(ReportDefinition rd: removeRepDefn){ map.remove(rd); } // Now the adverseEvents in aeList are appended to the list of adverseEvents associated to the only amenable ReportDefinition // in the filteredMap Map<AdverseEvent, Boolean> existingAeMap = new HashMap<AdverseEvent, Boolean>(); for(ReportDefinition rd: map.keySet()){ if(rd.getAmendable()){ for(AdverseEvent ae: map.get(rd)) existingAeMap.put(ae, Boolean.TRUE); // Now add the AdverseEvents from aeList to this list for(AdverseEvent ae: aeList) if(!existingAeMap.containsKey(ae)) map.get(rd).add(ae); } } return map; } /** * Evaluates the provided data and associates new {@link Report} instances with the given * {@link ExpeditedAdverseEventReport}. * <p> * This method may be called multiple times for the same expedited data. Implementors must be * sure not to add multiple {@link Report}s for the same {@link ReportDefinition}. * Implementors must also <em>not</em> remove * {@link gov.nih.nci.cabig.caaers.domain.report.Report}s if they don't evaluate as required * (e.g., some reports may have been directly selected by the user). Instead, implementors * should update the {@link Report#setRequired} flag. * * @param expeditedData * @return the report definitions which the evaluation indicated were required. */ /* * @Transactional(readOnly=false) public void addRequiredReports(ExpeditedAdverseEventReport * expeditedData) { Map<String,List<String>> map; List<String> reportDefinitionNames = new * ArrayList<String>(); try { map = * adverseEventEvaluationService.evaluateSAEReportSchedule(expeditedData); } catch (Exception e) { * throw new CaaersSystemException( "Could not determine the reports necessary for the given * expedited adverse event data", e); } * * Set<String> keys = map.keySet(); for (String key : keys) { List<String> reportDefNames = * map.get(key); // TO-DO need to clarify this ranking incase of multi actions in rules if * (reportDefNames.size() != 0) { String reportDefName = * extractTopPriorityReportDefintionName(reportDefNames); System.out.println("adding ..." + * reportDefName); reportDefinitionNames.add(reportDefName); } * * //uncomment the above part and comment the below code after figuring oout ranking. //for * (String reportDefName : reportDefNames) { //reportDefinitionNames.add(reportDefName); //} } * * for (Object reportDefinitionName : reportDefinitionNames) { * * ReportDefinition def = reportDefinitionDao.getByName(reportDefinitionName.toString()); Report * report = existingReportWithDef(expeditedData, def); * * if (report == null) { report = reportService.createReport(def, expeditedData); * //expeditedAdverseEventReportDao.save(expeditedData); } report.setRequired(true); } * } */ /** * Will create the Report by calling ReportService, then saves the ExpeditedAdverseEventReport */ @Transactional(readOnly = false) public void addOptionalReports(ExpeditedAdverseEventReport expeditedData, Collection<ReportDefinition> reportDefs) { for (ReportDefinition def : reportDefs) { reportRepository.createReport(def, expeditedData); } expeditedAdverseEventReportDao.save(expeditedData); } private Report existingReportWithDef(ExpeditedAdverseEventReport expeditedData, ReportDefinition def) { for (Report report : expeditedData.getReports()) { log.debug("Examining Report with def " + report.getReportDefinition().getName() + " (id: " + report.getReportDefinition().getId() + "; hash: " + Integer.toHexString(report.getReportDefinition().hashCode()) + ')'); if (report.getReportDefinition().equals(def)) { log.debug("Matched"); return report; } } log.debug("No Report with def matching " + def.getName() + " (id: " + def.getId() + "; hash: " + Integer.toHexString(def.hashCode()) + ") found in EAER " + expeditedData.getId()); return null; } /** * @return All the report definitions which might apply to the given study, site, and * participant */ // TODO: it might more sense for this to go in ReportService public List<ReportDefinition> applicableReportDefinitions(StudyParticipantAssignment assignment) { List<ReportDefinition> reportDefinitions = new ArrayList<ReportDefinition>(); // Same organization play multiple roles. Set<Integer> orgIdSet = new HashSet<Integer>(); for (StudyOrganization studyOrganization : assignment.getStudySite().getStudy() .getStudyOrganizations()) { orgIdSet.add(studyOrganization.getOrganization().getId()); } for (Integer orgId : orgIdSet) { reportDefinitions.addAll(reportDefinitionDao.getAll(orgId)); } /** * Get REport definitions of CTEP for DCP studies , because DCP uses CTEP * report definitions also . TEMP fix */ if (assignment.getStudySite().getStudy().getPrimaryFundingSponsor().getOrganization().getName().equals("Division of Cancer Prevention")) { reportDefinitions.addAll(reportDefinitionDao.getAll(this.organizationDao.getByName("Cancer Therapy Evaluation Program").getId())); } return reportDefinitions; } @Deprecated private String extractTopPriorityReportDefinition(List<ReportDefinition> reportDefs) { // XXX: You could do this without the array conversion using Collections.sort Comparator<ReportDefinition> c = new ReportDefinitionComparator(); ReportDefinition[] reportDefArray = new ReportDefinition[reportDefs.size()]; java.util.Arrays.sort(reportDefs.toArray(reportDefArray), c); ReportDefinition reportDefinition = reportDefArray[reportDefArray.length - 1]; return reportDefinition.getName(); } public Collection<ExpeditedReportSection> mandatorySections( ExpeditedAdverseEventReport expeditedData) { try { Collection<ExpeditedReportSection> sections = adverseEventEvaluationService .mandatorySections(expeditedData); if (log.isDebugEnabled()) log.debug("Mandatory sections: " + sections); return sections; } catch (Exception e) { throw new CaaersSystemException("Could not get mandatory sections", e); } } /** * Checks whether all the mandatory fields, are duly filled. If the report is complete, the * ErrorMessages will be empty * * @param report - * {@link Report} * @return {@link ReportSubmittability} */ // return type based on the method name, is misleading,need to find a better name. public ReportSubmittability isSubmittable(Report report) { return reportRepository.validate(report); /* * -- commented based on the new biz rule try { return reportService.validate(report, * adverseEventEvaluationService.mandatorySectionsForReport(report)); } catch * (RuntimeException re) { throw re; } catch (Exception e) { throw new * CaaersSystemException("Unable to determine mandatory sections", e); } */ } public ValidationErrors validateReportingBusinessRules(ExpeditedAdverseEventReport aeReport, ExpeditedReportSection sections) { try { return adverseEventEvaluationService.validateReportingBusinessRules(aeReport, sections); } catch (Exception e) { log.error("Error while evaluating business rules", e); throw new CaaersSystemException("Error while evaluating business rules", e); } } // //// CONFIGURATION public void setReportDefinitionDao(ReportDefinitionDao reportDefinitionDao) { this.reportDefinitionDao = reportDefinitionDao; } public void setExpeditedAdverseEventReportDao( ExpeditedAdverseEventReportDao expeditedAdverseEventReportDao) { this.expeditedAdverseEventReportDao = expeditedAdverseEventReportDao; } public void setReportRepository(ReportRepository reportRepository) { this.reportRepository = reportRepository; } public void setAdverseEventEvaluationService( AdverseEventEvaluationService adverseEventEvaluationService) { this.adverseEventEvaluationService = adverseEventEvaluationService; } public AdverseEventEvaluationService getAdverseEventEvaluationService() { return adverseEventEvaluationService; } public void setOrganizationDao(OrganizationDao organizationDao) { this.organizationDao = organizationDao; } }
package com.kislay.rulette.evaluationengine.impl.trie; import com.kislay.rulette.evaluationengine.IEvaluationEngine; import com.kislay.rulette.evaluationengine.impl.trie.node.Node; import com.kislay.rulette.evaluationengine.impl.trie.node.RangeNode; import com.kislay.rulette.evaluationengine.impl.trie.node.ValueNode; import com.kislay.rulette.metadata.RuleSystemMetaData; import com.kislay.rulette.rule.Rule; import com.kislay.rulette.ruleinput.RuleInputMetaData; import com.kislay.rulette.ruleinput.RuleType; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.concurrent.ConcurrentHashMap; /** * * @author kislay.verma */ public class TrieBasedEvaluationEngine implements IEvaluationEngine { private final RuleSystemMetaData metaData; private final Map<Integer, Rule> allRules = new ConcurrentHashMap<>(); private final Node root; public TrieBasedEvaluationEngine(RuleSystemMetaData metaData) throws Exception { this(metaData, null); } public TrieBasedEvaluationEngine(RuleSystemMetaData metaData, List<Rule> rules) throws Exception { this.metaData = metaData; if (this.metaData.getInputColumnList().get(0).getRuleType().equals(RuleType.VALUE)) { this.root = new ValueNode(this.metaData.getInputColumnList().get(0).getName()); } else { this.root = new RangeNode(this.metaData.getInputColumnList().get(0).getName()); } if (rules != null) { for (Rule rule : rules) { addRule(rule); } } } @Override public List<Rule> getAllRules() { return new ArrayList<>(this.allRules.values()); } @Override public Rule getRule(Integer ruleId) { if (ruleId == null) { return null; } return this.allRules.get(ruleId); } @Override public Rule getRule(Map<String, String> inputMap) throws Exception { List<Rule> eligibleRules = getEligibleRules(inputMap); if (eligibleRules != null && !eligibleRules.isEmpty()) { return eligibleRules.get(0); } return null; } @Override public Rule getNextApplicableRule(Map<String, String> inputMap) throws Exception { List<Rule> eligibleRules = getEligibleRules(inputMap); if (eligibleRules != null && eligibleRules.size() > 1) { return eligibleRules.get(1); } return null; } @Override public void addRule(Rule rule) throws Exception { Node currNode = this.root; for (int i = 0; i < metaData.getInputColumnList().size(); i++) { RuleInputMetaData currInput = metaData.getInputColumnList().get(i); // 1. See if the current node has a node mapping to the field value List<Node> nodeList = currNode.getNodesForAddingRule(rule.getColumnData(currInput.getName()).getRawValue()); // 2. If it doesn't, create a new empty node and map the field value // to the new node. // Also move to the new node. if (nodeList.isEmpty()) { Node newNode; if (i < metaData.getInputColumnList().size() - 1) { if (metaData.getInputColumnList().get(i + 1).getRuleType().equals(RuleType.VALUE)) { newNode = new ValueNode(metaData.getInputColumnList().get(i + 1).getName()); } else { newNode = new RangeNode(metaData.getInputColumnList().get(i + 1).getName()); } } else { newNode = new ValueNode(""); } currNode.addChildNode(rule.getColumnData(currInput.getName()), newNode); currNode = newNode; } // 3. If it does, move to that node. else { currNode = nodeList.get(0); } } currNode.setRule(rule); this.allRules.put( Integer.parseInt(rule.getColumnData(metaData.getUniqueIdColumnName()).getRawValue()), rule); } @Override public void deleteRule(Rule rule) throws Exception { // Delete the rule from the map this.allRules.remove( Integer.parseInt(rule.getColumnData(metaData.getUniqueIdColumnName()).getRawValue())); // Locate and delete the rule from the trie Stack<Node> stack = new Stack<>(); Node currNode = this.root; for (RuleInputMetaData rimd : metaData.getInputColumnList()) { String value = rule.getColumnData(rimd.getName()).getRawValue(); value = (value == null) ? "" : value; Node nextNode = currNode.getMatchingRule(value); stack.push(currNode); currNode = nextNode; } if (!currNode.getRule().getColumnData(metaData.getUniqueIdColumnName()).equals( rule.getColumnData(metaData.getUniqueIdColumnName()))) { throw new Exception("The rule to be deleted and the rule found are not the same." + "Something went horribly wrong"); } // Get rid of the leaf node stack.pop(); // Handle the ancestors of the leaf while (!stack.isEmpty()) { Node node = stack.pop(); // Visit nodes in leaf to root order and: // 1. If this is the only value in the popped node, delete the node. // 2. If there are other values too, remove this value from the node. if (node.getCount() <= 1) { node = null; } else { node.removeChildNode(rule.getColumnData(node.getName())); } } } private List<Rule> getEligibleRules(Map<String, String> inputMap) throws Exception { if (inputMap != null) { Stack<Node> currStack = new Stack<>(); currStack.add(root); for (RuleInputMetaData rimd : metaData.getInputColumnList()) { Stack<Node> nextStack = new Stack<>(); for (Node node : currStack) { String value = inputMap.get(rimd.getName()); value = (value == null) ? "" : value; List<Node> eligibleRules = node.getNodes(value, true); if (eligibleRules != null && !eligibleRules.isEmpty()) { nextStack.addAll(eligibleRules); } else { throw new RuntimeException("No rule found. Field " + rimd.getName() + " mismatched"); } } currStack = nextStack; } if (!currStack.isEmpty()) { List<Rule> rules = new ArrayList<>(); for (Node node : currStack) { if (node.getRule() != null) { rules.add(node.getRule()); } } Collections.sort(rules, new RuleComparator()); return rules; } } return null; } /* * This class is used to sort lists of eligible rules to get the best fitting rule. * The sort also helps in determining the next applicable rule. It is not meant as * a general rule comparator as that does not make any sense at all (which is also why * the Rule class does not implement Comparable - it would suggest that, in general, * rules can be compared against each other for priority ordering or whatever). * * The comparator iterates over the input fields in decreasing order of priority and ranks * a specific value higher than 'Any'. */ private class RuleComparator implements Comparator<Rule> { @Override public int compare(Rule rule1, Rule rule2) { for (RuleInputMetaData col : metaData.getInputColumnList()) { String colName = col.getName(); if (colName.equals(metaData.getUniqueIdColumnName()) || colName.equals(metaData.getUniqueOutputColumnName())) { continue; } String colValue1 = rule1.getColumnData(colName).getRawValue(); colValue1 = (colValue1 == null) ? "" : colValue1; String colValue2 = rule2.getColumnData(colName).getRawValue(); colValue2 = (colValue2 == null) ? "" : colValue2; /* * In going down the order of priority of inputs, the first mismatch will * yield the answer of the comparison. "" (meaning 'Any') matches everything, * but an exact match is better. So if the column values are unequal, whichever * rule has non-'Any' as the value will rank higher. */ if (!colValue1.equals(colValue2)) { return "".equals(colValue1) ? 1 : -1; } } // If all column values are same return 0; } } }
package org.eclipse.che.selenium.miscellaneous; import static java.lang.String.format; import static org.eclipse.che.selenium.core.constant.TestCommandsConstants.CUSTOM; import static org.eclipse.che.selenium.core.constant.TestMenuCommandsConstants.Assistant.ASSISTANT; import static org.eclipse.che.selenium.core.constant.TestMenuCommandsConstants.Assistant.NAVIGATE_TO_FILE; import static org.eclipse.che.selenium.core.project.ProjectTemplates.MAVEN_SIMPLE; import static org.eclipse.che.selenium.core.utils.WaitUtils.sleepQuietly; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.google.common.collect.ImmutableMap; import com.google.inject.Inject; import java.net.URL; import java.nio.file.Paths; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import org.eclipse.che.selenium.core.client.TestCommandServiceClient; import org.eclipse.che.selenium.core.client.TestProjectServiceClient; import org.eclipse.che.selenium.core.workspace.TestWorkspace; import org.eclipse.che.selenium.pageobject.CodenvyEditor; import org.eclipse.che.selenium.pageobject.Ide; import org.eclipse.che.selenium.pageobject.Loader; import org.eclipse.che.selenium.pageobject.Menu; import org.eclipse.che.selenium.pageobject.NavigateToFile; import org.eclipse.che.selenium.pageobject.ProjectExplorer; import org.eclipse.che.selenium.pageobject.intelligent.CommandsPalette; import org.openqa.selenium.WebDriverException; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class NavigateToFileTest { private static final String PROJECT_NAME = "NavigateFile"; private static final String PROJECT_NAME_2 = "NavigateFile_2"; private static final String FILE_CREATED_FROM_CONSOLE = "createdFrom.con"; private static final String COMMAND_FOR_FILE_CREATION = "createFile"; private static final String HIDDEN_FOLDER_NAME = ".hiddenFolder"; private static final String HIDDEN_FILE_NAME = ".hiddenFile"; private static final String FILE_IN_HIDDEN_FOLDER = "innerFile.css"; private static final int MAX_TIMEOUT_FOR_UPDATING_INDEXES = 10; @Inject private TestWorkspace workspace; @Inject private Ide ide; @Inject private ProjectExplorer projectExplorer; @Inject private Loader loader; @Inject private CodenvyEditor editor; @Inject private NavigateToFile navigateToFile; @Inject private Menu menu; @Inject private TestProjectServiceClient testProjectServiceClient; @Inject private TestCommandServiceClient testCommandServiceClient; @Inject private CommandsPalette commandsPalette; @BeforeClass public void setUp() throws Exception { URL resource = getClass().getResource("/projects/guess-project"); testProjectServiceClient.importProject( workspace.getId(), Paths.get(resource.toURI()), PROJECT_NAME, MAVEN_SIMPLE); testProjectServiceClient.importProject( workspace.getId(), Paths.get(resource.toURI()), PROJECT_NAME_2, MAVEN_SIMPLE); testCommandServiceClient.createCommand( format("touch /projects/%s/%s", PROJECT_NAME_2, FILE_CREATED_FROM_CONSOLE), COMMAND_FOR_FILE_CREATION, CUSTOM, workspace.getId()); ide.open(workspace); ide.waitOpenedWorkspaceIsReadyToUse(); projectExplorer.waitItem(PROJECT_NAME); projectExplorer.waitItem(PROJECT_NAME_2); } @Test(dataProvider = "dataForCheckingTheSameFileInDifferentProjects") public void shouldNavigateToFileForFirstProject( String inputValueForChecking, Map<Integer, String> expectedValues) { // Open the project one and check function 'Navigate To File' launchNavigateToFileAndCheckResults(inputValueForChecking, expectedValues, 1); } @Test(dataProvider = "dataForCheckingTheSameFileInDifferentProjects") public void shouldDoNavigateToFileForSecondProject( String inputValueForChecking, Map<Integer, String> expectedValues) { launchNavigateToFileAndCheckResults(inputValueForChecking, expectedValues, 2); } @Test(dataProvider = "dataToNavigateToFileCreatedOutsideIDE") public void shouldNavigateToFileWithJustCreatedFiles( String inputValueForChecking, Map<Integer, String> expectedValues) throws Exception { String content = "NavigateToFileTest"; testProjectServiceClient.createFileInProject( workspace.getId(), PROJECT_NAME, expectedValues.get(1).split(" ")[0], content); commandsPalette.openCommandPalette(); commandsPalette.startCommandByDoubleClick(COMMAND_FOR_FILE_CREATION); sleepQuietly(MAX_TIMEOUT_FOR_UPDATING_INDEXES); int randomItemFromList = ThreadLocalRandom.current().nextInt(1, 2); launchNavigateToFileAndCheckResults(inputValueForChecking, expectedValues, randomItemFromList); } @Test public void shouldNotDisplayHiddenFilesAndFoldersInDropDown() throws Exception { addHiddenFoldersAndFileThroughProjectService(); launchNavigateToFileFromUIAndTypeValue(FILE_IN_HIDDEN_FOLDER); assertTrue(navigateToFile.getText().isEmpty()); navigateToFile.closeNavigateToFileForm(); launchNavigateToFileFromUIAndTypeValue(HIDDEN_FILE_NAME); assertTrue(navigateToFile.getText().isEmpty()); } @Test(dataProvider = "dataToCheckNavigateByNameWithSpecialSymbols") public void shouldDisplayFilesFoundByMask( String inputValueForChecking, Map<Integer, String> expectedValues) { launchNavigateToFileFromUIAndTypeValue(inputValueForChecking); navigateToFile.waitSuggestedPanel(); waitExpectedItemsInNavigateToFileDropdown(expectedValues); navigateToFile.closeNavigateToFileForm(); navigateToFile.waitFormToClose(); } private void addHiddenFoldersAndFileThroughProjectService() throws Exception { testProjectServiceClient.createFolder( workspace.getId(), PROJECT_NAME + "/" + HIDDEN_FOLDER_NAME); testProjectServiceClient.createFileInProject( workspace.getId(), PROJECT_NAME + "/" + HIDDEN_FOLDER_NAME, FILE_IN_HIDDEN_FOLDER, "contentFile1"); testProjectServiceClient.createFileInProject( workspace.getId(), PROJECT_NAME_2 + "/", HIDDEN_FILE_NAME, "content-of-hidden-file"); sleepQuietly(MAX_TIMEOUT_FOR_UPDATING_INDEXES); } private void launchNavigateToFileAndCheckResults( String navigatingValue, Map<Integer, String> expectedItems, final int numValueFromDropDawnList) { // extract the path (without opened class) String dropdownVerificationPath = expectedItems.get(numValueFromDropDawnList).split(" ")[1]; String openedFileWithExtension = expectedItems.get(numValueFromDropDawnList).split(" ")[0]; // extract the name of opened files that display in a tab (the ".java" extension are not shown // in tabs) String openedFileNameInTheTab = openedFileWithExtension.replace(".java", ""); launchNavigateToFileFromUIAndTypeValue(navigatingValue); navigateToFile.waitSuggestedPanel(); waitExpectedItemsInNavigateToFileDropdown(expectedItems); try { navigateToFile.selectFileByName(dropdownVerificationPath); } catch (WebDriverException ex) { // remove try-catch block after issue has been resolved fail("Known issue https://github.com/eclipse/che/issues/8465", ex); } editor.waitActive(); editor.getAssociatedPathFromTheTab(openedFileNameInTheTab); editor.closeFileByNameWithSaving(openedFileNameInTheTab); } private void launchNavigateToFileFromUIAndTypeValue(String navigatingValue) { loader.waitOnClosed(); menu.runCommand(ASSISTANT, NAVIGATE_TO_FILE); navigateToFile.waitFormToOpen(); loader.waitOnClosed(); navigateToFile.typeSymbolInFileNameField(navigatingValue); loader.waitOnClosed(); } private void waitExpectedItemsInNavigateToFileDropdown(Map<Integer, String> expectedItems) { expectedItems .values() .stream() .map(it -> it.toString()) .forEach(it -> Assert.assertTrue(navigateToFile.isFilenameSuggested(it))); } @DataProvider private Object[][] dataForCheckingTheSameFileInDifferentProjects() { return new Object[][] { { "A", ImmutableMap.of( 1, "AppController.java (/NavigateFile/src/main/java/org/eclipse/qa/examples)", 2, "AppController.java (/NavigateFile_2/src/main/java/org/eclipse/qa/examples)") }, { "R", ImmutableMap.of( 1, "README.md (/NavigateFile)", 2, "README.md (/NavigateFile_2)") } }; } @DataProvider private Object[][] dataToNavigateToFileCreatedOutsideIDE() { return new Object[][] { { "c", ImmutableMap.of( 1, "createdFrom.api (/NavigateFile)", 2, "createdFrom.con (/NavigateFile_2)") } }; } @DataProvider private Object[][] dataToCheckNavigateByNameWithSpecialSymbols() { return new Object[][] { { "*.java", ImmutableMap.of( 1, "AppController.java (/NavigateFile/src/main/java/org/eclipse/qa/examples)", 2, "AppController.java (/NavigateFile_2/src/main/java/org/eclipse/qa/examples)") }, { "ind*.jsp", ImmutableMap.of( 1, "index.jsp (/NavigateFile/src/main/webapp)", 2, "index.jsp (/NavigateFile_2/src/main/webapp)") }, { "*R*.md", ImmutableMap.of( 1, "README.md (/NavigateFile)", 2, "README.md (/NavigateFile_2)") }, { "we?.xml", ImmutableMap.of( 1, "web.xml (/NavigateFile/src/main/webapp/WEB-INF)", 2, "web.xml (/NavigateFile_2/src/main/webapp/WEB-INF)") }, { "gu?ss_n?m.j?p", ImmutableMap.of( 1, "guess_num.jsp (/NavigateFile/src/main/webapp/WEB-INF/jsp)", 2, "guess_num.jsp (/NavigateFile_2/src/main/webapp/WEB-INF/jsp)") } }; } }
package org.zanata.webtrans.client.editor.table; import net.customware.gwt.presenter.client.EventBus; import org.zanata.webtrans.client.events.CopySourceEvent; import org.zanata.webtrans.client.ui.HighlightingLabel; import org.zanata.webtrans.shared.model.TransUnit; import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.gen2.table.client.AbstractColumnDefinition; import com.google.gwt.gen2.table.client.CellRenderer; import com.google.gwt.gen2.table.client.ColumnDefinition; import com.google.gwt.gen2.table.client.DefaultTableDefinition; import com.google.gwt.gen2.table.client.RowRenderer; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; public class TableEditorTableDefinition extends DefaultTableDefinition<TransUnit> { // public static final int INDICATOR_COL = 0; public static final int SOURCE_COL = 0; public static final int TARGET_COL = 1; private String findMessage; private SourcePanel sourcePanel; private EventBus eventBus; private final RowRenderer<TransUnit> rowRenderer = new RowRenderer<TransUnit>() { @Override public void renderRowValue(TransUnit rowValue, AbstractRowView<TransUnit> view) { String styles = "TableEditorRow "; styles += view.getRowIndex() % 2 == 0 ? "odd-row" : "even-row"; String state = ""; switch (rowValue.getStatus()) { case Approved: state = " Approved"; break; case NeedReview: state = " Fuzzy"; break; case New: state = " New"; break; } styles += state + "StateDecoration"; view.setStyleName(styles); } }; // private final AbstractColumnDefinition<TransUnit, TransUnit> // indicatorColumnDefinition = // new AbstractColumnDefinition<TransUnit, TransUnit>() { // @Override // public TransUnit getCellValue(TransUnit rowValue) { // return rowValue; // @Override // public void setCellValue(TransUnit rowValue, TransUnit cellValue) { // cellValue.setSource(rowValue.getSource()); // private final CellRenderer<TransUnit, TransUnit> indicatorCellRenderer = // new CellRenderer<TransUnit, TransUnit>() { // @Override // public void renderRowValue( // TransUnit rowValue, // ColumnDefinition<TransUnit, TransUnit> columnDef, // com.google.gwt.gen2.table.client.TableDefinition.AbstractCellView<TransUnit> // view) { // view.setStyleName("TableEditorCell TableEditorCell-Source"); // if(rowValue.getEditStatus().equals(EditState.Lock)) { // Image image = new Image("../img/silk/user.png"); // view.setWidget(image); private final AbstractColumnDefinition<TransUnit, TransUnit> sourceColumnDefinition = new AbstractColumnDefinition<TransUnit, TransUnit>() { @Override public TransUnit getCellValue(TransUnit rowValue) { return rowValue; } @Override public void setCellValue(TransUnit rowValue, TransUnit cellValue) { cellValue.setSource(rowValue.getSource()); cellValue.setSourceComment(rowValue.getSourceComment()); } }; private final CellRenderer<TransUnit, TransUnit> sourceCellRenderer = new CellRenderer<TransUnit, TransUnit>() { @Override public void renderRowValue(final TransUnit rowValue, ColumnDefinition<TransUnit, TransUnit> columnDef, AbstractCellView<TransUnit> view) { view.setStyleName("TableEditorCell TableEditorCell-Source"); TableResources images = GWT.create(TableResources.class); final Image copyButton = new Image(images.copySrcButton()); copyButton.setStyleName("gwt-Button"); // copyButton.setStyleName("gwt-Button-display-onhover"); copyButton.setTitle(messages.copySourcetoTarget()); copyButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rowValue.setTarget(rowValue.getSource()); eventBus.fireEvent(new CopySourceEvent(rowValue)); } }); sourcePanel = new SourcePanel(rowValue, messages); if (findMessage != null && !findMessage.isEmpty()) { sourcePanel.highlightSearch(findMessage); } sourcePanel.getLabel().sinkEvents(Event.ONCLICK); sourcePanel.getLabel().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Log.debug("click"); if (targetCellEditor.isOpened()) { targetCellEditor.acceptEdit(); } } }); sourcePanel.add(copyButton); view.setWidget(sourcePanel); } }; private final AbstractColumnDefinition<TransUnit, TransUnit> targetColumnDefinition = new AbstractColumnDefinition<TransUnit, TransUnit>() { @Override public TransUnit getCellValue(TransUnit rowValue) { return rowValue; } @Override public void setCellValue(TransUnit rowValue, TransUnit cellValue) { cellValue.setTarget(rowValue.getTarget()); } }; private final CellRenderer<TransUnit, TransUnit> targetCellRenderer = new CellRenderer<TransUnit, TransUnit>() { @Override public void renderRowValue(TransUnit rowValue, ColumnDefinition<TransUnit, TransUnit> columnDef, AbstractCellView<TransUnit> view) { view.setStyleName("TableEditorCell TableEditorCell-Target"); final Label label = new HighlightingLabel(); // if editor is opening, do not render target cell, otherwise editor // will be closed // targetCellEditor.isEditing not suitable since when we click the save // button, cellValue is not null. if (targetCellEditor.isOpened()) return; if (rowValue.getTarget().isEmpty()) { label.setText(messages.clickHere()); label.setStylePrimaryName("TableEditorContent-Empty"); } else { label.setText(rowValue.getTarget()); label.setStylePrimaryName("TableEditorContent"); } if (findMessage != null && !findMessage.isEmpty()) { ((HighlightingLabel) label).highlightSearch(findMessage); } label.setTitle(messages.clickHere()); // TODO label.setTitle(rowValue.getTargetComment()); view.setWidget(label); } }; private InlineTargetCellEditor targetCellEditor; private final NavigationMessages messages; public void setFindMessage(String findMessage) { Log.info("set find message: " + findMessage); this.findMessage = findMessage; } public TableEditorTableDefinition(final NavigationMessages messages, final RedirectingCachedTableModel<TransUnit> tableModel, final EventBus eventBus) { this.messages = messages; this.eventBus = eventBus; setRowRenderer(rowRenderer); // indicatorColumnDefinition.setMaximumColumnWidth(15); // indicatorColumnDefinition.setPreferredColumnWidth(15); // indicatorColumnDefinition.setMinimumColumnWidth(15); // indicatorColumnDefinition.setCellRenderer(indicatorCellRenderer); sourceColumnDefinition.setCellRenderer(sourceCellRenderer); targetColumnDefinition.setCellRenderer(targetCellRenderer); CancelCallback<TransUnit> cancelCallBack = new CancelCallback<TransUnit>() { @Override public void onCancel(TransUnit cellValue) { tableModel.onCancel(cellValue); } }; EditRowCallback transValueCallBack = new EditRowCallback() { @Override public void gotoNextRow(int row) { tableModel.gotoNextRow(row); } @Override public void gotoPrevRow(int row) { tableModel.gotoPrevRow(row); } @Override public void gotoNextFuzzy(int row) { tableModel.gotoNextFuzzy(row); } @Override public void gotoPrevFuzzy(int row) { tableModel.gotoPrevFuzzy(row); } }; this.targetCellEditor = new InlineTargetCellEditor(messages, cancelCallBack, transValueCallBack, eventBus); targetColumnDefinition.setCellEditor(targetCellEditor); // See _INDEX consts above if modifying! // addColumnDefinition(indicatorColumnDefinition); addColumnDefinition(sourceColumnDefinition); addColumnDefinition(targetColumnDefinition); } public InlineTargetCellEditor getTargetCellEditor() { return targetCellEditor; } }
package gov.nih.nci.cananolab.service.protocol.impl; import gov.nih.nci.cananolab.domain.common.Protocol; import gov.nih.nci.cananolab.domain.particle.Characterization; import gov.nih.nci.cananolab.dto.common.AccessibilityBean; import gov.nih.nci.cananolab.dto.common.ProtocolBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.exception.NoAccessException; import gov.nih.nci.cananolab.exception.ProtocolException; import gov.nih.nci.cananolab.service.BaseServiceLocalImpl; import gov.nih.nci.cananolab.service.common.impl.FileServiceLocalImpl; import gov.nih.nci.cananolab.service.protocol.ProtocolService; import gov.nih.nci.cananolab.service.protocol.helper.ProtocolServiceHelper; import gov.nih.nci.cananolab.service.security.SecurityService; import gov.nih.nci.cananolab.system.applicationservice.CustomizedApplicationService; import gov.nih.nci.cananolab.util.Comparators; import gov.nih.nci.system.client.ApplicationServiceProvider; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Property; /** * Local implementation of ProtocolService * * @author pansu * */ public class ProtocolServiceLocalImpl extends BaseServiceLocalImpl implements ProtocolService { private static Logger logger = Logger .getLogger(ProtocolServiceLocalImpl.class); private ProtocolServiceHelper helper; private FileServiceLocalImpl fileService; public ProtocolServiceLocalImpl() { super(); helper = new ProtocolServiceHelper(this.securityService); fileService = new FileServiceLocalImpl(this.securityService); } public ProtocolServiceLocalImpl(UserBean user) { super(user); helper = new ProtocolServiceHelper(this.securityService); fileService = new FileServiceLocalImpl(this.securityService); } public ProtocolServiceLocalImpl(SecurityService securityService) { super(securityService); helper = new ProtocolServiceHelper(this.securityService); fileService = new FileServiceLocalImpl(this.securityService); } public ProtocolBean findProtocolById(String protocolId) throws ProtocolException, NoAccessException { ProtocolBean protocolBean = null; try { Protocol protocol = helper.findProtocolById(protocolId); if (protocol != null) { protocolBean = loadProtocolBean(protocol); } } catch (NoAccessException e) { throw e; } catch (Exception e) { String err = "Problem finding the protocol by id: " + protocolId; logger.error(err, e); throw new ProtocolException(err, e); } return protocolBean; } private ProtocolBean loadProtocolBean(Protocol protocol) throws Exception { ProtocolBean protocolBean = new ProtocolBean(protocol); if (user != null) { List<AccessibilityBean> groupAccesses = super .findGroupAccessibilities(protocol.getId().toString()); List<AccessibilityBean> userAccesses = super .findUserAccessibilities(protocol.getId().toString()); protocolBean.setUserAccesses(userAccesses); protocolBean.setGroupAccesses(groupAccesses); } return protocolBean; } /** * Persist a new protocol file or update an existing protocol file * * @param protocolBean * @throws Exception */ public void saveProtocol(ProtocolBean protocolBean) throws ProtocolException, NoAccessException { if (user == null) { throw new NoAccessException(); } try { Boolean newProtocol = true; if (protocolBean.getDomain().getId() != null) { newProtocol = false; if (!securityService.checkCreatePermission(protocolBean .getDomain().getId().toString())) { throw new NoAccessException(); } } if (protocolBean.getFileBean() != null) { fileService.prepareSaveFile(protocolBean.getFileBean() .getDomainFile()); } Protocol dbProtocol = helper.findProtocolBy(protocolBean .getDomain().getType(), protocolBean.getDomain().getName(), protocolBean.getDomain().getVersion()); if (dbProtocol != null) { if (dbProtocol.getId() != protocolBean.getDomain().getId()) { protocolBean.getDomain().setId(dbProtocol.getId()); } protocolBean.getDomain() .setCreatedBy(dbProtocol.getCreatedBy()); protocolBean.getDomain().setCreatedDate( dbProtocol.getCreatedDate()); } // protocol type, name or version has been updated but protocol ID // was kept else if (protocolBean.getDomain().getId() != null) { protocolBean.getDomain().setId(null); protocolBean.getDomain().setCreatedBy( helper.getUser().getLoginName()); protocolBean.getDomain().setCreatedDate(new Date()); } CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider .getApplicationService(); appService.saveOrUpdate(protocolBean.getDomain()); // save to the file system fileData is not empty if (protocolBean.getFileBean() != null) { fileService.writeFile(protocolBean.getFileBean()); } // save default accesses if (newProtocol) { super.saveDefaultAccessibility(protocolBean.getDomain().getId() .toString()); } } catch (Exception e) { String err = "Error in saving the protocol file."; logger.error(err, e); throw new ProtocolException(err, e); } } public ProtocolBean findProtocolBy(String protocolType, String protocolName, String protocolVersion) throws ProtocolException, NoAccessException { try { Protocol protocol = helper.findProtocolBy(protocolType, protocolName, protocolVersion); if (protocol != null) { ProtocolBean protocolBean = loadProtocolBean(protocol); return protocolBean; } else { return null; } } catch (NoAccessException e) { throw e; } catch (Exception e) { String err = "Problem finding protocol by name and type."; logger.error(err, e); throw new ProtocolException(err, e); } } public List<ProtocolBean> findProtocolsBy(String protocolType, String protocolName, String protocolAbbreviation, String fileTitle) throws ProtocolException { List<ProtocolBean> protocolBeans = new ArrayList<ProtocolBean>(); try { List<Protocol> protocols = helper.findProtocolsBy(protocolType, protocolName, protocolAbbreviation, fileTitle); Collections.sort(protocols, new Comparators.ProtocolNameVersionComparator()); for (Protocol protocol : protocols) { //don't need to load accessibility ProtocolBean protocolBean = new ProtocolBean(protocol); protocolBeans.add(protocolBean); } return protocolBeans; } catch (Exception e) { String err = "Problem finding protocols."; logger.error(err, e); throw new ProtocolException(err, e); } } public int getNumberOfPublicProtocols() throws ProtocolException { try { int count = helper.getNumberOfPublicProtocols(); return count; } catch (Exception e) { String err = "Error finding counts of public protocols."; logger.error(err, e); throw new ProtocolException(err, e); } } public void deleteProtocol(Protocol protocol) throws ProtocolException, NoAccessException { if (user == null) { throw new NoAccessException(); } try { CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider .getApplicationService(); // assume protocol is loaded with protocol file // find associated characterizations // List<Long> charIds = findCharacterizationIdsByProtocolId(protocol // .getId().toString()); // CharacterizationServiceHelper charServiceHelper = new // CharacterizationServiceHelper(); // for (Long id : charIds) { // Characterization achar = charServiceHelper // .findCharacterizationById(id.toString()); // achar.setProtocol(null); // appService.saveOrUpdate(achar); List<Characterization> chars = this .findCharacterizationsByProtocolId(protocol.getId() .toString()); for (Characterization achar : chars) { achar.setProtocol(null); appService.saveOrUpdate(achar); } appService.delete(protocol); } catch (Exception e) { String err = "Error in deleting the protocol."; logger.error(err, e); throw new ProtocolException(err, e); } } private List<Long> findCharacterizationIdsByProtocolId(String protocolId) throws Exception { CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider .getApplicationService(); DetachedCriteria crit = DetachedCriteria.forClass( Characterization.class).setProjection( Projections.distinct(Property.forName("id"))); crit.createAlias("protocol", "protocol"); crit.add(Property.forName("protocol.id").eq(new Long(protocolId))); List results = appService.query(crit); List<Long> ids = new ArrayList<Long>(); for (Object obj : results) { Long charId = (Long) obj; ids.add(charId); } return ids; } private List<Characterization> findCharacterizationsByProtocolId( String protocolId) throws Exception { CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider .getApplicationService(); DetachedCriteria crit = DetachedCriteria .forClass(Characterization.class); crit.createAlias("protocol", "protocol"); crit.add(Property.forName("protocol.id").eq(new Long(protocolId))); List results = appService.query(crit); List<Characterization> chars = new ArrayList<Characterization>(); for (Object obj : results) { Characterization achar = (Characterization) obj; chars.add(achar); } return chars; } public void assignAccessibility(AccessibilityBean access, Protocol protocol) throws ProtocolException, NoAccessException { if (!isUserOwner(protocol.getCreatedBy())) { throw new NoAccessException(); } try { super.saveAccessibility(access, protocol.getId().toString()); if (protocol.getFile() != null) { super.saveAccessibility(access, protocol.getFile().getId() .toString()); } } catch (Exception e) { String error = "Error in assigning access to protocol"; throw new ProtocolException(error, e); } } public void removeAccessibility(AccessibilityBean access, Protocol protocol) throws ProtocolException, NoAccessException { if (!isUserOwner(protocol.getCreatedBy())) { throw new NoAccessException(); } try { if (protocol != null) { super.deleteAccessibility(access, protocol.getId().toString()); if (protocol.getFile() != null) { super.deleteAccessibility(access, protocol.getFile() .getId().toString()); } } } catch (Exception e) { String error = "Error in assigning access to protocol"; throw new ProtocolException(error, e); } } public ProtocolServiceHelper getHelper() { return helper; } }
package edu.usc.irds.sparkler.plugin; import edu.usc.irds.sparkler.AbstractExtensionPoint; import edu.usc.irds.sparkler.Config; import edu.usc.irds.sparkler.SparklerConfiguration; import edu.usc.irds.sparkler.SparklerException; import edu.usc.irds.sparkler.UrlInjectorObj; import io.netty.handler.codec.json.JsonObjectDecoder; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.pf4j.Extension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Collection; import java.util.Iterator; @Extension public class UrlInjector extends AbstractExtensionPoint implements Config { private static final Logger LOG = LoggerFactory.getLogger(UrlInjector.class); private Map<String, Object> pluginConfig; @Override public Collection<UrlInjectorObj> processConfig(Collection<String> urls) { SparklerConfiguration config = jobContext.getConfiguration(); List<UrlInjectorObj> r = new ArrayList<>(); try { pluginConfig = config.getPluginConfiguration(pluginId); } catch (SparklerException e) { e.printStackTrace(); } if (pluginConfig != null) { // Get replacement values from config List<String> vals = (List<String>) pluginConfig.get("values"); LOG.debug("Found vals: {}", vals); // Get mode type from config String mode = (String) pluginConfig.get("mode"); if (mode.equals("replace")) { // Function 1: Replace placeholder in url and add new url to list r = replaceURLToken(urls, vals); } else if (mode.equals("selenium")) { // Function 2: Keep url but loop on selenium script r = appendSelenium(urls, vals); } else if (mode.equals("json")) { // Function 3: Keep url but create json to POST r = appendJSON(urls, vals); } else if (mode.equals("form")){ r = appendForm(urls, vals); } } return r; } private List<UrlInjectorObj> appendForm(Collection<String> urls, List<String> tokens) { List<UrlInjectorObj> fixedUrls = new ArrayList<>(); Map script = (Map) pluginConfig.get("form"); JSONObject root = new JSONObject(); JSONObject obj = new JSONObject(script); root.put("form", obj); for (Iterator<String> iterator = urls.iterator(); iterator.hasNext();) { String u = iterator.next(); String method = getHTTPMethod(u); u = trimHTTPMethod(u); if (tokens.size() > 0) { for (String temp : tokens) { String json = root.toString(); json = json.replace("${token}", temp); root.put("TAG", temp); UrlInjectorObj o = new UrlInjectorObj(u, json, method); fixedUrls.add(o); } } else { UrlInjectorObj o = new UrlInjectorObj(u, root.toString(), method); fixedUrls.add(o); } } return fixedUrls; } // Simple URL token replacement, takes a list of urls and a list of tokens and // applies // each token to each url. private List<UrlInjectorObj> replaceURLToken(Collection<String> urls, List<String> tokens) { List<UrlInjectorObj> fixedUrls = new ArrayList<>(); JSONObject root = new JSONObject(); for (Iterator<String> iterator = urls.iterator(); iterator.hasNext();) { String u = iterator.next(); for (String temp : tokens) { String rep = u.replace("${token}", temp); String method = getHTTPMethod(rep); rep = trimHTTPMethod(rep); root.put("TAG", temp); UrlInjectorObj o = new UrlInjectorObj(rep, root.toString(), method); fixedUrls.add(o); } } return fixedUrls; } private List<UrlInjectorObj> appendJSON(Collection<String> urls, List<String> tokens) { List<UrlInjectorObj> fixedUrls = new ArrayList<>(); String jsonStr = (String) pluginConfig.get("json"); for (Iterator<String> iterator = urls.iterator(); iterator.hasNext();) { String u = iterator.next(); String method = getHTTPMethod(u); u = trimHTTPMethod(u); if (tokens.size() > 0) { for (String temp : tokens) { JSONObject root = new JSONObject(); JSONParser parser = new JSONParser(); JSONObject json; String parsedJsonStr = jsonStr.replace("${token}", temp); try { json = (JSONObject) parser.parse(parsedJsonStr); root.put("JSON", json); root.put("TAG", temp); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } UrlInjectorObj o = new UrlInjectorObj(u, root.toString(), method); fixedUrls.add(o); } } else { UrlInjectorObj o = new UrlInjectorObj(u, jsonStr, method); fixedUrls.add(o); } } return fixedUrls; } private List<UrlInjectorObj> appendSelenium(Collection<String> urls, List<String> tokens) { List<UrlInjectorObj> fixedUrls = new ArrayList<>(); Map script = (Map) pluginConfig.get("selenium"); JSONObject root = new JSONObject(); JSONObject obj = new JSONObject(script); root.put("selenium", obj); for (Iterator<String> iterator = urls.iterator(); iterator.hasNext();) { String u = iterator.next(); String method = getHTTPMethod(u); u = trimHTTPMethod(u); if (tokens.size() > 0) { for (String temp : tokens) { root.put("TAG", temp); String json = root.toString(); json = json.replace("${token}", temp); UrlInjectorObj o = new UrlInjectorObj(u, json, method); fixedUrls.add(o); } } else { root.put("TAG", this.pluginConfig.getOrDefault("tag", "no tag defined")); UrlInjectorObj o = new UrlInjectorObj(u, root.toString(), method); fixedUrls.add(o); } } return fixedUrls; } private String getHTTPMethod(String url) { if (url.startsWith("GET|")) { return "GET"; } else if (url.startsWith("PUT|")) { return "PUT"; } else if (url.startsWith("POST|")) { return "POST"; } return "GET"; } private String trimHTTPMethod(String url) { if (url.startsWith("GET|")) { return url.substring(4); } else if (url.startsWith("PUT|")) { return url.substring(4); } else if (url.startsWith("POST|")) { return url.substring(5); } return url; } }
package test.http; import com.firefly.client.http2.SimpleHTTPClient; import com.firefly.codec.http2.model.HttpHeader; import com.firefly.codec.http2.stream.HTTPOutputStream; import com.firefly.server.http2.SimpleHTTPServer; import com.firefly.server.http2.SimpleHTTPServerConfiguration; import com.firefly.server.http2.SimpleResponse; import com.firefly.utils.concurrent.Promise; import com.firefly.utils.io.BufferUtils; import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.atomic.AtomicLong; /** * @author Pengtao Qiu */ public class ProxyDemo { public static void main(String[] args) { SimpleHTTPClient client = new SimpleHTTPClient(); SimpleHTTPServer server = new SimpleHTTPServer(); server.headerComplete(srcRequest -> { long start = System.currentTimeMillis(); System.out.println(srcRequest.getRequest().toString()); System.out.println(srcRequest.getRequest().getFields()); try { // copy origin request line and headers to destination request Promise.Completable<HTTPOutputStream> outputCompletable = new Promise.Completable<>(); SimpleHTTPClient.RequestBuilder dstReq = client.request(srcRequest.getRequest().getMethod(), srcRequest.getRequest().getURI().toURI().toURL()) .addAll(srcRequest.getRequest().getFields()) .output(outputCompletable); long contentLength = srcRequest.getRequest().getFields().getLongField(HttpHeader.CONTENT_LENGTH.asString()); if (contentLength > 0) { // transmit origin request body to destination server AtomicLong count = new AtomicLong(); srcRequest.content(srcBuffer -> outputCompletable.thenAccept(dstOutput -> { try { if (count.addAndGet(srcBuffer.remaining()) < contentLength) { dstOutput.write(srcBuffer); } else { dstOutput.write(srcBuffer); dstOutput.close(); } } catch (IOException e) { e.printStackTrace(); } })); } else { outputCompletable.thenAccept(dstOutput -> { try { dstOutput.close(); } catch (IOException e) { e.printStackTrace(); } }); } srcRequest.messageComplete(req -> { SimpleResponse srcResponse = req.getResponse(); srcResponse.setAsynchronous(true); dstReq.headerComplete(dstResponse -> { // copy destination server response line and headers to origin response System.out.println(dstResponse.toString()); System.out.println(dstResponse.getFields()); srcResponse.getResponse().setStatus(dstResponse.getStatus()); srcResponse.getResponse().setReason(dstResponse.getReason()); srcResponse.getResponse().setHttpVersion(dstResponse.getHttpVersion()); srcResponse.getResponse().getFields().addAll(dstResponse.getFields()); }).content(dstBuffer -> { // transmit destination server response body System.out.println("receive dst data -> " + dstBuffer.remaining()); try { srcResponse.getOutputStream().write(BufferUtils.toArray(dstBuffer)); } catch (IOException e) { e.printStackTrace(); } }).messageComplete(dstResponse -> { try { srcResponse.getOutputStream().close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("time: " + (System.currentTimeMillis() - start)); }).end(); }); System.out.println("block time: " + (System.currentTimeMillis() - start) + "|" + srcRequest.getRequest().getURIString()); } catch (Exception e) { e.printStackTrace(); } }).listen("localhost", 3344); } }
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */ package jp.oist.flint.sedml; import jp.oist.flint.util.IntegrationMethodFormat; import java.math.BigDecimal; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; public class SedmlWriter { private final boolean mFull; public SedmlWriter(boolean full) { mFull = full; } private String escape(String s) { return s.replaceAll(">","&gt;").replaceAll("<", "&lt;").replaceAll("&", "&amp;").replaceAll("'", "&apos;"); } public void writeSimulationConfiguration(final ISimulationConfigurationList configs, final OutputStream os) throws IOException, SedmlException { try (OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8); BufferedWriter writer = new BufferedWriter(osw)) { writer.append("<?xml version='1.0' encoding='UTF-8'?>\n"); writer.append("<sedML xmlns='http: if (mFull) { // FIXME } int modelCount = configs.getConfigurationCount(); writer.append(" <listOfSimulations>\n"); for (int i=0; i<modelCount; i++) { ISimulationConfiguration config = configs.getConfiguration(i); BigDecimal nop = new BigDecimal(config.getLength()).divide(new BigDecimal(config.getStep())); int numberOfPoints = nop.intValueExact(); writer.append(String.format(" <uniformTimeCourse id='sim%s' name='Simulation %s' initialTime='0' outputStartTime='%s' outputEndTime='%s' numberOfPoints='%s' flint:granularity='%s'>\n", i, i, config.getOutputStartTime(), config.getLength(), numberOfPoints, config.getGranularity())); writer.append(" <algorithm kisaoID='KISAO:"); String kisaoId = IntegrationMethodFormat.kisaoId(config.getIntegrationMethod()); if (kisaoId == null) throw new SedmlException("invalid integration method: " + config.getIntegrationMethod()); writer.append(kisaoId); writer.append("'/>\n"); writer.append(" </uniformTimeCourse>\n"); } writer.append(" </listOfSimulations>\n"); writer.append(" <listOfModels>\n"); for (int i=0; i<modelCount; i++) { ISimulationConfiguration config = configs.getConfiguration(i); writer.append(String.format(" <model id='model%s' name='Model %s' language='urn:sedml:language:phml' source='", i, i)); if (mFull) { writer.append(escape(config.getModelCanonicalPath())); } else { writer.append("%%MODEL_PATH%%"); } writer.append("'/>\n"); } writer.append(" </listOfModels>\n"); writer.append(" <listOfTasks>\n"); for (int i=0; i<modelCount; i++) { writer.append(String.format(" <task id='task%s' name='Task %s' modelReference='model%s' simulationReference='sim%s'/>\n", i, i, i, i)); } writer.append(" </listOfTasks>\n"); writer.append(" <listOfDataGenerators>\n"); int index = 0; for (int i=0; i<modelCount; i++) { ISimulationConfiguration config = configs.getConfiguration(i); for (String key : config.getKeys()) { String kc = key.replace(' ', ':'); writer.append(" <dataGenerator id='dg" + index + "' name='" + kc + "'>\n"); writer.append(" <listOfVariables>\n"); writer.append(" <variable id='v" + index + "' taskReference='task"+i+"' target='" + kc + "'/>\n"); writer.append(" </listOfVariables>\n"); writer.append(" <math:math>\n"); writer.append(" <math:ci>v" + index + "</math:ci>\n"); writer.append(" </math:math>\n"); writer.append(" </dataGenerator>\n"); index += 1; } } writer.append(" </listOfDataGenerators>\n"); writer.append("</sedML>\n"); } } public void writeSimulationConfiguration(final ISimulationConfiguration config, final OutputStream os) throws ArithmeticException, IOException, SedmlException { BigDecimal nop = new BigDecimal(config.getLength()).divide(new BigDecimal(config.getStep())); int numberOfPoints = nop.intValueExact(); try (OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8); BufferedWriter writer = new BufferedWriter(osw)) { writer.append("<?xml version='1.0' encoding='UTF-8'?>\n"); writer.append("<sedML xmlns='http: if (mFull) { writer.append(" <annotation>\n"); writer.append(" <flint:filter syntax='" + config.getFilterSyntax() + "' pattern='" + escape(config.getFilterPattern()) + "' column='" + config.getFilterColumn() + "' />\n"); writer.append(" </annotation>\n"); } writer.append(" <listOfSimulations>\n"); writer.append(" <uniformTimeCourse id='sim0' name='Simulation 0' initialTime='0' outputStartTime='"); writer.append(config.getOutputStartTime()); writer.append("' outputEndTime='" + config.getLength() + "' numberOfPoints='" + numberOfPoints + "' flint:granularity='" + config.getGranularity() + "'>\n"); writer.append(" <algorithm kisaoID='KISAO:"); String kisaoId = IntegrationMethodFormat.kisaoId(config.getIntegrationMethod()); if (kisaoId == null) throw new SedmlException("invalid integration method: " + config.getIntegrationMethod()); writer.append(kisaoId); writer.append("'/>\n"); writer.append(" </uniformTimeCourse>\n"); writer.append(" </listOfSimulations>\n"); writer.append(" <listOfModels>\n"); writer.append(" <model id='model0' name='Model 0' language='urn:sedml:language:phml' source='"); if (mFull) { writer.append(escape(config.getModelCanonicalPath())); } else { writer.append("%%MODEL_PATH%%"); } writer.append("'/>\n"); writer.append(" </listOfModels>\n"); writer.append(" <listOfTasks>\n"); writer.append(" <task id='task0' name='Task 0' modelReference='model0' simulationReference='sim0'/>\n"); writer.append(" </listOfTasks>\n"); writer.append(" <listOfDataGenerators>\n"); int i = 0; for (String key : config.getKeys()) { String kc = key.replace(' ', ':'); writer.append(" <dataGenerator id='dg" + i + "' name='" + kc + "'>\n"); writer.append(" <listOfVariables>\n"); writer.append(" <variable id='v" + i + "' taskReference='task0' target='" + kc + "'/>\n"); writer.append(" </listOfVariables>\n"); writer.append(" <math:math>\n"); writer.append(" <math:ci>v" + i + "</math:ci>\n"); writer.append(" </math:math>\n"); writer.append(" </dataGenerator>\n"); i += 1; } writer.append(" </listOfDataGenerators>\n"); writer.append("</sedML>\n"); } } }
package org.apache.james.remotemanager; import java.io.*; import java.net.*; import java.util.*; import javax.mail.internet.ParseException; import org.apache.avalon.framework.component.Component; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.component.ComponentManager; import org.apache.avalon.framework.component.Composable; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.logger.AbstractLoggable; import org.apache.avalon.cornerstone.services.connection.ConnectionHandler; import org.apache.avalon.cornerstone.services.scheduler.PeriodicTimeTrigger; import org.apache.avalon.cornerstone.services.scheduler.Target; import org.apache.avalon.cornerstone.services.scheduler.TimeScheduler; import org.apache.james.Constants; import org.apache.james.BaseConnectionHandler; import org.apache.james.services.MailServer; import org.apache.james.services.User; import org.apache.james.services.JamesUser; import org.apache.james.services.UsersRepository; import org.apache.james.services.UsersStore; import org.apache.mailet.MailAddress; import org.apache.james.userrepository.DefaultUser; public class RemoteManagerHandler extends BaseConnectionHandler implements ConnectionHandler, Composable, Configurable, Target { private UsersStore usersStore; private UsersRepository users; private boolean inLocalUsers = true; private TimeScheduler scheduler; private MailServer mailServer; private BufferedReader in; private PrintWriter out; private HashMap admaccount = new HashMap(); private Socket socket; public void configure( final Configuration configuration ) throws ConfigurationException { timeout = configuration.getChild( "connectiontimeout" ).getValueAsInteger( 120000 ); final Configuration admin = configuration.getChild( "administrator_accounts" ); final Configuration[] accounts = admin.getChildren( "account" ); for ( int i = 0; i < accounts.length; i++ ) { admaccount.put( accounts[ i ].getAttribute( "login" ), accounts[ i ].getAttribute( "password" ) ); } } public void compose( final ComponentManager componentManager ) throws ComponentException { scheduler = (TimeScheduler)componentManager. lookup( "org.apache.avalon.cornerstone.services.scheduler.TimeScheduler" ); mailServer = (MailServer)componentManager. lookup( "org.apache.james.services.MailServer" ); usersStore = (UsersStore)componentManager. lookup( "org.apache.james.services.UsersStore" ); users = usersStore.getRepository("LocalUsers");; } /** * Handle a connection. * This handler is responsible for processing connections as they occur. * * @param connection the connection * @exception IOException if an error reading from socket occurs * @exception ProtocolException if an error handling connection occurs */ public void handleConnection( final Socket connection ) throws IOException { /* if( admaccount.isEmpty() ) { getLogger().warn("No Administrative account defined"); getLogger().warn("RemoteManager failed to be handled"); return; } */ final PeriodicTimeTrigger trigger = new PeriodicTimeTrigger( timeout, -1 ); scheduler.addTrigger( this.toString(), trigger, this ); socket = connection; String remoteHost = socket.getInetAddress().getHostName(); String remoteIP = socket.getInetAddress().getHostAddress(); try { in = new BufferedReader(new InputStreamReader( socket.getInputStream() )); out = new PrintWriter( socket.getOutputStream(), true); getLogger().info( "Access from " + remoteHost + "(" + remoteIP + ")" ); out.println( "JAMES RemoteAdministration Tool " + Constants.SOFTWARE_VERSION ); out.println("Please enter your login and password"); String login = null; String password = null; do { scheduler.resetTrigger(this.toString()); if (login != null) { final String message = "Login failed for " + login; out.println( message ); getLogger().info( message ); } out.println("Login id:"); login = in.readLine(); out.println("Password:"); password = in.readLine(); } while (!password.equals(admaccount.get(login)) || password.length() == 0); scheduler.resetTrigger(this.toString()); out.println( "Welcome " + login + ". HELP for a list of commands" ); getLogger().info("Login for " + login + " succesful"); try { while (parseCommand(in.readLine())) { scheduler.resetTrigger(this.toString()); } } catch (Throwable thr) { System.out.println("Exception: " + thr.getMessage()); thr.printStackTrace(); } getLogger().info("Logout for " + login + "."); socket.close(); } catch ( final IOException e ) { out.println("Error. Closing connection"); out.flush(); getLogger().error( "Exception during connection from " + remoteHost + " (" + remoteIP + ")"); } scheduler.removeTrigger(this.toString()); } public void targetTriggered( final String triggerName ) { getLogger().error("Connection timeout on socket"); try { out.println("Connection timeout. Closing connection"); socket.close(); } catch ( final IOException ioe ) { } } private boolean parseCommand( String command ) { if (command == null) return false; StringTokenizer commandLine = new StringTokenizer(command.trim(), " "); int arguments = commandLine.countTokens(); if (arguments == 0) { return true; } else if(arguments > 0) { command = commandLine.nextToken(); } String argument = (String) null; if(arguments > 1) { argument = commandLine.nextToken(); } String argument1 = (String) null; if(arguments > 2) { argument1 = commandLine.nextToken(); } if (command.equalsIgnoreCase("ADDUSER")) { String username = argument; String passwd = argument1; try { if (username.equals("") || passwd.equals("")) { out.println("usage: adduser [username] [password]"); return true; } } catch (NullPointerException e) { out.println("usage: adduser [username] [password]"); return true; } boolean success = false; if (users.contains(username)) { out.println("user " + username + " already exist"); } else if ( inLocalUsers ) { success = mailServer.addUser(username, passwd); } else { DefaultUser user = new DefaultUser(username, "SHA"); user.setPassword(passwd); success = users.addUser(user); } if ( success ) { out.println("User " + username + " added"); getLogger().info("User " + username + " added"); } else { out.println("Error adding user " + username); getLogger().info("Error adding user " + username); } out.flush(); } else if (command.equalsIgnoreCase("SETPASSWORD")) { if (argument == null || argument1 == null) { out.println("usage: setpassword [username] [password]"); return true; } String username = argument; String passwd = argument1; if (username.equals("") || passwd.equals("")) { out.println("usage: adduser [username] [password]"); return true; } User user = users.getUserByName(username); if (user == null) { out.println("No such user"); return true; } boolean success; success = user.setPassword(passwd); if (success){ users.updateUser(user); out.println("Password for " + username + " reset"); getLogger().info("Password for " + username + " reset"); } else { out.println("Error resetting password"); getLogger().info("Error resetting password"); } out.flush(); return true; } else if (command.equalsIgnoreCase("DELUSER")) { String user = argument; if (user.equals("")) { out.println("usage: deluser [username]"); return true; } try { users.removeUser(user); } catch (Exception e) { out.println("Error deleting user " + user + " : " + e.getMessage()); return true; } out.println("User " + user + " deleted"); getLogger().info("User " + user + " deleted"); } else if (command.equalsIgnoreCase("LISTUSERS")) { out.println("Existing accounts " + users.countUsers()); for (Iterator it = users.list(); it.hasNext();) { out.println("user: " + (String) it.next()); } } else if (command.equalsIgnoreCase("COUNTUSERS")) { out.println("Existing accounts " + users.countUsers()); } else if (command.equalsIgnoreCase("VERIFY")) { String user = argument; if (user.equals("")) { out.println("usage: verify [username]"); return true; } if (users.contains(user)) { out.println("User " + user + " exist"); } else { out.println("User " + user + " does not exist"); } } else if (command.equalsIgnoreCase("HELP")) { out.println("Currently implemented commans:"); out.println("help display this help"); out.println("listusers display existing accounts"); out.println("countusers display the number of existing accounts"); out.println("adduser [username] [password] add a new user"); out.println("verify [username] verify if specified user exist"); out.println("deluser [username] delete existing user"); out.println("setpassword [username] [password] sets a user's password"); out.println("setalias [username] [alias] sets a user's alias"); out.println("unsetalias [username] removes a user's alias"); out.println("setforwarding [username] [emailaddress] forwards a user's email to another account"); out.println("user [repositoryname] change to another user repository"); out.println("shutdown kills the current JVM (convenient when James is run as a daemon)"); out.println("quit close connection"); out.flush(); } else if (command.equalsIgnoreCase("SETALIAS")) { if (argument == null || argument1 == null) { out.println("usage: setalias [username] [alias]"); return true; } String username = argument; String alias = argument1; if (username.equals("") || alias.equals("")) { out.println("usage: adduser [username] [alias]"); return true; } JamesUser user = (JamesUser) users.getUserByName(username); if (user == null) { out.println("No such user"); return true; } JamesUser aliasUser = (JamesUser) users.getUserByName(alias); if (aliasUser == null) { out.println("Alias unknown to server" + " - create that user first."); return true; } boolean success; success = user.setAlias(alias); if (success){ user.setAliasing(true); users.updateUser(user); out.println("Alias for " + username + " set to:" + alias); getLogger().info("Alias for " + username + " set to:" + alias); } else { out.println("Error setting alias"); getLogger().info("Error setting alias"); } out.flush(); return true; } else if (command.equalsIgnoreCase("SETFORWARDING")) { if (argument == null || argument1 == null) { out.println("usage: setforwarding [username] [emailaddress]"); return true; } String username = argument; String forward = argument1; if (username.equals("") || forward.equals("")) { out.println("usage: adduser [username] [emailaddress]"); return true; } // Verify user exists User baseuser = users.getUserByName(username); if (baseuser == null) { out.println("No such user"); return true; } else if (! (baseuser instanceof JamesUser ) ) { out.println("Can't set forwarding for this user type."); return true; } JamesUser user = (JamesUser)baseuser; // Veriy acceptable email address MailAddress forwardAddr; try { forwardAddr = new MailAddress(forward); } catch(ParseException pe) { out.println("Parse exception with that email address: " + pe.getMessage()); out.println("Forwarding address not added for " + username); return true; } boolean success; success = user.setForwardingDestination(forwardAddr); if (success){ user.setForwarding(true); users.updateUser(user); out.println("Forwarding destination for " + username + " set to:" + forwardAddr.toString()); getLogger().info("Forwarding destination for " + username + " set to:" + forwardAddr.toString()); } else { out.println("Error setting forwarding"); getLogger().info("Error setting forwarding"); } out.flush(); return true; } else if (command.equalsIgnoreCase("UNSETALIAS")) { if (argument == null) { out.println("usage: unsetalias [username]"); return true; } String username = argument; if (username.equals("")) { out.println("usage: adduser [username]"); return true; } JamesUser user = (JamesUser) users.getUserByName(username); if (user == null) { out.println("No such user"); return true; } if (user.getAliasing()){ user.setAliasing(false); users.updateUser(user); out.println("Alias for " + username + " unset"); getLogger().info("Alias for " + username + " unset"); } else { out.println("Aliasing not active for" + username); getLogger().info("Aliasing not active for" + username); } out.flush(); return true; } else if (command.equalsIgnoreCase("USE")) { if (argument == null || argument.equals("")) { out.println("usage: use [repositoryName]"); return true; } String repositoryName = argument; UsersRepository repos = usersStore.getRepository(repositoryName); if ( repos == null ) { out.println("no such repository"); return true; } else { users = repos; out.println("Changed to repository '" + repositoryName + "'."); if ( repositoryName.equalsIgnoreCase("localusers") ) { inLocalUsers = true; } else { inLocalUsers = false; } return true; } } else if (command.equalsIgnoreCase("QUIT")) { out.println("bye"); return false; } else if (command.equalsIgnoreCase("SHUTDOWN")) { out.println("shuting down, bye bye"); System.exit(0); return false; } else { out.println("unknown command " + command); } return true; } }
package org.jboss.forge.ui.base; import java.net.URL; import org.jboss.forge.ui.UICategory; import org.jboss.forge.ui.UICommand; import org.jboss.forge.ui.UICommandMetadata; public class UICommandMetadataBase implements UICommandMetadata { private static String[] VALID_DOC_EXTENSIONS = { ".txt.gzip", ".txt.gz", ".txt", ".asciidoc.gzip", ".asciidoc.gz", ".asciidoc" }; private final String name; private final String description; private final UICategory category; private final URL docLocation; public UICommandMetadataBase(String name, String description) { this(name, description, null, null); } public UICommandMetadataBase(String name, String description, UICategory category) { this(name, description, category, null); } public UICommandMetadataBase(String name, String description, URL docLocation) { this(name, description, null, docLocation); } public UICommandMetadataBase(String name, String description, UICategory category, URL docLocation) { super(); this.name = name; this.description = description; this.category = category; this.docLocation = docLocation; } @Override public String getName() { return name; } @Override public String getDescription() { return description; } @Override public UICategory getCategory() { return category; } @Override public URL getDocLocation() { return docLocation; } /** * Calculates the location of the documentation of a specific {@link UICommand} * * @param type an {@link UICommand} instance * @return the URL with the location for the {@link UICommand} documentation, or null if not found */ public static URL getDocLocationFor(Class<? extends UICommand> type) { URL url = null; for (String extension : VALID_DOC_EXTENSIONS) { String docFileName = type.getSimpleName() + extension; url = type.getResource(docFileName); if (url != null) { break; } } return url; } }
package io.appium.android.bootstrap.handler; import io.appium.android.bootstrap.AndroidCommand; import io.appium.android.bootstrap.AndroidCommandResult; import io.appium.android.bootstrap.AndroidElement; import io.appium.android.bootstrap.AndroidElementClassMap; import io.appium.android.bootstrap.AndroidElementsHash; import io.appium.android.bootstrap.CommandHandler; import io.appium.android.bootstrap.Dynamic; import io.appium.android.bootstrap.Logger; import io.appium.android.bootstrap.WDStatus; import io.appium.android.bootstrap.exceptions.AndroidCommandException; import io.appium.android.bootstrap.exceptions.ElementNotFoundException; import io.appium.android.bootstrap.exceptions.ElementNotInHashException; import io.appium.android.bootstrap.exceptions.InvalidStrategyException; import io.appium.android.bootstrap.exceptions.UnallowedTagNameException; import io.appium.android.bootstrap.selector.Strategy; import java.util.ArrayList; import java.util.Hashtable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.android.uiautomator.core.UiObjectNotFoundException; import com.android.uiautomator.core.UiSelector; public class Find extends CommandHandler { AndroidElementsHash elements = AndroidElementsHash.getInstance(); Dynamic dynamic = new Dynamic(); private Object[] cascadeChildSels(final ArrayList<UiSelector> tail, final ArrayList<String> tailOuts) { if (tail.size() == 1) { final Object[] retVal = { tail.get(0), tailOuts.get(0) }; return retVal; } else { final UiSelector head = tail.remove(0); final String headOut = tailOuts.remove(0); final Object[] res = cascadeChildSels(tail, tailOuts); final Object[] retVal = { head.childSelector((UiSelector) res[0]), headOut + ".childSelector(" + (String) res[1] + ")" }; return retVal; } } /* * @param command The {@link AndroidCommand} used for this handler. * * @return {@link AndroidCommandResult} * * @throws JSONException * * @see io.appium.android.bootstrap.CommandHandler#execute(io.appium.android. * bootstrap.AndroidCommand) */ @Override public AndroidCommandResult execute(final AndroidCommand command) throws JSONException { final Hashtable<String, Object> params = command.params(); // only makes sense on a device final Strategy strategy = Strategy.fromString((String) params .get("strategy")); final String contextId = (String) params.get("context"); if (strategy == Strategy.DYNAMIC) { Logger.debug("Finding dynamic."); final JSONArray selectors = (JSONArray) params.get("selector"); // Return the first element of the first selector that matches. JSONObject result = new JSONObject(); Logger.debug(selectors.toString()); try { for (int selIndex = 0; selIndex < selectors.length(); selIndex++) { final UiSelector sel = dynamic.get((JSONArray) selectors .get(selIndex)); Logger.debug(sel.toString()); try { // fetch will throw on not found. result = fetchElement(sel, contextId); return getSuccessResult(result); } catch (final ElementNotFoundException enf) { Logger.debug("Not found."); } } return getSuccessResult(new AndroidCommandResult( WDStatus.NO_SUCH_ELEMENT, "No element found.")); } catch (final Exception e) { return getErrorResult(e.getMessage()); } } final String text = (String) params.get("selector"); Logger.debug("Finding " + text + " using " + strategy.toString() + " with the contextId: " + contextId); final Boolean multiple = (Boolean) params.get("multiple"); final boolean isXpath = strategy.equalsIgnoreCase("xpath"); if (isXpath) { final JSONArray xpathPath = (JSONArray) params.get("path"); final String xpathAttr = (String) params.get("attr"); final String xpathConstraint = (String) params.get("constraint"); final Boolean xpathSubstr = (Boolean) params.get("substr"); try { if (multiple) { final UiSelector sel = getSelectorForXpath(xpathPath, xpathAttr, xpathConstraint, xpathSubstr); return getSuccessResult(fetchElements(sel, contextId)); } else { final UiSelector sel = getSelectorForXpath(xpathPath, xpathAttr, xpathConstraint, xpathSubstr); return getSuccessResult(fetchElement(sel, contextId)); } } catch (final AndroidCommandException e) { return getErrorResult(e.getMessage()); } catch (final ElementNotFoundException e) { return getErrorResult(e.getMessage()); } catch (final UnallowedTagNameException e) { return getErrorResult(e.getMessage()); } catch (final ElementNotInHashException e) { return getErrorResult(e.getMessage()); } catch (final UiObjectNotFoundException e) { return getErrorResult(e.getMessage()); } } else { try { final UiSelector sel = getSelector(strategy, text, multiple); if (multiple) { return getSuccessResult(fetchElements(sel, contextId)); } else { return getSuccessResult(fetchElement(sel, contextId)); } } catch (final InvalidStrategyException e) { return getErrorResult(e.getMessage()); } catch (final ElementNotFoundException e) { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); } catch (final UnallowedTagNameException e) { return getErrorResult(e.getMessage()); } catch (final AndroidCommandException e) { return getErrorResult(e.getMessage()); } catch (final ElementNotInHashException e) { return getErrorResult(e.getMessage()); } catch (final UiObjectNotFoundException e) { return getErrorResult(e.getMessage()); } } } /** * Get the element from the {@link AndroidElementsHash} and return the element * id using JSON. * * @param sel * A UiSelector that targets the element to fetch. * @param contextId * The Id of the element used for the context. * * @return JSONObject * @throws JSONException * @throws ElementNotFoundException * @throws ElementNotInHashException */ private JSONObject fetchElement(final UiSelector sel, final String contextId) throws JSONException, ElementNotFoundException, ElementNotInHashException { final JSONObject res = new JSONObject(); final AndroidElement el = elements.getElement(sel, contextId); return res.put("ELEMENT", el.getId()); } /** * Get an array of elements from the {@link AndroidElementsHash} and return * the element's ids using JSON. * * @param sel * A UiSelector that targets the element to fetch. * @param contextId * The Id of the element used for the context. * * @return JSONObject * @throws JSONException * @throws UiObjectNotFoundException * @throws ElementNotInHashException */ private JSONArray fetchElements(final UiSelector sel, final String contextId) throws JSONException, ElementNotInHashException, UiObjectNotFoundException { final JSONArray resArray = new JSONArray(); final ArrayList<AndroidElement> els = elements.getElements(sel, contextId); for (final AndroidElement el : els) { resArray.put(new JSONObject().put("ELEMENT", el.getId())); } return resArray; } /** * Create and return a UiSelector based on the strategy, text, and how many * you want returned. * * @param strategy * The {@link Strategy} used to search for the element. * @param text * Any text used in the search (i.e. match, regex, etc.) * @param many * Boolean that is either only one element (false), or many (true) * @return UiSelector * @throws InvalidStrategyException * @throws AndroidCommandException */ private UiSelector getSelector(final Strategy strategy, final String text, final Boolean many) throws InvalidStrategyException, AndroidCommandException, UnallowedTagNameException { UiSelector sel = new UiSelector(); switch (strategy) { case CLASS_NAME: case TAG_NAME: String androidClass = AndroidElementClassMap.match(text); if (androidClass.contentEquals("android.widget.Button")) { androidClass += "|android.widget.ImageButton"; androidClass = androidClass.replaceAll("([^\\p{Alnum}|])", "\\\\$1"); sel = sel.classNameMatches("^" + androidClass + "$"); } else { sel = sel.className(androidClass); } break; case NAME: sel = sel.description(text); break; case XPATH: break; case LINK_TEXT: case PARTIAL_LINK_TEXT: case ID: case CSS_SELECTOR: default: throw new InvalidStrategyException("Strategy " + strategy.getStrategyName() + " is not valid."); } if (!many) { sel = sel.instance(0); } return sel; } /** * Create and return a UiSelector based on Xpath attributes. * * @param path * The Xpath path. * @param attr * The attribute. * @param constraint * Any constraint. * @param substr * Any substr. * * @return UiSelector * @throws AndroidCommandException */ private UiSelector getSelectorForXpath(final JSONArray path, final String attr, String constraint, final boolean substr) throws AndroidCommandException, UnallowedTagNameException { UiSelector s = new UiSelector(); final ArrayList<UiSelector> subSels = new ArrayList<UiSelector>(); final ArrayList<String> subSelOuts = new ArrayList<String>(); JSONObject pathObj; String nodeType; Object nodeIndex; final String substrStr = substr ? "true" : "false"; Logger.info("Building xpath selector from attr " + attr + " and constraint " + constraint + " and substr " + substrStr); String selOut = "s";
package io.appium.android.bootstrap.handler; import io.appium.android.bootstrap.AndroidCommand; import io.appium.android.bootstrap.AndroidCommandResult; import io.appium.android.bootstrap.AndroidElement; import io.appium.android.bootstrap.AndroidElementClassMap; import io.appium.android.bootstrap.AndroidElementsHash; import io.appium.android.bootstrap.CommandHandler; import io.appium.android.bootstrap.Dynamic; import io.appium.android.bootstrap.Logger; import io.appium.android.bootstrap.WDStatus; import io.appium.android.bootstrap.exceptions.AndroidCommandException; import io.appium.android.bootstrap.exceptions.ElementNotFoundException; import io.appium.android.bootstrap.exceptions.ElementNotInHashException; import io.appium.android.bootstrap.exceptions.InvalidStrategyException; import io.appium.android.bootstrap.exceptions.UnallowedTagNameException; import io.appium.android.bootstrap.selector.Strategy; import java.util.ArrayList; import java.util.Hashtable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.android.uiautomator.core.UiObjectNotFoundException; import com.android.uiautomator.core.UiSelector; public class Find extends CommandHandler { AndroidElementsHash elements = AndroidElementsHash.getInstance(); Dynamic dynamic = new Dynamic(); /* * @param command The {@link AndroidCommand} used for this handler. * * @return {@link AndroidCommandResult} * * @throws JSONException * * @see io.appium.android.bootstrap.CommandHandler#execute(io.appium.android. * bootstrap.AndroidCommand) */ @Override public AndroidCommandResult execute(final AndroidCommand command) throws JSONException { final Hashtable<String, Object> params = command.params(); // only makes sense on a device final Strategy strategy = Strategy.fromString((String) params .get("strategy")); final String contextId = (String) params.get("context"); if (strategy == Strategy.DYNAMIC) { Logger.debug("Finding dynamic."); final JSONArray selectors = (JSONArray) params.get("selector"); // Return the first element of the first selector that matches. JSONObject result = new JSONObject(); Logger.debug(selectors.toString()); try { for (int selIndex = 0; selIndex < selectors.length(); selIndex++) { final UiSelector sel = dynamic.get((JSONArray) selectors .get(selIndex)); Logger.debug(sel.toString()); try { // fetch will throw on not found. result = fetchElement(sel, contextId); return getSuccessResult(result); } catch (final ElementNotFoundException enf) { Logger.debug("Not found."); } } return getSuccessResult(new AndroidCommandResult( WDStatus.NO_SUCH_ELEMENT, "No element found.")); } catch (final Exception e) { return getErrorResult(e.getMessage()); } } final String text = (String) params.get("selector"); Logger.debug("Finding " + text + " using " + strategy.toString() + " with the contextId: " + contextId); final Boolean multiple = (Boolean) params.get("multiple"); final boolean isXpath = strategy.equalsIgnoreCase("xpath"); if (isXpath) { final JSONArray xpathPath = (JSONArray) params.get("path"); final String xpathAttr = (String) params.get("attr"); final String xpathConstraint = (String) params.get("constraint"); final Boolean xpathSubstr = (Boolean) params.get("substr"); try { if (multiple) { final UiSelector sel = getSelectorForXpath(xpathPath, xpathAttr, xpathConstraint, xpathSubstr); return getSuccessResult(fetchElements(sel, contextId)); } else { final UiSelector sel = getSelectorForXpath(xpathPath, xpathAttr, xpathConstraint, xpathSubstr); return getSuccessResult(fetchElement(sel, contextId)); } } catch (final AndroidCommandException e) { return getErrorResult(e.getMessage()); } catch (final ElementNotFoundException e) { return getErrorResult(e.getMessage()); } catch (final UnallowedTagNameException e) { return getErrorResult(e.getMessage()); } catch (final ElementNotInHashException e) { return getErrorResult(e.getMessage()); } catch (final UiObjectNotFoundException e) { return getErrorResult(e.getMessage()); } } else { try { final UiSelector sel = getSelector(strategy, text, multiple); if (multiple) { return getSuccessResult(fetchElements(sel, contextId)); } else { return getSuccessResult(fetchElement(sel, contextId)); } } catch (final InvalidStrategyException e) { return getErrorResult(e.getMessage()); } catch (final ElementNotFoundException e) { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); } catch (final UnallowedTagNameException e) { return getErrorResult(e.getMessage()); } catch (final AndroidCommandException e) { return getErrorResult(e.getMessage()); } catch (final ElementNotInHashException e) { return getErrorResult(e.getMessage()); } catch (final UiObjectNotFoundException e) { return getErrorResult(e.getMessage()); } } } /** * Get the element from the {@link AndroidElementsHash} and return the element * id using JSON. * * @param sel * A UiSelector that targets the element to fetch. * @param contextId * The Id of the element used for the context. * * @return JSONObject * @throws JSONException * @throws ElementNotFoundException * @throws ElementNotInHashException */ private JSONObject fetchElement(final UiSelector sel, final String contextId) throws JSONException, ElementNotFoundException, ElementNotInHashException { final JSONObject res = new JSONObject(); final AndroidElement el = elements.getElement(sel, contextId); return res.put("ELEMENT", el.getId()); } /** * Get an array of elements from the {@link AndroidElementsHash} and return * the element's ids using JSON. * * @param sel * A UiSelector that targets the element to fetch. * @param contextId * The Id of the element used for the context. * * @return JSONObject * @throws JSONException * @throws UiObjectNotFoundException * @throws ElementNotInHashException */ private JSONArray fetchElements(final UiSelector sel, final String contextId) throws JSONException, ElementNotInHashException, UiObjectNotFoundException { final JSONArray resArray = new JSONArray(); final ArrayList<AndroidElement> els = elements.getElements(sel, contextId); for (final AndroidElement el : els) { resArray.put(new JSONObject().put("ELEMENT", el.getId())); } return resArray; } /** * Create and return a UiSelector based on the strategy, text, and how many * you want returned. * * @param strategy * The {@link Strategy} used to search for the element. * @param text * Any text used in the search (i.e. match, regex, etc.) * @param many * Boolean that is either only one element (false), or many (true) * @return UiSelector * @throws InvalidStrategyException * @throws AndroidCommandException */ private UiSelector getSelector(final Strategy strategy, final String text, final Boolean many) throws InvalidStrategyException, AndroidCommandException, UnallowedTagNameException { UiSelector sel = new UiSelector(); switch (strategy) { case CLASS_NAME: case TAG_NAME: String androidClass = AndroidElementClassMap.match(text); if (androidClass.contentEquals("android.widget.Button")) { androidClass += "|android.widget.ImageButton"; androidClass = androidClass.replaceAll("([^\\p{Alnum}|])", "\\\\$1"); sel = sel.classNameMatches("^" + androidClass + "$"); } else { sel = sel.className(androidClass); } break; case NAME: sel = sel.description(text); break; case XPATH: break; case LINK_TEXT: case PARTIAL_LINK_TEXT: case ID: case CSS_SELECTOR: default: throw new InvalidStrategyException("Strategy " + strategy.getStrategyName() + " is not valid."); } if (!many) { sel = sel.instance(0); } return sel; } /** * Create and return a UiSelector based on Xpath attributes. * * @param path * The Xpath path. * @param attr * The attribute. * @param constraint * Any constraint. * @param substr * Any substr. * * @return UiSelector * @throws AndroidCommandException */ private UiSelector getSelectorForXpath(final JSONArray path, final String attr, String constraint, final boolean substr) throws AndroidCommandException, UnallowedTagNameException { UiSelector s = new UiSelector(); JSONObject pathObj; String nodeType; String searchType; final String substrStr = substr ? "true" : "false"; Logger.info("Building xpath selector from attr " + attr + " and constraint " + constraint + " and substr " + substrStr); String selOut = "s";
package dr.evomodel.continuous; import dr.evolution.tree.MultivariateTraitTree; import dr.evomodel.tree.TreeModel; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; /** * @author Marc A. Suchard * @author Guy Baele */ public interface MissingTraits { public void handleMissingTips(); public boolean isCompletelyMissing(int index); public boolean isPartiallyMissing(int index); void computeWeightedAverage(double[] meanCache, int meanOffset0, double precision0, int meanOffset1, double precision1, int meanThisOffset, int dim); abstract class Abstract implements MissingTraits { protected static final boolean DEBUG = false; Abstract(MultivariateTraitTree treeModel, List<Integer> missingIndices, int dim) { this.treeModel = treeModel; this.dim = dim; this.missingIndices = missingIndices; completelyMissing = new boolean[treeModel.getNodeCount()]; Arrays.fill(completelyMissing, 0, treeModel.getExternalNodeCount() - 1, false); Arrays.fill(completelyMissing, treeModel.getExternalNodeCount(), treeModel.getNodeCount(), true); // All internal and root nodes are missing } final protected MultivariateTraitTree treeModel; final protected int dim; final protected List<Integer> missingIndices; final protected boolean[] completelyMissing; } public class CompletelyMissing extends Abstract { CompletelyMissing(MultivariateTraitTree treeModel, List<Integer> missingIndices, int dim) { super(treeModel, missingIndices, dim); } public void handleMissingTips() { for (Integer i : missingIndices) { int whichTip = i / dim; Logger.getLogger("dr.evomodel").info( "\tMarking taxon " + treeModel.getTaxonId(whichTip) + " as completely missing"); completelyMissing[whichTip] = true; } } public boolean isCompletelyMissing(int index) { return completelyMissing[index]; } public boolean isPartiallyMissing(int index) { return false; } public void computeWeightedAverage(double[] meanCache, int meanOffset0, double precision0, int meanOffset1, double precision1, int meanThisOffset, int dim) { IntegratedMultivariateTraitLikelihood.computeWeightedAverage( meanCache, meanOffset0, precision0, meanCache, meanOffset1, precision1, meanCache, meanThisOffset, dim); } } public class PartiallyMissing extends Abstract { PartiallyMissing(TreeModel treeModel, List<Integer> missingIndices, int dim) { super(treeModel, missingIndices, dim); } public void handleMissingTips() { throw new RuntimeException("Not yet implemented"); } public boolean isCompletelyMissing(int index) { throw new RuntimeException("Not yet implemented"); } public boolean isPartiallyMissing(int index) { throw new RuntimeException("Not yet implemented"); } public void computeWeightedAverage(double[] meanCache, int meanOffset0, double precision0, int meanOffset1, double precision1, int meanThisOffset, int dim) { throw new RuntimeException("Not yet implemented"); } } }
package dr.inference.markovchain; import dr.inference.model.CompoundLikelihood; import dr.inference.model.Likelihood; import dr.inference.model.Model; import dr.inference.operators.*; import dr.inference.prior.Prior; import java.util.ArrayList; import java.util.logging.Logger; /** * A concrete markov chain. This is final as the only things that should need * overriding are in the delegates (prior, likelihood, schedule and acceptor). * The design of this class is to be fairly immutable as far as settings goes. * * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: MarkovChain.java,v 1.10 2006/06/21 13:34:42 rambaut Exp $ */ public final class MarkovChain { private final static boolean DEBUG = false; private final static boolean PROFILE = true; public static final double EVALUATION_TEST_THRESHOLD = 1e-6; private final OperatorSchedule schedule; private final Acceptor acceptor; private final Prior prior; private final Likelihood likelihood; private boolean pleaseStop = false; private boolean isStopped = false; private double bestScore, currentScore, initialScore; private long currentLength; private boolean useCoercion = true; private final long fullEvaluationCount; private final int minOperatorCountForFullEvaluation; private double evaluationTestThreshold = EVALUATION_TEST_THRESHOLD; public MarkovChain(Prior prior, Likelihood likelihood, OperatorSchedule schedule, Acceptor acceptor, long fullEvaluationCount, int minOperatorCountForFullEvaluation, double evaluationTestThreshold, boolean useCoercion) { currentLength = 0; this.prior = prior; this.likelihood = likelihood; this.schedule = schedule; this.acceptor = acceptor; this.useCoercion = useCoercion; this.fullEvaluationCount = fullEvaluationCount; this.minOperatorCountForFullEvaluation = minOperatorCountForFullEvaluation; this.evaluationTestThreshold = evaluationTestThreshold; currentScore = evaluate(likelihood, prior); } /** * Resets the markov chain */ public void reset() { currentLength = 0; // reset operator acceptance levels for (int i = 0; i < schedule.getOperatorCount(); i++) { schedule.getOperator(i).reset(); } } /** * Run the chain for a given number of states. * * @param length number of states to run the chain. * <p/> * param onTheFlyOperatorWeights */ public long runChain(long length, boolean disableCoerce /*,int onTheFlyOperatorWeights*/) { likelihood.makeDirty(); currentScore = evaluate(likelihood, prior); long currentState = currentLength; final Model currentModel = likelihood.getModel(); if (currentState == 0) { initialScore = currentScore; bestScore = currentScore; fireBestModel(currentState, currentModel); } if (currentScore == Double.NEGATIVE_INFINITY) { // identify which component of the score is zero... if (prior != null) { double logPrior = prior.getLogPrior(likelihood.getModel()); if (logPrior == Double.NEGATIVE_INFINITY) { throw new IllegalArgumentException( "The initial model is invalid because one of the priors has zero probability."); } } String message = "The initial likelihood is zero"; if (likelihood instanceof CompoundLikelihood) { message += ": " + ((CompoundLikelihood) likelihood).getDiagnosis(); } else { message += "."; } throw new IllegalArgumentException(message); } else if (currentScore == Double.POSITIVE_INFINITY || Double.isNaN(currentScore)) { String message = "A likelihood returned with a numerical error"; if (likelihood instanceof CompoundLikelihood) { message += ": " + ((CompoundLikelihood) likelihood).getDiagnosis(); } else { message += "."; } throw new IllegalArgumentException(message); } pleaseStop = false; isStopped = false; //int otfcounter = onTheFlyOperatorWeights > 0 ? onTheFlyOperatorWeights : 0; double[] logr = {0.0}; boolean usingFullEvaluation = true; // set ops count in mcmc element instead if (fullEvaluationCount == 0) // Temporary solution until full code review usingFullEvaluation = false; boolean fullEvaluationError = false; while (!pleaseStop && (currentState < (currentLength + length))) { String diagnosticStart = ""; // periodically log states fireCurrentModel(currentState, currentModel); if (pleaseStop) { isStopped = true; break; } // Get the operator final int op = schedule.getNextOperatorIndex(); final MCMCOperator mcmcOperator = schedule.getOperator(op); double oldScore = currentScore; if (usingFullEvaluation) { diagnosticStart = likelihood instanceof CompoundLikelihood ? ((CompoundLikelihood) likelihood).getDiagnosis() : ""; } // assert Profiler.startProfile("Store"); // The current model is stored here in case the proposal fails if (currentModel != null) { currentModel.storeModelState(); } // assert Profiler.stopProfile("Store"); boolean operatorSucceeded = true; double hastingsRatio = 1.0; boolean accept = false; logr[0] = -Double.MAX_VALUE; try { // The new model is proposed // assert Profiler.startProfile("Operate"); if (DEBUG) { System.out.println("\n&& Operator: " + mcmcOperator.getOperatorName()); } if (mcmcOperator instanceof GeneralOperator) { hastingsRatio = ((GeneralOperator) mcmcOperator).operate(prior, likelihood); } else { hastingsRatio = mcmcOperator.operate(); } // assert Profiler.stopProfile("Operate"); } catch (OperatorFailedException e) { operatorSucceeded = false; } double score = 0.0; double deviation = 0.0; // System.err.print("" + currentState + ": "); if (operatorSucceeded) { // The new model is proposed // assert Profiler.startProfile("Evaluate"); if (DEBUG) { System.out.println("** Evaluate"); } long elapsedTime = 0; if (PROFILE) { elapsedTime = System.currentTimeMillis(); } // The new model is evaluated score = evaluate(likelihood, prior); if (PROFILE) { mcmcOperator.addEvaluationTime(System.currentTimeMillis() - elapsedTime); } String diagnosticOperator = ""; if (usingFullEvaluation) { diagnosticOperator = likelihood instanceof CompoundLikelihood ? ((CompoundLikelihood) likelihood).getDiagnosis() : ""; } if (score == Double.POSITIVE_INFINITY || Double.isNaN(score)) { if (likelihood instanceof CompoundLikelihood) { Logger.getLogger("error").severe("State "+currentState+": A likelihood returned with a numerical error:\n" + ((CompoundLikelihood)likelihood).getDiagnosis()); } else { Logger.getLogger("error").severe("State "+currentState+": A likelihood returned with a numerical error."); } // If the user has chosen to ignore this error then we transform it // to a negative infinity so the state is rejected. score = Double.NEGATIVE_INFINITY; } if (usingFullEvaluation) { // This is a test that the state was correctly evaluated. The // likelihood of all components of the model are flagged as // needing recalculation, then the full likelihood is calculated // again and compared to the first result. This checks that the // BEAST is aware of all changes that the operator induced. likelihood.makeDirty(); final double testScore = evaluate(likelihood, prior); final String d2 = likelihood instanceof CompoundLikelihood ? ((CompoundLikelihood) likelihood).getDiagnosis() : ""; if (Math.abs(testScore - score) > evaluationTestThreshold) { Logger.getLogger("error").severe( "State "+currentState+": State was not correctly calculated after an operator move.\n" + "Likelihood evaluation: " + score + "\nFull Likelihood evaluation: " + testScore + "\n" + "Operator: " + mcmcOperator + " " + mcmcOperator.getOperatorName() + (diagnosticOperator.length() > 0 ? "\n\nDetails\nBefore: " + diagnosticOperator + "\nAfter: " + d2 : "") + "\n\n"); fullEvaluationError = true; } } if (score > bestScore) { bestScore = score; fireBestModel(currentState, currentModel); } accept = mcmcOperator instanceof GibbsOperator || acceptor.accept(oldScore, score, hastingsRatio, logr); deviation = score - oldScore; } // The new model is accepted or rejected if (accept) { if (DEBUG) { System.out.println("** Move accepted: new score = " + score + ", old score = " + oldScore); } mcmcOperator.accept(deviation); currentModel.acceptModelState(); currentScore = score; // if( otfcounter > 0 ) { // --otfcounter; // if( otfcounter == 0 ) { // adjustOpWeights(currentState); // otfcounter = onTheFlyOperatorWeights; } else { if (DEBUG) { System.out.println("** Move rejected: new score = " + score + ", old score = " + oldScore); } mcmcOperator.reject(); // assert Profiler.startProfile("Restore"); currentModel.restoreModelState(); if (usingFullEvaluation) { // This is a test that the state is correctly restored. The // restored state is fully evaluated and the likelihood compared with // that before the operation was made. likelihood.makeDirty(); final double testScore = evaluate(likelihood, prior); final String d2 = likelihood instanceof CompoundLikelihood ? ((CompoundLikelihood) likelihood).getDiagnosis() : ""; if (Math.abs(testScore - oldScore) > evaluationTestThreshold) { final Logger logger = Logger.getLogger("error"); logger.severe("State "+currentState+": State was not correctly restored after reject step.\n" + "Likelihood before: " + oldScore + " Likelihood after: " + testScore + "\n" + "Operator: " + mcmcOperator + " " + mcmcOperator.getOperatorName() + (diagnosticStart.length() > 0 ? "\n\nDetails\nBefore: " + diagnosticStart + "\nAfter: " + d2 : "") + "\n\n"); fullEvaluationError = true; } } } // assert Profiler.stopProfile("Restore"); if (!disableCoerce && mcmcOperator instanceof CoercableMCMCOperator) { coerceAcceptanceProbability((CoercableMCMCOperator) mcmcOperator, logr[0]); } if (usingFullEvaluation) { if (schedule.getMinimumAcceptAndRejectCount() >= minOperatorCountForFullEvaluation && currentState >= fullEvaluationCount) { // full evaluation is only switched off when each operator has done a // minimum number of operations (currently 1) and fullEvalationCount // operations in total. usingFullEvaluation = false; if (fullEvaluationError) { // If there has been an error then stop with an error throw new RuntimeException( "One or more evaluation errors occurred during the test phase of this\n" + "run. These errors imply critical errors which may produce incorrect\n" + "results."); } } } fireEndCurrentIteration(currentState); currentState += 1; } currentLength = currentState; return currentLength; } public void terminateChain() { fireFinished(currentLength); // Profiler.report(); } // private void adjustOpWeights(int currentState) { // final int count = schedule.getOperatorCount(); // double[] s = new double[count]; // final double factor = 100; // final double limitSpan = 1000; // System.err.println("start cycle " + currentState); // double sHas = 0.0/* , sNot = 0.0 */, nHas = 0.0; // for(int no = 0; no < count; ++no) { // final MCMCOperator op = schedule.getOperator(no); // final double v = op.getSpan(true); // if( v == 0 ) { // // sNot += op.getWeight(); // s[no] = 0; // } else { // sHas += op.getWeight(); // s[no] = Math.max(factor * Math.min(v, limitSpan), 1); // nHas += s[no]; // // for(int no = 0; no < count; ++no) { // // final MCMCOperator op = schedule.getOperator(no); // // final double v = op.getSpan(false); // // if( v == 0 ) { // // System.err.println(op.getOperatorName() + " blocks"); // // return; // // keep sum of changed parts unchanged // final double scaleHas = sHas / nHas; // for(int no = 0; no < count; ++no) { // final MCMCOperator op = schedule.getOperator(no); // if( s[no] > 0 ) { // final double val = s[no] * scaleHas; // op.setWeight(val); // System.err.println("set " + op.getOperatorName() + " " + val); // } else { // System.err.println("** " + op.getOperatorName() + " = " // + op.getWeight()); // schedule.operatorsHasBeenUpdated(); public Prior getPrior() { return prior; } public Likelihood getLikelihood() { return likelihood; } public Model getModel() { return likelihood.getModel(); } public OperatorSchedule getSchedule() { return schedule; } public Acceptor getAcceptor() { return acceptor; } public double getInitialScore() { return initialScore; } public double getBestScore() { return bestScore; } public long getCurrentLength() { return currentLength; } public void setCurrentLength(long currentLength) { this.currentLength = currentLength; } public double getCurrentScore() { return currentScore; } public void pleaseStop() { pleaseStop = true; } public boolean isStopped() { return isStopped; } protected double evaluate(Likelihood likelihood, Prior prior) { double logPosterior = 0.0; if (prior != null) { final double logPrior = prior.getLogPrior(likelihood.getModel()); if (logPrior == Double.NEGATIVE_INFINITY) { return Double.NEGATIVE_INFINITY; } logPosterior += logPrior; } final double logLikelihood = likelihood.getLogLikelihood(); if (Double.isNaN(logLikelihood)) { return Double.NEGATIVE_INFINITY; } // System.err.println("** " + logPosterior + " + " + logLikelihood + // " = " + (logPosterior + logLikelihood)); logPosterior += logLikelihood; return logPosterior; } /** * Updates the proposal parameter, based on the target acceptance * probability This method relies on the proposal parameter being a * decreasing function of acceptance probability. * * @param op The operator * @param logr */ private void coerceAcceptanceProbability(CoercableMCMCOperator op, double logr) { if (isCoercable(op)) { final double p = op.getCoercableParameter(); final double i = schedule.getOptimizationTransform(MCMCOperator.Utils.getOperationCount(op)); final double target = op.getTargetAcceptanceProbability(); final double newp = p + ((1.0 / (i + 1.0)) * (Math.exp(logr) - target)); if (newp > -Double.MAX_VALUE && newp < Double.MAX_VALUE) { op.setCoercableParameter(newp); } } } private boolean isCoercable(CoercableMCMCOperator op) { return op.getMode() == CoercionMode.COERCION_ON || (op.getMode() != CoercionMode.COERCION_OFF && useCoercion); } public void addMarkovChainListener(MarkovChainListener listener) { listeners.add(listener); } public void removeMarkovChainListener(MarkovChainListener listener) { listeners.remove(listener); } public void addMarkovChainDelegate(MarkovChainDelegate delegate) { delegates.add(delegate); } public void removeMarkovChainDelegate(MarkovChainDelegate delegate) { delegates.remove(delegate); } private void fireBestModel(long state, Model bestModel) { for (MarkovChainListener listener : listeners) { listener.bestState(state, bestModel); } } private void fireCurrentModel(long state, Model currentModel) { for (MarkovChainListener listener : listeners) { listener.currentState(state, currentModel); } for (MarkovChainDelegate delegate : delegates) { delegate.currentState(state); } } private void fireFinished(long chainLength) { for (MarkovChainListener listener : listeners) { listener.finished(chainLength); } for (MarkovChainDelegate delegate : delegates) { delegate.finished(chainLength); } } private void fireEndCurrentIteration(long state) { for (MarkovChainDelegate delegate : delegates) { delegate.currentStateEnd(state); } } private final ArrayList<MarkovChainListener> listeners = new ArrayList<MarkovChainListener>(); private final ArrayList<MarkovChainDelegate> delegates = new ArrayList<MarkovChainDelegate>(); }
package dr.inference.model; import java.util.ArrayList; import java.util.List; /** * A multidimensional parameter constructed from its component parameters. * * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: CompoundParameter.java,v 1.13 2005/06/14 10:40:34 rambaut Exp $ */ public class CompoundParameter extends Parameter.Abstract implements VariableListener { public CompoundParameter(String name, Parameter[] params) { this(name); for (Parameter parameter : params) { dimension += parameter.getDimension(); parameter.addParameterListener(this); } for (Parameter parameter : params) { for (int j = 0; j < parameter.getDimension(); j++) { parameters.add(parameter); pindex.add(j); } uniqueParameters.add(parameter); labelParameter(parameter); } } public CompoundParameter(String name) { this.name = name; dimension = 0; } private void labelParameter(Parameter parameter) { if (parameter.getParameterName() == null) { String parameterName = name + uniqueParameters.size(); parameter.setId(parameterName); } } public void addParameter(Parameter param) { uniqueParameters.add(param); for (int j = 0; j < param.getDimension(); j++) { parameters.add(param); pindex.add(j); } dimension += param.getDimension(); if (dimension != parameters.size()) { throw new RuntimeException( "dimension=" + dimension + " parameters.size()=" + parameters.size() ); } param.addParameterListener(this); labelParameter(param); } public void removeParameter(Parameter param) { int dim = 0; for (Parameter parameter : uniqueParameters) { if (parameter == param) { break; } dim += parameter.getDimension(); } for (int i = 0; i < param.getDimension(); i++) { parameters.remove(dim); pindex.remove(dim); } if (parameters.contains(param)) throw new RuntimeException(); uniqueParameters.remove(param); dimension -= param.getDimension(); if (dimension != parameters.size()) throw new RuntimeException(); param.removeParameterListener(this); } /** * @return name if the parameter has been given a specific name, else it returns getId() */ public final String getParameterName() { if (name != null) return name; return getId(); } public Parameter getParameter(int index) { return uniqueParameters.get(index); } public int getParameterCount() { return uniqueParameters.size(); } public String getDimensionName(int dim) { return parameters.get(dim).getDimensionName(pindex.get(dim)); } public int getDimension() { return dimension; } public void setDimension(int dim) { throw new RuntimeException(); } public void addBounds(Bounds<Double> boundary) { if (bounds == null) { bounds = new CompoundBounds(); // return; } //else { IntersectionBounds newBounds = new IntersectionBounds(getDimension()); newBounds.addBounds(bounds); ((IntersectionBounds) bounds).addBounds(boundary); } public Bounds<Double> getBounds() { if (bounds == null) { bounds = new CompoundBounds(); } return bounds; } public void addDimension(int index, double value) { Parameter p = parameters.get(index); int pi = pindex.get(index); parameters.add(index, p); pindex.add(index, pi); p.addDimension(pi, value); for (int i = pi; i < p.getDimension(); i++) { pindex.set(index, i); index += 1; } } public double removeDimension(int index) { Parameter p = parameters.get(index); int pi = pindex.get(index); parameters.remove(index); pindex.remove(index); double v = p.removeDimension(pi); for (int i = pi; i < p.getDimension(); i++) { pindex.set(index, i); index += 1; } return v; } public void fireParameterChangedEvent() { doNotPropogateChangeUp = true; for (Parameter p : parameters) { p.fireParameterChangedEvent(); } doNotPropogateChangeUp = false; fireParameterChangedEvent(-1, ChangeType.ALL_VALUES_CHANGED); } public double getParameterValue(int dim) { return parameters.get(dim).getParameterValue(pindex.get(dim)); } public double[] inspectParametersValues() { return getParameterValues(); } public void setParameterValue(int dim, double value) { parameters.get(dim).setParameterValue(pindex.get(dim), value); } // public void setParameterValue(int row, int column, double a) // getParameter(column).setParameterValue(row, a); public void setParameterValueQuietly(int dim, double value) { parameters.get(dim).setParameterValueQuietly(pindex.get(dim), value); } // public void setParameterValueQuietly(int row, int column, double a){ // getParameter(column).setParameterValueQuietly(row, a); public void setParameterValueNotifyChangedAll(int dim, double value) { parameters.get(dim).setParameterValueNotifyChangedAll(pindex.get(dim), value); } // public void setParameterValueNotifyChangedAll(int row, int column, double val){ // getParameter(column).setParameterValueNotifyChangedAll(row, val); protected void storeValues() { for (Parameter parameter : uniqueParameters) { parameter.storeParameterValues(); } } protected void restoreValues() { for (Parameter parameter : uniqueParameters) { parameter.restoreParameterValues(); } } protected void acceptValues() { for (Parameter parameter : uniqueParameters) { parameter.acceptParameterValues(); } } protected final void adoptValues(Parameter source) { // the parameters that make up a compound parameter will have // this function called on them individually so we don't need // to do anything here. } public String toString() { StringBuffer buffer = new StringBuffer(String.valueOf(getParameterValue(0))); final Bounds bounds = getBounds(); buffer.append("[").append(String.valueOf(bounds.getLowerLimit(0))); buffer.append(",").append(String.valueOf(bounds.getUpperLimit(0))).append("]"); for (int i = 1; i < getDimension(); i++) { buffer.append(", ").append(String.valueOf(getParameterValue(i))); buffer.append("[").append(String.valueOf(bounds.getLowerLimit(i))); buffer.append(",").append(String.valueOf(bounds.getUpperLimit(i))).append("]"); } return buffer.toString(); } // Parameter listener interface public void variableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { int dim = 0; for (Parameter parameter1 : uniqueParameters) { if (variable == parameter1) { if (!doNotPropogateChangeUp) { int subparameterIndex = (index == -1) ? -1 : dim + index; fireParameterChangedEvent(subparameterIndex, type); } break; } dim += parameter1.getDimension(); } } // Private and protected stuff private class CompoundBounds implements Bounds<Double> { public Double getUpperLimit(int dim) { return parameters.get(dim).getBounds().getUpperLimit(pindex.get(dim)); } public Double getLowerLimit(int dim) { return parameters.get(dim).getBounds().getLowerLimit(pindex.get(dim)); } public int getBoundsDimension() { return getDimension(); } } protected ArrayList<Parameter> getParameters(){ return parameters; } private final List<Parameter> uniqueParameters = new ArrayList<Parameter>(); private final ArrayList<Parameter> parameters = new ArrayList<Parameter>(); private final ArrayList<Integer> pindex = new ArrayList<Integer>(); private Bounds bounds = null; private int dimension; private String name; private boolean doNotPropogateChangeUp = false; public static void main(String[] args) { Parameter param1 = new Parameter.Default(2); Parameter param2 = new Parameter.Default(2); Parameter param3 = new Parameter.Default(2); System.out.println(param1.getDimension()); CompoundParameter parameter = new CompoundParameter("parameter", new Parameter[]{param1, param2}); parameter.addParameter(param3); parameter.removeParameter(param2); } }
package io.vertx.example.unit.test; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpServer; import io.vertx.example.unit.SomeVerticle; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(VertxUnitRunner.class) public class MyJUnitTest { Vertx vertx; HttpServer server; @Before public void before(TestContext context) { vertx = Vertx.vertx(); server = vertx.createHttpServer().requestHandler(req -> req.response().end("foo")). listen(8080, context.asyncAssertSuccess()); } @After public void after(TestContext context) { vertx.close(context.asyncAssertSuccess()); } @Test public void test1(TestContext context) { // Send a request and get a response HttpClient client = vertx.createHttpClient(); Async async = context.async(); client.getNow(8080, "localhost", "/", resp -> { resp.bodyHandler(body -> context.assertEquals("foo", body.toString())); client.close(); async.complete(); }); } @Test public void test2(TestContext context) { // Deploy and undeploy a verticle vertx.deployVerticle(SomeVerticle.class.getName(), context.asyncAssertSuccess(deploymentID -> { vertx.undeploy(deploymentID, context.asyncAssertSuccess()); })); } }
package org.unix4j.util; import static junit.framework.Assert.fail; import java.io.File; import java.util.List; /** * Helper class to assert actual files one by one, either by their * {@link #assertAbsolute(String) absolute} or {@link #assertRelative(File, String) * relative} path. Assertions do not need to be performed in the order that the * files appear in the actualFiles list. */ class FileAsserter { private final List<File> actualFiles; /** * Constructor with actual files to assert. * * @param actualFiles * the actual files to assert. */ public FileAsserter(List<File> actualFiles) { this.actualFiles = actualFiles; } /** * Assert the absolute path against files which have yet to be asserted. * * @param expectedFileOrDirName * the expected absolute path of the directory or file */ public void assertAbsolute(final String expectedFileOrDirName) { File fileFound = null; for(final File file: actualFiles){ if(expectedFileOrDirName.equals(file.getPath())){ fileFound = file; } } if(fileFound == null){ String message = "Could not find file matching path: " + expectedFileOrDirName + "Amongst remaining files which have yet to be asserted:\n"; for(final File file: actualFiles){ message += " [" + file.getPath() + "]\n"; } fail(message); } else { actualFiles.remove(fileFound); } } /** * Assert the absoulte path against files which have yet to be asserted. * * @param expectedParentDir * the parent directory of the expected file or directory * @param expectedChildName * the child name of the expected file or directory */ public void assertAbsolute(final File expectedParentDir, final String expectedChildName) { assertAbsolute(new File(expectedParentDir, expectedChildName).getPath()); } /** * Assert the relative path against files which have yet to be asserted. * * @param relativeRoot * the root directory for the relative path * @param expectedRelativePath * the expected path relative to the given * {@code relativeRoot} * @see FileUtil#getRelativePath(File, File) */ public void assertRelative(final File relativeRoot, String expectedRelativePath) { File fileFound = null; for(final File file: actualFiles){ if(expectedRelativePath.equals(FileUtil.getRelativePath(relativeRoot, file))){ fileFound = file; } } if(fileFound == null){ String message = "Could not find file matching relative path: " + expectedRelativePath + " with relative root: " + relativeRoot.getPath() + "Amongst remaining files which have yet to be asserted:\n"; for(final File file: actualFiles){ message += " [" + FileUtil.getRelativePath(relativeRoot, file) + "]\n"; } fail(message); } else { actualFiles.remove(fileFound); } } }
package edu.oakland.OUSoft.database; import edu.oakland.OUSoft.items.Instructor; import edu.oakland.OUSoft.items.Person; import edu.oakland.OUSoft.items.Student; import java.util.ArrayList; public class OUPeople { private ArrayList<Student> students; private ArrayList<Instructor> instructors; private ArrayList<Person> others; public OUPeople() { this.students = new ArrayList<>(); this.instructors = new ArrayList<>(); this.others = new ArrayList<>(); } /** * Retrieve a student using their ID * * @param ID The students ID * @return The student, or null if not found */ public Student retrieveStudentByID(String ID) { for (Student student : students) { if (student.getID().equals(ID)) { return student; } } return null; } /** * Retrieve an instructor using their ID * * @param ID The instructors ID * @return The instructor, or null if not found */ public Instructor retrieveInstructorByID(String ID) { for (Instructor instructor : instructors) { if (instructor.getID().equals(ID)) { return instructor; } } return null; } /** * Add a person to the database, automatically determining type * * @param person The Person to add */ public void add(Person person) { if (person instanceof Student) { this.students.add((Student) person); } else if (person instanceof Instructor) { this.instructors.add((Instructor) person); } else { this.others.add(person); } } /** * Remove a student by reference * * @param student The Student to remove */ public void removeStudent(Student student) { this.students.remove(student); } /** * Remove an instructor by reference * * @param instructor The Instructor to remove */ public void removeInstructor(Instructor instructor) { this.instructors.remove(instructor); } /** * Remove a student by ID * * @param ID The ID of the Student to remove */ public void removeStudentByID(String ID) { this.students.remove(retrieveStudentByID(ID)); } /** * Remove an instructor by ID * * @param ID The ID of the Instructor to remove */ public void removeInstructorByID(String ID) { this.instructors.remove(retrieveInstructorByID(ID)); } /** * Print every student to standard output */ public void printAllStudents(boolean doHeader) { if (doHeader) { System.out.println("Students in the database: " + this.students.size()); } for (Student student : this.students) { System.out.println(student); } } /** * Print every instructor to standard output */ public void printAllInstructors(boolean doHeader) { if (doHeader) { System.out.println("Instructors in the database: " + this.instructors.size()); } for (Instructor instructor : this.instructors) { System.out.println(instructor); } } /** * Print every uncategorized person to standard output */ public void printAllOthers(boolean doHeader) { if (doHeader) { System.out.println("There are " + this.others.size() + " others in the database"); } for (Person person : this.others) { System.out.println(person); } } /** * Print every person to standard output */ public void printAll(boolean doHeader) { if (doHeader) { int count = this.students.size() + this.instructors.size() + this.others.size(); System.out.println("People in the database: " + count); } this.printAllInstructors(false); this.printAllStudents(false); this.printAllOthers(false); } }
package com.booking.validator.utils; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Supplier; public class ConcurrentPipeline<T> implements Service { private final int concurrencyLimit; private final Supplier<? extends Supplier<CompletableFuture<T>>> supplier; private final BiConsumer<T, Throwable> consumer; private volatile boolean run = false; public ConcurrentPipeline(Supplier<? extends Supplier<CompletableFuture<T>>> supplier, BiConsumer<T, Throwable> consumer, int concurrencyLimit) { this.supplier = supplier; this.consumer = consumer; this.concurrencyLimit = concurrencyLimit; } @Override public void start(){ run = true; for (int i = 0; i < concurrencyLimit; i++) startTaskAsync(); } @Override public void stop(){ run = false; } private void startTaskAsync(){ if (run) CompletableFuture.supplyAsync(supplier) .thenCompose( Supplier::get ) .whenComplete( consumer ) .whenComplete( (x,t)-> { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } startTaskAsync(); }); // a consumer exception could be handled here } }
package edu.wustl.common.beans; public class NameValueBean implements Comparable { private Object name=new Object(); private Object value=new Object(); //To decide whether the NameValueBean has to be sorted by value. //By default it will sort by name. private boolean sortByValue = false; public NameValueBean() { } public NameValueBean(Object name, Object value) { this.name = name; this.value = value; } public NameValueBean(Object name, Object value,boolean sortByValue) { this.name = name; this.value = value; this.sortByValue = sortByValue; } /** * @return Returns the sortByValue. */ public boolean isSortByValue() { return sortByValue; } /** * @param sortByValue The sortByValue to set. */ public void setSortByValue(boolean sortByValue) { this.sortByValue = sortByValue; } /** * @return Returns the name. */ public String getName() { return name.toString() ; } /** * @param name The name to set. */ public void setName(Object name) { this.name = name; } /** * @return Returns the value. */ public String getValue() { return value.toString(); } /** * @param value The value to set. */ public void setValue(Object value) { this.value = value; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return new String("name:"+ name.toString() +" value:"+value.toString() ); } public int compareTo(Object obj) { // Logger.out.debug("In CompareTo" ); // Logger.out.debug("ObjClass : " + obj.getClass().getName()); // Logger.out.debug("NameClass : " +((NameValueBean)obj).getName().getClass().getName()); // Logger.out.debug("ValueClass : " +((NameValueBean)obj).getValue().getClass().getName()); if(obj instanceof NameValueBean) { NameValueBean nameValueBean = (NameValueBean)obj; if(nameValueBean.name instanceof String ) { //This fix was required for bug:2818 //Sort by value if the variable is set to true. if(sortByValue && nameValueBean.isSortByValue()) { return (new Long(Long.parseLong(value.toString()))).compareTo(new Long(Long.parseLong(nameValueBean.getValue()))); } else { return name.toString().toLowerCase().compareTo(nameValueBean.getName().toString().toLowerCase()); } } else { return compareObject(obj); } } return 0; } private int compareObject(Object tmpobj) { NameValueBean obj = (NameValueBean)tmpobj; //Logger.out.debug(name.getClass()+" : " + obj.name.getClass() ); if(name.getClass() == obj.name.getClass() ) { if(name.getClass().getName().equalsIgnoreCase("java.lang.Long" )) { Long numOne = (Long)name; Long numTwo = (Long)obj.name; return numOne.compareTo(numTwo ); } else if(name.getClass().getName().equalsIgnoreCase("java.lang.Double" )) { Double numOne = (Double)name; Double numTwo = (Double)(obj.name); return numOne.compareTo(numTwo ); } else if(name.getClass().getName().equalsIgnoreCase("java.lang.Float" )) { Float numOne = (Float)name; Float numTwo = (Float)(obj.name); return numOne.compareTo(numTwo ); } else if(name.getClass().getName().equalsIgnoreCase("java.lang.Integer" )) { Integer numOne = (Integer)name; Integer numTwo = (Integer)(obj.name); return numOne.compareTo(numTwo ); } } // Logger.out.debug("Number type didnot match"); return 0; } }
package me.sniggle.android.utils.fragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.lang.reflect.Constructor; import me.sniggle.android.utils.application.BaseApplication; import me.sniggle.android.utils.application.BaseContext; import me.sniggle.android.utils.presenter.BasePresenter; import me.sniggle.android.utils.presenter.FragmentPresenter; /** * A convenience fragment implementation, automatically inflating the associated layout, * creating the appropriate presenter, registering the fragment as subscriber to the event bus * and allowing to publish new events * * @author iulius * @since 1.0 */ public abstract class BaseFragment<Ctx extends BaseContext, Application extends BaseApplication<Ctx>, Presenter extends BasePresenter<Ctx> & FragmentPresenter> extends Fragment { private final Class<Presenter> presenterClass; private final int layoutId; private Presenter presenter; /** * * @param layoutId * the id of the required layout * @param presenterClass * the class of the presenter to be used */ protected BaseFragment(int layoutId, Class<Presenter> presenterClass) { this.layoutId = layoutId; this.presenterClass = presenterClass; } /** * * @return * the app's dependency context */ protected Ctx getAppContext() { return ((Application)getActivity().getApplication()).getAppContext(); } /** * publishes an event to the app's event bus * * @param event * event to be published */ protected void publishEvent(Object event) { getAppContext().getBus().post(event); } protected Presenter createPresenter() { Presenter presenter = null; try { Constructor<Presenter> constructor = presenterClass.getConstructor(getAppContext().getClass()); presenter = constructor.newInstance(getAppContext()); } catch (Exception e) { Log.e("fragment-presenter", e.getMessage()); } return presenter; } /** * called before view creating to allow early fragment configurations, e.g. registering * the fragment to the app's event bus */ protected void preCreateView() { getAppContext().getBus().register(this); } /** * creates the view like the Android method {#onCreateView} * * @param inflater * the inflater * @param container * the container * @param savedInstanceState * the saved instance state * @return the inflated view */ protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(layoutId, container, false); } /** * performs configurations using the newly created view, e.g. initializing the associated presenter * * @param view * the just created view * @param savedInstanceState * the saved instance state */ protected void postCreateView(View view, Bundle savedInstanceState) { if( presenter == null ) { throw new RuntimeException("Failed to create presenter for fragment"); } presenter.onViewCreated(view); } @Override public void onAttach(Context context) { super.onAttach(context); presenter = createPresenter(); presenter.onAttach(context); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); presenter.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { presenter.onCreateView(); preCreateView(); View result = createView(inflater, container, savedInstanceState); postCreateView(result, savedInstanceState); return result; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); presenter.onViewCreated(view); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); presenter.onActivityCreated(savedInstanceState); } @Override public void onStart() { super.onStart(); presenter.onStart(); } @Override public void onResume() { super.onResume(); presenter.onResume(); } @Override public void onPause() { presenter.onPause(); super.onPause(); } @Override public void onStop() { presenter.onStop(); super.onStop(); } @Override public void onDestroyView() { getAppContext().getBus().unregister(this); this.presenter.onDestroyView(); super.onDestroyView(); } @Override public void onDestroy() { presenter.onDestroy(); super.onDestroy(); } @Override public void onDetach() { presenter.onDetach(); presenter = null; super.onDetach(); } }
package io.vertx.ext.web.handler; import io.vertx.codegen.annotations.VertxGen; import io.vertx.ext.auth.htdigest.HtdigestAuth; import io.vertx.ext.web.handler.impl.DigestAuthHandlerImpl; /** * An auth handler that provides HTTP Basic Authentication support. * * @author <a href="mailto:[email protected]">Paulo Lopes</a> */ @VertxGen public interface DigestAuthHandler extends AuthHandler { /** * The default nonce expire timeout to use in milliseconds. */ long DEFAULT_NONCE_EXPIRE_TIMEOUT = 3600000; /** * Create a digest auth handler * * @param authProvider the auth provider to use * @return the auth handler */ static DigestAuthHandler create(HtdigestAuth authProvider) { return new DigestAuthHandlerImpl(authProvider, DEFAULT_NONCE_EXPIRE_TIMEOUT); } /** * Create a digest auth handler, specifying the expire timeout for nonces. * * @param authProvider the auth service to use * @param nonceExpireTimeout the nonce expire timeout in milliseconds. * @return the auth handler */ static DigestAuthHandler create(HtdigestAuth authProvider, long nonceExpireTimeout) { return new DigestAuthHandlerImpl(authProvider, nonceExpireTimeout); } }