List of usage examples for java.math RoundingMode CEILING
RoundingMode CEILING
To view the source code for java.math RoundingMode CEILING.
Click Source Link
From source file:android.melbournehistorymap.MapsActivity.java
private void updateMap() { //Now get the maps central location LatLng mapCenter = mMap.getCameraPosition().target; //clear markers mMap.clear();// w w w. j a va2 s . co m //if user tries to zoom to far out of the world, bring them back down to earth... if (mMap.getCameraPosition().zoom < ZOOM_RESTRICT_LEVEL) { CameraPosition cameraPosition = new CameraPosition.Builder().target(mapCenter) // Sets the center of the map to location user .zoom(ZOOM_RESTRICT_LEVEL) // Sets the zoom .bearing(0) // Sets the orientation of the camera to east .tilt(25) // Sets the tilt of the camera to 30 degrees .build(); // Creates a CameraPosition from the builder mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } //rebuild lat/lng variable to be used for Google Places API requests double lat = mapCenter.latitude; double lng = mapCenter.longitude; double zoom = mMap.getCameraPosition().zoom; LatLng leftBorder = mMap.getProjection().getVisibleRegion().farLeft; //Work out distance between current location and place location //Source Library: https://github.com/googlemaps/android-maps-utils double radius = SphericalUtil.computeDistanceBetween(mapCenter, leftBorder); //Now that we have the new long/latitude of the camera position include zoom level //Lets check the database to determine if the user has been here already //Set DB helper DBHelper myDBHelper = new DBHelper(MapsActivity.this, WikiAPI.DB_NAME, null, WikiAPI.VERSION); //Open DB as readable only. SQLiteDatabase db = myDBHelper.getWritableDatabase(); //Prepare DB Search variables DecimalFormat dfLat = new DecimalFormat("#.##"); DecimalFormat dfLng = new DecimalFormat("#.##"); DecimalFormat dfZoom = new DecimalFormat("#"); dfLat.setRoundingMode(RoundingMode.CEILING); dfLng.setRoundingMode(RoundingMode.CEILING); dfZoom.setRoundingMode(RoundingMode.CEILING); double dblLat = Double.parseDouble(dfLat.format(lat)); double dblLng = Double.parseDouble(dfLng.format(lng)); double dblZoom = Double.parseDouble(dfZoom.format(zoom)); //Limit by 1 rows Cursor cursor = db.query(DBHelper.LOC_TABLE, null, "LAT LIKE '" + dblLat + "%' AND LNG LIKE '" + dblLng + "%' AND ZOOM = '" + dblZoom + "'", null, null, null, null, "1"); int count = cursor.getCount(); if (count == 0) { //user has not been to this location/zoom level before //add the new location data, then trigger the google place webservice api ContentValues values = new ContentValues(); values.put("lat", String.valueOf(dblLat)); values.put("lng", String.valueOf(dblLng)); values.put("zoom", String.valueOf(dblZoom)); db.insert(DBHelper.LOC_TABLE, null, values); String url; url = updateURL(lat, lng, radius); List<List<String>> googlePlaces = null; //null on first reference, the list is updated within the method callstack db.close(); GoogleAPI.callMapMethod(mMap, url, MapsActivity.this, googlePlaces, spinner); } if (count == 1) { //user has been here before //get place data from DB and not from the API //if place data returned hasn't been updated in 30 days - update data using getPlaceByID method Cursor placeCursor = db.query(DBHelper.TABLE_NAME, null, "PLACE_TYPES LIKE '%point_of_interest%'", null, null, null, null, null); List<List<String>> googlePlaces = new ArrayList<List<String>>(); while (placeCursor.moveToNext()) { String place_ID = placeCursor.getString(placeCursor.getColumnIndex("PLACE_ID")); String placeName = placeCursor.getString(placeCursor.getColumnIndex("PLACE_NAME")); String placeLoc = placeCursor.getString(placeCursor.getColumnIndex("PLACE_LOCATION")); String placeLat = placeCursor.getString(placeCursor.getColumnIndex("LAT")); String placeLng = placeCursor.getString(placeCursor.getColumnIndex("LNG")); //if lat and long from database is in the search bounds, add to the list of data to be shown LatLngBounds SEARCH_BOUNDS = mMap.getProjection().getVisibleRegion().latLngBounds; LatLng search_loc = new LatLng(Double.parseDouble(placeLat), Double.parseDouble(placeLng)); if (SEARCH_BOUNDS.contains(search_loc)) { //now what data do we want? //Initiate a place data array List<String> placeData = new ArrayList<String>(); //add place data to its array placeData.add(placeName); //0 placeData.add(place_ID); //1 placeData.add(placeLoc); //2 placeData.add(String.valueOf(placeLat)); //3 placeData.add(String.valueOf(placeLng)); //4 placeData.add(""); //5 placeData.add(""); //6 //send the place specific data to the google places array list googlePlaces.add(placeData); } } db.close(); //TODO: Get this method off the main UI thread! GoogleAPI.filterPlaces(googlePlaces, mMap, this, spinner); } }
From source file:org.apache.calcite.runtime.SqlFunctions.java
public static BigDecimal ceil(BigDecimal b0) { return b0.setScale(0, RoundingMode.CEILING); }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#divide(java.lang.Object, java.lang.Number, java.lang.Number, java.math.RoundingMode, java.lang.Class)}. *///from w ww. j a v a 2s. c o m @SuppressWarnings("unchecked") @Test public void testDivideTNumberNumberRoundingModeClassOfT() { assertEquals("null", null, divide(null, null, null, null, null)); assertEquals("null", null, divide(10, 5, 0, null, null)); assertEquals("null", null, divide(10, 5, null, null, null)); assertEquals("null", null, divide(10, 3, 2, RoundingMode.DOWN, null)); assertEquals("null", (Object) 3.33f, divide(10, 3, 2, RoundingMode.DOWN, float.class)); try { for (Class<?> type : PRIMITIVES) { Object expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class) .invoke(null, "0"); assertEquals("fallback: " + type.getSimpleName(), expected, divide(null, null, null, null, (Class<? extends Number>) type)); } for (Class<?> type : NUMBERS) { Object expected = valueOf(3.33, (Class<? extends Number>) type); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.DOWN, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.HALF_EVEN, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.HALF_UP, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.FLOOR, (Class<? extends Number>) type)); expected = valueOf(3.34, (Class<? extends Number>) type); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.UP, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.CEILING, (Class<? extends Number>) type)); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } }
From source file:com.espertech.esper.client.TestConfigurationParser.java
protected static void assertFileConfig(Configuration config) throws Exception { // assert name for class assertEquals(2, config.getEventTypeAutoNamePackages().size()); assertEquals("com.mycompany.eventsone", config.getEventTypeAutoNamePackages().toArray()[0]); assertEquals("com.mycompany.eventstwo", config.getEventTypeAutoNamePackages().toArray()[1]); // assert name for class assertEquals(3, config.getEventTypeNames().size()); assertEquals("com.mycompany.myapp.MySampleEventOne", config.getEventTypeNames().get("MySampleEventOne")); assertEquals("com.mycompany.myapp.MySampleEventTwo", config.getEventTypeNames().get("MySampleEventTwo")); assertEquals("com.mycompany.package.MyLegacyTypeEvent", config.getEventTypeNames().get("MyLegacyTypeEvent")); // assert auto imports assertEquals(8, config.getImports().size()); assertEquals("java.lang.*", config.getImports().get(0)); assertEquals("java.math.*", config.getImports().get(1)); assertEquals("java.text.*", config.getImports().get(2)); assertEquals("java.util.*", config.getImports().get(3)); assertEquals("com.espertech.esper.client.annotation.*", config.getImports().get(4)); assertEquals("com.espertech.esper.dataflow.ops.*", config.getImports().get(5)); assertEquals("com.mycompany.myapp.*", config.getImports().get(6)); assertEquals("com.mycompany.myapp.ClassOne", config.getImports().get(7)); // assert XML DOM - no schema assertEquals(2, config.getEventTypesXMLDOM().size()); ConfigurationEventTypeXMLDOM noSchemaDesc = config.getEventTypesXMLDOM().get("MyNoSchemaXMLEventName"); assertEquals("MyNoSchemaEvent", noSchemaDesc.getRootElementName()); assertEquals("/myevent/element1", noSchemaDesc.getXPathProperties().get("element1").getXpath()); assertEquals(XPathConstants.NUMBER, noSchemaDesc.getXPathProperties().get("element1").getType()); assertEquals(null, noSchemaDesc.getXPathProperties().get("element1").getOptionalCastToType()); assertNull(noSchemaDesc.getXPathFunctionResolver()); assertNull(noSchemaDesc.getXPathVariableResolver()); assertFalse(noSchemaDesc.isXPathPropertyExpr()); // assert XML DOM - with schema ConfigurationEventTypeXMLDOM schemaDesc = config.getEventTypesXMLDOM().get("MySchemaXMLEventName"); assertEquals("MySchemaEvent", schemaDesc.getRootElementName()); assertEquals("MySchemaXMLEvent.xsd", schemaDesc.getSchemaResource()); assertEquals("actual-xsd-text-here", schemaDesc.getSchemaText()); assertEquals("samples:schemas:simpleSchema", schemaDesc.getRootElementNamespace()); assertEquals("default-name-space", schemaDesc.getDefaultNamespace()); assertEquals("/myevent/element2", schemaDesc.getXPathProperties().get("element2").getXpath()); assertEquals(XPathConstants.STRING, schemaDesc.getXPathProperties().get("element2").getType()); assertEquals(Long.class, schemaDesc.getXPathProperties().get("element2").getOptionalCastToType()); assertEquals("/bookstore/book", schemaDesc.getXPathProperties().get("element3").getXpath()); assertEquals(XPathConstants.NODESET, schemaDesc.getXPathProperties().get("element3").getType()); assertEquals(null, schemaDesc.getXPathProperties().get("element3").getOptionalCastToType()); assertEquals("MyOtherXMLNodeEvent", schemaDesc.getXPathProperties().get("element3").getOptionaleventTypeName()); assertEquals(1, schemaDesc.getNamespacePrefixes().size()); assertEquals("samples:schemas:simpleSchema", schemaDesc.getNamespacePrefixes().get("ss")); assertFalse(schemaDesc.isXPathResolvePropertiesAbsolute()); assertEquals("com.mycompany.OptionalFunctionResolver", schemaDesc.getXPathFunctionResolver()); assertEquals("com.mycompany.OptionalVariableResolver", schemaDesc.getXPathVariableResolver()); assertTrue(schemaDesc.isXPathPropertyExpr()); assertFalse(schemaDesc.isEventSenderValidatesRoot()); assertFalse(schemaDesc.isAutoFragment()); assertEquals("startts", schemaDesc.getStartTimestampPropertyName()); assertEquals("endts", schemaDesc.getEndTimestampPropertyName()); // assert mapped events assertEquals(1, config.getEventTypesMapEvents().size()); assertTrue(config.getEventTypesMapEvents().keySet().contains("MyMapEvent")); Map<String, String> expectedProps = new HashMap<String, String>(); expectedProps.put("myInt", "int"); expectedProps.put("myString", "string"); assertEquals(expectedProps, config.getEventTypesMapEvents().get("MyMapEvent")); assertEquals(1, config.getMapTypeConfigurations().size()); Set<String> superTypes = config.getMapTypeConfigurations().get("MyMapEvent").getSuperTypes(); EPAssertionUtil.assertEqualsExactOrder(new Object[] { "MyMapSuperType1", "MyMapSuperType2" }, superTypes.toArray());//from w ww . j av a 2s . c o m assertEquals("startts", config.getMapTypeConfigurations().get("MyMapEvent").getStartTimestampPropertyName()); assertEquals("endts", config.getMapTypeConfigurations().get("MyMapEvent").getEndTimestampPropertyName()); // assert objectarray events assertEquals(1, config.getEventTypesNestableObjectArrayEvents().size()); assertTrue(config.getEventTypesNestableObjectArrayEvents().containsKey("MyObjectArrayEvent")); Map<String, String> expectedPropsObjectArray = new HashMap<String, String>(); expectedPropsObjectArray.put("myInt", "int"); expectedPropsObjectArray.put("myString", "string"); assertEquals(expectedPropsObjectArray, config.getEventTypesNestableObjectArrayEvents().get("MyObjectArrayEvent")); assertEquals(1, config.getObjectArrayTypeConfigurations().size()); Set<String> superTypesOA = config.getObjectArrayTypeConfigurations().get("MyObjectArrayEvent") .getSuperTypes(); EPAssertionUtil.assertEqualsExactOrder( new Object[] { "MyObjectArraySuperType1", "MyObjectArraySuperType2" }, superTypesOA.toArray()); assertEquals("startts", config.getObjectArrayTypeConfigurations().get("MyObjectArrayEvent") .getStartTimestampPropertyName()); assertEquals("endts", config.getObjectArrayTypeConfigurations().get("MyObjectArrayEvent").getEndTimestampPropertyName()); // assert legacy type declaration assertEquals(1, config.getEventTypesLegacy().size()); ConfigurationEventTypeLegacy legacy = config.getEventTypesLegacy().get("MyLegacyTypeEvent"); assertEquals(ConfigurationEventTypeLegacy.CodeGeneration.ENABLED, legacy.getCodeGeneration()); assertEquals(ConfigurationEventTypeLegacy.AccessorStyle.PUBLIC, legacy.getAccessorStyle()); assertEquals(1, legacy.getFieldProperties().size()); assertEquals("myFieldName", legacy.getFieldProperties().get(0).getAccessorFieldName()); assertEquals("myfieldprop", legacy.getFieldProperties().get(0).getName()); assertEquals(1, legacy.getMethodProperties().size()); assertEquals("myAccessorMethod", legacy.getMethodProperties().get(0).getAccessorMethodName()); assertEquals("mymethodprop", legacy.getMethodProperties().get(0).getName()); assertEquals(Configuration.PropertyResolutionStyle.CASE_INSENSITIVE, legacy.getPropertyResolutionStyle()); assertEquals("com.mycompany.myapp.MySampleEventFactory.createMyLegacyTypeEvent", legacy.getFactoryMethod()); assertEquals("myCopyMethod", legacy.getCopyMethod()); assertEquals("startts", legacy.getStartTimestampPropertyName()); assertEquals("endts", legacy.getEndTimestampPropertyName()); // assert database reference - data source config assertEquals(3, config.getDatabaseReferences().size()); ConfigurationDBRef configDBRef = config.getDatabaseReferences().get("mydb1"); ConfigurationDBRef.DataSourceConnection dsDef = (ConfigurationDBRef.DataSourceConnection) configDBRef .getConnectionFactoryDesc(); assertEquals("java:comp/env/jdbc/mydb", dsDef.getContextLookupName()); assertEquals( "{java.naming.provider.url=iiop://localhost:1050, java.naming.factory.initial=com.myclass.CtxFactory}", dsDef.getEnvProperties().toString()); assertEquals(ConfigurationDBRef.ConnectionLifecycleEnum.POOLED, configDBRef.getConnectionLifecycleEnum()); assertNull(configDBRef.getConnectionSettings().getAutoCommit()); assertNull(configDBRef.getConnectionSettings().getCatalog()); assertNull(configDBRef.getConnectionSettings().getReadOnly()); assertNull(configDBRef.getConnectionSettings().getTransactionIsolation()); ConfigurationLRUCache lruCache = (ConfigurationLRUCache) configDBRef.getDataCacheDesc(); assertEquals(10, lruCache.getSize()); assertEquals(ConfigurationDBRef.ColumnChangeCaseEnum.LOWERCASE, configDBRef.getColumnChangeCase()); assertEquals(ConfigurationDBRef.MetadataOriginEnum.SAMPLE, configDBRef.getMetadataRetrievalEnum()); assertEquals(2, configDBRef.getSqlTypesMapping().size()); assertEquals("int", configDBRef.getSqlTypesMapping().get(2)); assertEquals("float", configDBRef.getSqlTypesMapping().get(6)); // assert database reference - driver manager config configDBRef = config.getDatabaseReferences().get("mydb2"); ConfigurationDBRef.DriverManagerConnection dmDef = (ConfigurationDBRef.DriverManagerConnection) configDBRef .getConnectionFactoryDesc(); assertEquals("my.sql.Driver", dmDef.getClassName()); assertEquals("jdbc:mysql://localhost", dmDef.getUrl()); assertEquals("myuser1", dmDef.getOptionalUserName()); assertEquals("mypassword1", dmDef.getOptionalPassword()); assertEquals("{user=myuser2, password=mypassword2, somearg=someargvalue}", dmDef.getOptionalProperties().toString()); assertEquals(ConfigurationDBRef.ConnectionLifecycleEnum.RETAIN, configDBRef.getConnectionLifecycleEnum()); assertEquals((Boolean) false, configDBRef.getConnectionSettings().getAutoCommit()); assertEquals("test", configDBRef.getConnectionSettings().getCatalog()); assertEquals(Boolean.TRUE, configDBRef.getConnectionSettings().getReadOnly()); assertEquals(new Integer(3), configDBRef.getConnectionSettings().getTransactionIsolation()); ConfigurationExpiryTimeCache expCache = (ConfigurationExpiryTimeCache) configDBRef.getDataCacheDesc(); assertEquals(60.5, expCache.getMaxAgeSeconds()); assertEquals(120.1, expCache.getPurgeIntervalSeconds()); assertEquals(ConfigurationCacheReferenceType.HARD, expCache.getCacheReferenceType()); assertEquals(ConfigurationDBRef.ColumnChangeCaseEnum.UPPERCASE, configDBRef.getColumnChangeCase()); assertEquals(ConfigurationDBRef.MetadataOriginEnum.METADATA, configDBRef.getMetadataRetrievalEnum()); assertEquals(1, configDBRef.getSqlTypesMapping().size()); assertEquals("java.lang.String", configDBRef.getSqlTypesMapping().get(99)); // assert database reference - data source factory and DBCP config configDBRef = config.getDatabaseReferences().get("mydb3"); ConfigurationDBRef.DataSourceFactory dsFactory = (ConfigurationDBRef.DataSourceFactory) configDBRef .getConnectionFactoryDesc(); assertEquals("org.apache.commons.dbcp.BasicDataSourceFactory", dsFactory.getFactoryClassname()); assertEquals("jdbc:mysql://localhost/test", dsFactory.getProperties().getProperty("url")); assertEquals("myusername", dsFactory.getProperties().getProperty("username")); assertEquals("mypassword", dsFactory.getProperties().getProperty("password")); assertEquals("com.mysql.jdbc.Driver", dsFactory.getProperties().getProperty("driverClassName")); assertEquals("2", dsFactory.getProperties().getProperty("initialSize")); // assert custom view implementations List<ConfigurationPlugInView> configViews = config.getPlugInViews(); assertEquals(2, configViews.size()); for (int i = 0; i < configViews.size(); i++) { ConfigurationPlugInView entry = configViews.get(i); assertEquals("ext" + i, entry.getNamespace()); assertEquals("myview" + i, entry.getName()); assertEquals("com.mycompany.MyViewFactory" + i, entry.getFactoryClassName()); } // assert custom virtual data window implementations List<ConfigurationPlugInVirtualDataWindow> configVDW = config.getPlugInVirtualDataWindows(); assertEquals(2, configVDW.size()); for (int i = 0; i < configVDW.size(); i++) { ConfigurationPlugInVirtualDataWindow entry = configVDW.get(i); assertEquals("vdw" + i, entry.getNamespace()); assertEquals("myvdw" + i, entry.getName()); assertEquals("com.mycompany.MyVdwFactory" + i, entry.getFactoryClassName()); if (i == 1) { assertEquals("abc", entry.getConfig()); } } // assert adapter loaders parsed List<ConfigurationPluginLoader> plugins = config.getPluginLoaders(); assertEquals(2, plugins.size()); ConfigurationPluginLoader pluginOne = plugins.get(0); assertEquals("Loader1", pluginOne.getLoaderName()); assertEquals("com.espertech.esper.support.plugin.SupportLoaderOne", pluginOne.getClassName()); assertEquals(2, pluginOne.getConfigProperties().size()); assertEquals("val1", pluginOne.getConfigProperties().get("name1")); assertEquals("val2", pluginOne.getConfigProperties().get("name2")); assertEquals( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sample-initializer><some-any-xml-can-be-here>This section for use by a plugin loader.</some-any-xml-can-be-here></sample-initializer>", pluginOne.getConfigurationXML()); ConfigurationPluginLoader pluginTwo = plugins.get(1); assertEquals("Loader2", pluginTwo.getLoaderName()); assertEquals("com.espertech.esper.support.plugin.SupportLoaderTwo", pluginTwo.getClassName()); assertEquals(0, pluginTwo.getConfigProperties().size()); // assert plug-in aggregation function loaded assertEquals(4, config.getPlugInAggregationFunctions().size()); ConfigurationPlugInAggregationFunction pluginAgg = config.getPlugInAggregationFunctions().get(0); assertEquals("com.mycompany.MyMatrixAggregationMethod0DEPRECATED", pluginAgg.getFunctionClassName()); assertEquals("func1", pluginAgg.getName()); assertEquals(null, pluginAgg.getFactoryClassName()); pluginAgg = config.getPlugInAggregationFunctions().get(1); assertEquals("com.mycompany.MyMatrixAggregationMethod1DEPRECATED", pluginAgg.getFunctionClassName()); assertEquals("func2", pluginAgg.getName()); assertEquals(null, pluginAgg.getFactoryClassName()); pluginAgg = config.getPlugInAggregationFunctions().get(2); assertEquals(null, pluginAgg.getFunctionClassName()); assertEquals("func1a", pluginAgg.getName()); assertEquals("com.mycompany.MyMatrixAggregationMethod0Factory", pluginAgg.getFactoryClassName()); pluginAgg = config.getPlugInAggregationFunctions().get(3); assertEquals(null, pluginAgg.getFunctionClassName()); assertEquals("func2a", pluginAgg.getName()); assertEquals("com.mycompany.MyMatrixAggregationMethod1Factory", pluginAgg.getFactoryClassName()); // assert plug-in aggregation multi-function loaded assertEquals(1, config.getPlugInAggregationMultiFunctions().size()); ConfigurationPlugInAggregationMultiFunction pluginMultiAgg = config.getPlugInAggregationMultiFunctions() .get(0); EPAssertionUtil.assertEqualsExactOrder(new String[] { "func1", "func2" }, pluginMultiAgg.getFunctionNames()); assertEquals("com.mycompany.MyAggregationMultiFunctionFactory", pluginMultiAgg.getMultiFunctionFactoryClassName()); assertEquals(1, pluginMultiAgg.getAdditionalConfiguredProperties().size()); assertEquals("value1", pluginMultiAgg.getAdditionalConfiguredProperties().get("prop1")); // assert plug-in singlerow function loaded assertEquals(2, config.getPlugInSingleRowFunctions().size()); ConfigurationPlugInSingleRowFunction pluginSingleRow = config.getPlugInSingleRowFunctions().get(0); assertEquals("com.mycompany.MyMatrixSingleRowMethod0", pluginSingleRow.getFunctionClassName()); assertEquals("method1", pluginSingleRow.getFunctionMethodName()); assertEquals("func3", pluginSingleRow.getName()); assertEquals(ConfigurationPlugInSingleRowFunction.ValueCache.DISABLED, pluginSingleRow.getValueCache()); assertEquals(ConfigurationPlugInSingleRowFunction.FilterOptimizable.ENABLED, pluginSingleRow.getFilterOptimizable()); assertFalse(pluginSingleRow.isRethrowExceptions()); pluginSingleRow = config.getPlugInSingleRowFunctions().get(1); assertEquals("com.mycompany.MyMatrixSingleRowMethod1", pluginSingleRow.getFunctionClassName()); assertEquals("func4", pluginSingleRow.getName()); assertEquals("method2", pluginSingleRow.getFunctionMethodName()); assertEquals(ConfigurationPlugInSingleRowFunction.ValueCache.ENABLED, pluginSingleRow.getValueCache()); assertEquals(ConfigurationPlugInSingleRowFunction.FilterOptimizable.DISABLED, pluginSingleRow.getFilterOptimizable()); assertTrue(pluginSingleRow.isRethrowExceptions()); // assert plug-in guard objects loaded assertEquals(4, config.getPlugInPatternObjects().size()); ConfigurationPlugInPatternObject pluginPattern = config.getPlugInPatternObjects().get(0); assertEquals("com.mycompany.MyGuardFactory0", pluginPattern.getFactoryClassName()); assertEquals("ext0", pluginPattern.getNamespace()); assertEquals("guard1", pluginPattern.getName()); assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.GUARD, pluginPattern.getPatternObjectType()); pluginPattern = config.getPlugInPatternObjects().get(1); assertEquals("com.mycompany.MyGuardFactory1", pluginPattern.getFactoryClassName()); assertEquals("ext1", pluginPattern.getNamespace()); assertEquals("guard2", pluginPattern.getName()); assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.GUARD, pluginPattern.getPatternObjectType()); pluginPattern = config.getPlugInPatternObjects().get(2); assertEquals("com.mycompany.MyObserverFactory0", pluginPattern.getFactoryClassName()); assertEquals("ext0", pluginPattern.getNamespace()); assertEquals("observer1", pluginPattern.getName()); assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.OBSERVER, pluginPattern.getPatternObjectType()); pluginPattern = config.getPlugInPatternObjects().get(3); assertEquals("com.mycompany.MyObserverFactory1", pluginPattern.getFactoryClassName()); assertEquals("ext1", pluginPattern.getNamespace()); assertEquals("observer2", pluginPattern.getName()); assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.OBSERVER, pluginPattern.getPatternObjectType()); // assert engine defaults assertFalse(config.getEngineDefaults().getThreading().isInsertIntoDispatchPreserveOrder()); assertEquals(3000, config.getEngineDefaults().getThreading().getInsertIntoDispatchTimeout()); assertEquals(ConfigurationEngineDefaults.Threading.Locking.SUSPEND, config.getEngineDefaults().getThreading().getInsertIntoDispatchLocking()); assertFalse(config.getEngineDefaults().getThreading().isListenerDispatchPreserveOrder()); assertEquals(2000, config.getEngineDefaults().getThreading().getListenerDispatchTimeout()); assertEquals(ConfigurationEngineDefaults.Threading.Locking.SUSPEND, config.getEngineDefaults().getThreading().getListenerDispatchLocking()); assertTrue(config.getEngineDefaults().getThreading().isThreadPoolInbound()); assertTrue(config.getEngineDefaults().getThreading().isThreadPoolOutbound()); assertTrue(config.getEngineDefaults().getThreading().isThreadPoolRouteExec()); assertTrue(config.getEngineDefaults().getThreading().isThreadPoolTimerExec()); assertEquals(1, config.getEngineDefaults().getThreading().getThreadPoolInboundNumThreads()); assertEquals(2, config.getEngineDefaults().getThreading().getThreadPoolOutboundNumThreads()); assertEquals(3, config.getEngineDefaults().getThreading().getThreadPoolTimerExecNumThreads()); assertEquals(4, config.getEngineDefaults().getThreading().getThreadPoolRouteExecNumThreads()); assertEquals(1000, (int) config.getEngineDefaults().getThreading().getThreadPoolInboundCapacity()); assertEquals(1500, (int) config.getEngineDefaults().getThreading().getThreadPoolOutboundCapacity()); assertEquals(null, config.getEngineDefaults().getThreading().getThreadPoolTimerExecCapacity()); assertEquals(2000, (int) config.getEngineDefaults().getThreading().getThreadPoolRouteExecCapacity()); assertFalse(config.getEngineDefaults().getThreading().isInternalTimerEnabled()); assertEquals(1234567, config.getEngineDefaults().getThreading().getInternalTimerMsecResolution()); assertFalse(config.getEngineDefaults().getViewResources().isShareViews()); assertTrue(config.getEngineDefaults().getViewResources().isAllowMultipleExpiryPolicies()); assertEquals(Configuration.PropertyResolutionStyle.DISTINCT_CASE_INSENSITIVE, config.getEngineDefaults().getEventMeta().getClassPropertyResolutionStyle()); assertEquals(ConfigurationEventTypeLegacy.AccessorStyle.PUBLIC, config.getEngineDefaults().getEventMeta().getDefaultAccessorStyle()); assertEquals(Configuration.EventRepresentation.MAP, config.getEngineDefaults().getEventMeta().getDefaultEventRepresentation()); assertEquals(100, config.getEngineDefaults().getEventMeta().getAnonymousCacheSize()); assertTrue(config.getEngineDefaults().getLogging().isEnableExecutionDebug()); assertFalse(config.getEngineDefaults().getLogging().isEnableTimerDebug()); assertTrue(config.getEngineDefaults().getLogging().isEnableQueryPlan()); assertTrue(config.getEngineDefaults().getLogging().isEnableJDBC()); assertEquals("[%u] %m", config.getEngineDefaults().getLogging().getAuditPattern()); assertEquals(30000, config.getEngineDefaults().getVariables().getMsecVersionRelease()); assertEquals(3L, (long) config.getEngineDefaults().getPatterns().getMaxSubexpressions()); assertEquals(false, config.getEngineDefaults().getPatterns().isMaxSubexpressionPreventStart()); assertEquals(StreamSelector.RSTREAM_ISTREAM_BOTH, config.getEngineDefaults().getStreamSelection().getDefaultStreamSelector()); assertEquals(ConfigurationEngineDefaults.TimeSourceType.NANO, config.getEngineDefaults().getTimeSource().getTimeSourceType()); assertTrue(config.getEngineDefaults().getExecution().isPrioritized()); assertTrue(config.getEngineDefaults().getExecution().isFairlock()); assertTrue(config.getEngineDefaults().getExecution().isDisableLocking()); assertEquals(ConfigurationEngineDefaults.ThreadingProfile.LARGE, config.getEngineDefaults().getExecution().getThreadingProfile()); ConfigurationMetricsReporting metrics = config.getEngineDefaults().getMetricsReporting(); assertTrue(metrics.isEnableMetricsReporting()); assertEquals(4000L, metrics.getEngineInterval()); assertEquals(500L, metrics.getStatementInterval()); assertFalse(metrics.isThreading()); assertEquals(2, metrics.getStatementGroups().size()); assertTrue(metrics.isJmxEngineMetrics()); ConfigurationMetricsReporting.StmtGroupMetrics def = metrics.getStatementGroups().get("MyStmtGroup"); assertEquals(5000, def.getInterval()); assertTrue(def.isDefaultInclude()); assertEquals(50, def.getNumStatements()); assertTrue(def.isReportInactive()); assertEquals(5, def.getPatterns().size()); assertEquals(def.getPatterns().get(0), new Pair<StringPatternSet, Boolean>(new StringPatternSetRegex(".*"), true)); assertEquals(def.getPatterns().get(1), new Pair<StringPatternSet, Boolean>(new StringPatternSetRegex(".*test.*"), false)); assertEquals(def.getPatterns().get(2), new Pair<StringPatternSet, Boolean>(new StringPatternSetLike("%MyMetricsStatement%"), false)); assertEquals(def.getPatterns().get(3), new Pair<StringPatternSet, Boolean>(new StringPatternSetLike("%MyFraudAnalysisStatement%"), true)); assertEquals(def.getPatterns().get(4), new Pair<StringPatternSet, Boolean>(new StringPatternSetLike("%SomerOtherStatement%"), true)); def = metrics.getStatementGroups().get("MyStmtGroupTwo"); assertEquals(200, def.getInterval()); assertFalse(def.isDefaultInclude()); assertEquals(100, def.getNumStatements()); assertFalse(def.isReportInactive()); assertEquals(0, def.getPatterns().size()); assertTrue(config.getEngineDefaults().getLanguage().isSortUsingCollator()); assertTrue(config.getEngineDefaults().getExpression().isIntegerDivision()); assertTrue(config.getEngineDefaults().getExpression().isDivisionByZeroReturnsNull()); assertFalse(config.getEngineDefaults().getExpression().isSelfSubselectPreeval()); assertFalse(config.getEngineDefaults().getExpression().isUdfCache()); assertFalse(config.getEngineDefaults().getExpression().isExtendedAggregation()); assertTrue(config.getEngineDefaults().getExpression().isDuckTyping()); assertEquals(2, config.getEngineDefaults().getExpression().getMathContext().getPrecision()); assertEquals(RoundingMode.CEILING, config.getEngineDefaults().getExpression().getMathContext().getRoundingMode()); assertEquals(2, config.getEngineDefaults().getExceptionHandling().getHandlerFactories().size()); assertEquals("my.company.cep.LoggingExceptionHandlerFactory", config.getEngineDefaults().getExceptionHandling().getHandlerFactories().get(0)); assertEquals("my.company.cep.AlertExceptionHandlerFactory", config.getEngineDefaults().getExceptionHandling().getHandlerFactories().get(1)); assertEquals(2, config.getEngineDefaults().getConditionHandling().getHandlerFactories().size()); assertEquals("my.company.cep.LoggingConditionHandlerFactory", config.getEngineDefaults().getConditionHandling().getHandlerFactories().get(0)); assertEquals("my.company.cep.AlertConditionHandlerFactory", config.getEngineDefaults().getConditionHandling().getHandlerFactories().get(1)); assertEquals("abc", config.getEngineDefaults().getScripts().getDefaultDialect()); // variables assertEquals(3, config.getVariables().size()); ConfigurationVariable variable = config.getVariables().get("var1"); assertEquals(Integer.class.getName(), variable.getType()); assertEquals("1", variable.getInitializationValue()); assertFalse(variable.isConstant()); variable = config.getVariables().get("var2"); assertEquals(String.class.getName(), variable.getType()); assertEquals(null, variable.getInitializationValue()); assertFalse(variable.isConstant()); variable = config.getVariables().get("var3"); assertTrue(variable.isConstant()); // method references assertEquals(2, config.getMethodInvocationReferences().size()); ConfigurationMethodRef methodRef = config.getMethodInvocationReferences().get("abc"); expCache = (ConfigurationExpiryTimeCache) methodRef.getDataCacheDesc(); assertEquals(91.0, expCache.getMaxAgeSeconds()); assertEquals(92.2, expCache.getPurgeIntervalSeconds()); assertEquals(ConfigurationCacheReferenceType.WEAK, expCache.getCacheReferenceType()); methodRef = config.getMethodInvocationReferences().get("def"); lruCache = (ConfigurationLRUCache) methodRef.getDataCacheDesc(); assertEquals(20, lruCache.getSize()); // plug-in event representations assertEquals(2, config.getPlugInEventRepresentation().size()); ConfigurationPlugInEventRepresentation rep = config.getPlugInEventRepresentation() .get(new URI("type://format/rep/name")); assertEquals("com.mycompany.MyPlugInEventRepresentation", rep.getEventRepresentationClassName()); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><anyxml>test string event rep init</anyxml>", rep.getInitializer()); rep = config.getPlugInEventRepresentation().get(new URI("type://format/rep/name2")); assertEquals("com.mycompany.MyPlugInEventRepresentation2", rep.getEventRepresentationClassName()); assertEquals(null, rep.getInitializer()); // plug-in event types assertEquals(2, config.getPlugInEventTypes().size()); ConfigurationPlugInEventType type = config.getPlugInEventTypes().get("MyEvent"); assertEquals(2, type.getEventRepresentationResolutionURIs().length); assertEquals("type://format/rep", type.getEventRepresentationResolutionURIs()[0].toString()); assertEquals("type://format/rep2", type.getEventRepresentationResolutionURIs()[1].toString()); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><anyxml>test string event type init</anyxml>", type.getInitializer()); type = config.getPlugInEventTypes().get("MyEvent2"); assertEquals(1, type.getEventRepresentationResolutionURIs().length); assertEquals("type://format/rep2", type.getEventRepresentationResolutionURIs()[0].toString()); assertEquals(null, type.getInitializer()); // plug-in event representation resolution URIs when using a new name in a statement assertEquals(2, config.getPlugInEventTypeResolutionURIs().length); assertEquals("type://format/rep", config.getPlugInEventTypeResolutionURIs()[0].toString()); assertEquals("type://format/rep2", config.getPlugInEventTypeResolutionURIs()[1].toString()); // revision types assertEquals(1, config.getRevisionEventTypes().size()); ConfigurationRevisionEventType configRev = config.getRevisionEventTypes().get("MyRevisionEvent"); assertEquals(1, configRev.getNameBaseEventTypes().size()); assertTrue(configRev.getNameBaseEventTypes().contains("MyBaseEventName")); assertTrue(configRev.getNameDeltaEventTypes().contains("MyDeltaEventNameOne")); assertTrue(configRev.getNameDeltaEventTypes().contains("MyDeltaEventNameTwo")); EPAssertionUtil.assertEqualsAnyOrder(new String[] { "id", "id2" }, configRev.getKeyPropertyNames()); assertEquals(ConfigurationRevisionEventType.PropertyRevision.MERGE_NON_NULL, configRev.getPropertyRevision()); // variance types assertEquals(1, config.getVariantStreams().size()); ConfigurationVariantStream configVStream = config.getVariantStreams().get("MyVariantStream"); assertEquals(2, configVStream.getVariantTypeNames().size()); assertTrue(configVStream.getVariantTypeNames().contains("MyEvenTypetNameOne")); assertTrue(configVStream.getVariantTypeNames().contains("MyEvenTypetNameTwo")); assertEquals(ConfigurationVariantStream.TypeVariance.ANY, configVStream.getTypeVariance()); }
From source file:pcgui.SetupParametersPanel.java
private String generateDependentArray(Symbol sym, RealDistribution realDist) { ArrayList<Integer> paramValList = new ArrayList<Integer>(); for (Object param : sym.arrayParams) { //extract the dimension param = (String) param;//from w ww . j a va 2 s .c o m System.out.println("Param name =" + param); try { if (hashTable.containsKey(param)) { Symbol depSym = (Symbol) hashTable.get(param); String typeString = depSym.typeString; if ("Integer".equalsIgnoreCase(typeString.trim())) { Object strVal = depSym.get(); //can only allow allow one more level of dependency //varA Integer varB //ourSym array(varA,varC) if (hashTable.containsKey(strVal)) { Symbol s = (Symbol) hashTable.get(strVal); Integer val = (Integer) s.get(); paramValList.add(val); } else { Integer val = (Integer) strVal; paramValList.add(val); } } else if ("Set".equalsIgnoreCase(typeString.trim())) { String strVal = (String) depSym.get(); if (strVal.contains("..")) { //1..varA //take the upper limit String sizeVar = strVal.split("\\.\\.")[1]; if (hashTable.containsKey(sizeVar)) { Symbol s = (Symbol) hashTable.get(sizeVar); //only take the value of this var //not more than 2 level of dependency Integer val = (Integer) s.get(); paramValList.add(val); } else { //1..12 Integer val = Integer.parseInt((String) sizeVar); paramValList.add(val); } } else { //can only parse simple set size //{A,B,C,D} //{A //B //C //D} //we can get size by splitting using comma "," String strVal2 = (String) depSym.get(); Integer val = strVal2.split(",").length; paramValList.add(val); } } } else { //for constant integers //ourSym array(varA,5) Integer val = Integer.parseInt((String) param); paramValList.add(val); } } catch (IllegalArgumentException e) { e.printStackTrace(); //JOptionPane.showMessageDialog(this,"Check dimensions of variable "+sym.name, "Error", JOptionPane.ERROR_MESSAGE); return null; } } long arraySize = 1; StringBuilder sb = new StringBuilder(); for (Integer val : paramValList) { // System.out.println("UpdatedParam : "+val); arraySize *= val; } sb.append("["); for (long r = 1; r <= arraySize; r++) { DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.CEILING); String val = df.format(realDist.sample()); sb.append(val); sb.append(", "); } //remove the last "," sb.replace(sb.length() - 2, sb.length(), ""); sb.append("]"); // System.out.println("Generated Array: "+ sym.name); // System.out.println(sb.toString()); return sb.toString(); }
From source file:pcgui.SetupParametersPanel.java
/** * @param sym/*from w w w. ja va 2 s . c om*/ * @param realDist */ private String generateIndependentArray(Symbol sym, RealDistribution realDist) { ArrayList<Integer> paramValList = new ArrayList<Integer>(); for (Object param : sym.arrayParams) { //extract the dimension param = (String) param; try { Integer val = Integer.parseInt((String) param); paramValList.add(val); } catch (IllegalArgumentException e) { e.printStackTrace(); //JOptionPane.showMessageDialog(this,"Check dimension of variable "+sym.name, "Error", JOptionPane.ERROR_MESSAGE); return null; } } long arraySize = 1; StringBuilder sb = new StringBuilder(); for (Integer val : paramValList) { // System.out.println("UpdatedParam : "+val); arraySize *= val; } sb.append("["); for (long r = 1; r <= arraySize; r++) { DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.CEILING); String val = df.format(realDist.sample()); sb.append(val); sb.append(", "); } //remove the last "," sb.replace(sb.length() - 2, sb.length(), ""); sb.append("]"); // System.out.println("Generated Array: "+ sym.name); // System.out.println(sb.toString()); return sb.toString(); }
From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java
/** * @param empcntClientProjectDataList/*from w ww.j a v a 2s . co m*/ * @param empClientProjectTeamStructList * @param employee * @param month * @param year * @param costCentre * @param countType * @param allignedTimeZero * @param assistedTimeZero * @param apportionedTimeZero * @param allignedTimeOne * @param totalTimeOne * @return */ private void getMultipleProjectDetail(List<EmpcntClientProjectData> empOpenCntClientProjectDataList, List<EmpcntClientProjectData> empCloseCntClientProjectDataList, List<EmpClientProjectTeamStruct> empClientProjectTeamStructList, EmployeeMaster employee, TabMonth month, TabYear year, CostCentre costCentre, CountClassification countType, BigDecimal allignedTimeZero, BigDecimal assistedTimeZero, BigDecimal apportionedTimeZero, BigDecimal allignedTimeOne, BigDecimal totalTimeOne, Integer countTypeId, Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) { logger.debug("<====getMultipleProjectDetail START====>"); Integer employeeId = employee.getEmployeeId(); Integer yearId = year.getYearId(); Integer monthId = month.getMonthId(); String costCentreId = costCentre.getCostCentreId(); BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS); logger.debug("getMultipleProjectDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::" + costCentreId + "::" + deviderHour); // Get project details Map<Integer, EmpClientProjectTeamStruct> employeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>(); Map<Integer, EmpClientProjectTeamStruct> validEmployeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>(); for (EmpClientProjectTeamStruct empClientProjectTeamStructThree : empClientProjectTeamStructList) { employeeProjectIds.put(empClientProjectTeamStructThree.getProjectMaster().getProjectId(), empClientProjectTeamStructThree); } validEmployeeProjectIds.putAll(employeeProjectIds); // logger.debug("validEmployeeProjectIds 1:size===>" + // validEmployeeProjectIds.size()); // check in revenue table for (Integer key : employeeProjectIds.keySet()) { EmpClientProjectTeamStruct mapValues = employeeProjectIds.get(key); List<CollageProjectRevenue> listValues = collageProjectRevenueDao .findByYearIdMonthIdProjectIdCostCentreId(mapValues.getTabYear().getYearId(), mapValues.getTabMonth().getMonthId(), mapValues.getProjectMaster().getProjectId(), costCentre.getCostCentreId()); if (listValues.isEmpty()) { validEmployeeProjectIds.remove(key); } } // logger.debug("validEmployeeProjectIds 2:size===>" + // validEmployeeProjectIds.size()); // For all invalid projects calculate count zero if (validEmployeeProjectIds.isEmpty()) { getZeroProjectsDetail(yearId, monthId, costCentreId, empOpenCntClientProjectDataList, empCloseCntClientProjectDataList, employee, month, year, costCentre, countType, allignedTimeZero, assistedTimeZero, totalTimeOne, totalTimeOne, countTypeId, employeePcTagsTeamStructMap); } // Get list of project from execution data for that employee List<Integer> projectIdList = executionDataDao.findByPersonYearMonthCostCentre(employeeId, yearId, monthId, costCentreId); // logger.debug("execution data projects===>" + projectIdList.size()); // If List is empty if (projectIdList.isEmpty()) { // logger.debug("Contain InValid projects (: Find by Revenue)===>"); Map<Integer, BigDecimal> projectRevenueMap = new HashMap<Integer, BigDecimal>(); BigDecimal sumOfRevenue = BigDecimal.ZERO; List<Object[]> collageProjectRevenueList = collageProjectRevenueDao.findByCostCentreIdYearIdMonthId( costCentre.getCostCentreId(), year.getYearId(), month.getMonthId()); for (Object[] collageProjectRevenue : collageProjectRevenueList) { Integer projectId = (Integer) collageProjectRevenue[0]; BigDecimal revenue = (BigDecimal) collageProjectRevenue[1]; projectRevenueMap.put(projectId, revenue); } // logger.debug("projectRevenueMap size===>" + // projectRevenueMap.size()); for (Integer key : projectRevenueMap.keySet()) { sumOfRevenue = sumOfRevenue.add(projectRevenueMap.get(key)); } logger.debug("sumOfRevenue===>" + sumOfRevenue); for (Integer projectId : validEmployeeProjectIds.keySet()) { EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); BigDecimal revenue = projectRevenueMap.get(projectId); logger.debug("revenue===>" + revenue); BigDecimal projectRevenueCount = revenue.divide(sumOfRevenue, 2, RoundingMode.HALF_EVEN); projectRevenueCount = projectRevenueCount.setScale(2, RoundingMode.CEILING); // logger.debug("685 empOpenCntClientProjectData ProjectId:Revenue===>"+projectId+" : " // + projectRevenueCount); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, projectRevenueCount, BigDecimal.ZERO, BigDecimal.ZERO, projectRevenueCount); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else { // logger.debug("Else Contain Valid projects===>"); Integer validEmployeeProjectCount = validEmployeeProjectIds.size(); // Get valid projects list=>project is both revenue data and // execution data Set<Integer> validAllProjects = new HashSet<Integer>(); for (Integer projectId : projectIdList) { List<CollageProjectRevenue> listValues = collageProjectRevenueDao .findByYearIdMonthIdProjectIdCostCentreId(yearId, monthId, projectId, costCentreId); if (!listValues.isEmpty()) { validAllProjects.add(projectId); } } Integer validAllProjectCount = validAllProjects.size(); // logger.debug("validAllProjects :size===>" + // validAllProjects.size()); // Total hour worked by an Employee List<BigDecimal> toatalHours = executionDataDao.findByPersonIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId); BigDecimal toatlTime = toatalHours.get(0); // logger.debug("ToatalHours===>" + toatlTime); // Separate assigned projects from execution data projects Map<Integer, BigDecimal> assignedProjects = new HashMap<Integer, BigDecimal>(); Map<Integer, BigDecimal> unAssignedProjects = new HashMap<Integer, BigDecimal>(); List<Object[]> allProjectTimeList = executionDataDao .findByEmployeeIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId); for (Object[] result : allProjectTimeList) { Integer projectId = (Integer) result[0]; BigDecimal hour = (BigDecimal) result[1]; Integer companyId = (Integer) result[2]; if (validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) { // logger.debug("UnAssignedProjects===>" + // projectId+"::"+hour+"::"+companyId); assignedProjects.put(projectId, hour); } if (!validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) { // logger.debug("assignedProjects===>" + // projectId+"::"+hour+"::"+companyId); unAssignedProjects.put(projectId, hour); } } if (validEmployeeProjectCount == validAllProjectCount && validAllProjects.containsAll(validEmployeeProjectIds.keySet()) && unAssignedProjects.isEmpty()) { // logger.debug("validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)"); for (Integer key : assignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = assignedProjects.get(key); EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); // logger.debug("744 : Worked hours (Only in assigned projects) 1===>"+timeByProject+ // " : "+toatlTime); BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // logger.debug("745: Worked hours (Only in assigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else if (!assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) { // logger.debug("validEmployeeProjectCount!=validAllProjectCount :(Both in assigned and unassigned projects)"); if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) { // logger.debug("Worked hours===> >=168"); for (Integer key : assignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = assignedProjects.get(key); EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // logger.debug("768: Aligned hours (Both in assigned and unassigned projects) 1===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = unAssignedProjects.get(key); List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); ProjectMaster projectMaster = projectList.get(0); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // logger.debug("787: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else { // logger.debug("Worked hours===> <168"); BigDecimal totalUnAssingnedHours = BigDecimal.ZERO; BigDecimal assingnedHours = BigDecimal.ZERO; for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; // logger.debug("Project Id===>"+key); BigDecimal timeByProject = unAssignedProjects.get(key); BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours); // Assign to assisted count for unAssignedProjects List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); ProjectMaster projectMaster = projectList.get(0); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); // logger.debug("811: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } totalUnAssingnedHours = BigDecimal.ONE.subtract(totalUnAssingnedHours); // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours); for (Map.Entry<Integer, BigDecimal> entry : assignedProjects.entrySet()) { assingnedHours = assingnedHours.add(entry.getValue()); } // logger.debug("Aligned Hours===> "+assingnedHours); for (Integer key : assignedProjects.keySet()) { Integer projectId = key; BigDecimal timeByProject = assignedProjects.get(key); // logger.debug("831 :projectId : timeByProject===> "+projectId+" : "+timeByProject); EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); BigDecimal averageWorkedHours = timeByProject.divide(assingnedHours, 2, RoundingMode.HALF_EVEN); // logger.debug("834 :averageWorkedHours : assingnedHours===> "+averageWorkedHours+" : "+assingnedHours); BigDecimal actualWorkedHours = averageWorkedHours.multiply(totalUnAssingnedHours); actualWorkedHours = actualWorkedHours.setScale(2, RoundingMode.CEILING); // logger.debug("836: actualWorkedHours : totalUnAssingnedHours 2===>"+actualWorkedHours+" : "+totalUnAssingnedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, actualWorkedHours, assistedTimeZero, apportionedTimeZero, actualWorkedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } } else if (assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) { // logger.debug("Only in unassigned projects===>"); if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) { // logger.debug(" unassigned projects Worked hours===> >=168"); for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = unAssignedProjects.get(key); List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); ProjectMaster projectMaster = projectList.get(0); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // logger.debug("860: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else { // logger.debug("unassigned projects Worked hours===> <168"); BigDecimal totalUnAssingnedHours = BigDecimal.ZERO; BigDecimal assingnedHours = BigDecimal.ZERO; for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = unAssignedProjects.get(key); BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours); // Assign to assisted count for unAssignedProjects List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); ProjectMaster projectMaster = projectList.get(0); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); // logger.debug("884: Assisted hours in unassigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours); if (totalUnAssingnedHours.compareTo(BigDecimal.ONE) == -1) { BigDecimal remainProportion = BigDecimal.ONE.subtract(totalUnAssingnedHours); getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList, employee, month, year, costCentre, countType, remainProportion, unAssignedProjects, countTypeId, employeePcTagsTeamStructMap); } } } } // logger.debug("<====getMultipleProjectDetail END====>"); }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#round(Object, Number, RoundingMode, Class)}. *//*w w w .j a v a 2 s . c o m*/ @SuppressWarnings("unchecked") @Test public void testRoundObjectNumberRoundingModeClassOfT() { assertEquals("null", null, round(null, null, null, null)); try { for (Class<?> type : NUMBERS) { Object expected = null; if (ObjectUtils.isAny(ClassUtils.primitiveToWrapper(type), Float.class, Double.class)) { expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class).invoke(null, "3.14"); } else if (ClassUtils.isPrimitiveOrWrapper(type)) { expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class).invoke(null, "3"); } else { expected = new BigDecimal("3.14"); if (BigInteger.class.equals(type)) expected = ((BigDecimal) expected).toBigInteger(); } assertEquals("PI: " + type.getSimpleName(), expected, round(Math.PI, 2, RoundingMode.HALF_UP, (Class<? extends Number>) type)); if (ObjectUtils.isAny(ClassUtils.primitiveToWrapper(type), Float.class, Double.class)) { expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class).invoke(null, "3.15"); } else if (ClassUtils.isPrimitiveOrWrapper(type)) { expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class).invoke(null, "3"); } else { expected = new BigDecimal("3.15"); if (BigInteger.class.equals(type)) expected = ((BigDecimal) expected).toBigInteger(); } assertEquals("PI: " + type.getSimpleName(), expected, round(Math.PI, 2, RoundingMode.CEILING, (Class<? extends Number>) type)); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } }
From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java
/** * @param empcntClientProjectDataList/*from w w w. j a va 2s . co m*/ * @param empClientProjectTeamStructList * @param employee * @param month * @param year * @param costCentre * @param countType * @param allignedTimeZero * @param assistedTimeZero * @param apportionedTimeZero * @param allignedTimeOne * @param totalTimeOne */ private void getSingleProjectDetail(List<EmpcntClientProjectData> empOpenCntClientProjectDataList, List<EmpcntClientProjectData> empCloseCntClientProjectDataList, List<EmpClientProjectTeamStruct> empClientProjectTeamStructList, EmployeeMaster employee, TabMonth month, TabYear year, CostCentre costCentre, CountClassification countType, BigDecimal allignedTimeZero, BigDecimal assistedTimeZero, BigDecimal apportionedTimeZero, BigDecimal allignedTimeOne, BigDecimal totalTimeOne, Integer countTypeId, Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) { /* * Also assign to assisted if project detail present in both assigned * and unassigned list * * Note : Only in unassigned project . do the remaining count as per * revenue to apportion * * If not present in revenue table then go to zero project details */ logger.debug("<====getSingleProjectDetail START====>"); Integer employeeId = employee.getEmployeeId(); Integer yearId = year.getYearId(); Integer monthId = month.getMonthId(); String costCentreId = costCentre.getCostCentreId(); BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS); logger.debug("getSingleProjectDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::" + costCentreId + "::" + deviderHour); // Get project details Map<Integer, EmpClientProjectTeamStruct> employeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>(); Map<Integer, EmpClientProjectTeamStruct> validEmployeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>(); for (EmpClientProjectTeamStruct empClientProjectTeamStructThree : empClientProjectTeamStructList) { employeeProjectIds.put(empClientProjectTeamStructThree.getProjectMaster().getProjectId(), empClientProjectTeamStructThree); } validEmployeeProjectIds.putAll(employeeProjectIds); // logger.debug("validEmployeeProjectIds 1:size===>" + // validEmployeeProjectIds.size()); // check in revenue table for (Integer key : employeeProjectIds.keySet()) { EmpClientProjectTeamStruct mapValues = employeeProjectIds.get(key); List<CollageProjectRevenue> listValues = collageProjectRevenueDao .findByYearIdMonthIdProjectIdCostCentreId(mapValues.getTabYear().getYearId(), mapValues.getTabMonth().getMonthId(), mapValues.getProjectMaster().getProjectId(), costCentre.getCostCentreId()); if (listValues.isEmpty()) { validEmployeeProjectIds.remove(key); } } // logger.debug("validEmployeeProjectIds 2:size===>" + // validEmployeeProjectIds.size()); if (validEmployeeProjectIds.isEmpty()) { getZeroProjectsDetail(yearId, monthId, costCentreId, empOpenCntClientProjectDataList, empCloseCntClientProjectDataList, employee, month, year, costCentre, countType, allignedTimeZero, assistedTimeZero, totalTimeOne, totalTimeOne, countTypeId, employeePcTagsTeamStructMap); } // Get list of project from execution data for that employee List<Integer> projectIdList = executionDataDao.findByPersonYearMonthCostCentre(employeeId, yearId, monthId, costCentreId); // logger.debug("execution data projects===>" + projectIdList.size()); if (projectIdList.isEmpty()) { // logger.debug("Contain InValid projects :(Assign count one)===>"); for (Integer projectId : validEmployeeProjectIds.keySet()) { EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); // logger.debug("978: Contain InValid projects :(Assign count one)===>"+1); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, allignedTimeOne, assistedTimeZero, apportionedTimeZero, allignedTimeOne); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } else if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else { // logger.debug("Else Contain Valid projects===>"); Integer validEmployeeProjectCount = validEmployeeProjectIds.size(); // Get valid projects list=>project is both revenue data and // execution data Set<Integer> validAllProjects = new HashSet<Integer>(); for (Integer projectId : projectIdList) { List<CollageProjectRevenue> listValues = collageProjectRevenueDao .findByYearIdMonthIdProjectIdCostCentreId(yearId, monthId, projectId, costCentreId); if (!listValues.isEmpty()) { validAllProjects.add(projectId); } } Integer validAllProjectCount = validAllProjects.size(); // logger.debug("validAllProjects :size===>" + // validAllProjects.size()); // Total hour worked by an Employee List<BigDecimal> toatalHours = executionDataDao.findByPersonIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId); BigDecimal toatlTime = toatalHours.get(0); // logger.debug("ToatalHours===>" + toatlTime); // Separate assigned projects from execution data projects Map<Integer, BigDecimal> assignedProjects = new HashMap<Integer, BigDecimal>(); Map<Integer, BigDecimal> unAssignedProjects = new HashMap<Integer, BigDecimal>(); List<Object[]> allProjectTimeList = executionDataDao .findByEmployeeIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId); for (Object[] result : allProjectTimeList) { Integer projectId = (Integer) result[0]; BigDecimal hour = (BigDecimal) result[1]; Integer companyId = (Integer) result[2]; if (validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) { // logger.debug("UnAssignedProjects===>" + // projectId+"::"+hour+"::"+companyId); assignedProjects.put(projectId, hour); } if (!validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) { // logger.debug("assignedProjects===>" + // projectId+"::"+hour+"::"+companyId); unAssignedProjects.put(projectId, hour); } } if (validEmployeeProjectCount == 1 && validAllProjectCount == 1 && validAllProjects.containsAll(validEmployeeProjectIds.keySet()) && unAssignedProjects.isEmpty()) { // logger.debug("validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)"); for (Integer key : assignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); // logger.debug("1034 :validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)===>1"); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, allignedTimeOne, assistedTimeZero, apportionedTimeZero, allignedTimeOne); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else if (!assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) { // logger.debug("1047 : Both in assigned and unassigned projects===>"); if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) { // logger.debug("Worked hours===> >=168"); for (Integer key : assignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = assignedProjects.get(key); EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // logger.debug("1056 :assigned:(Both in assigned and unassigned projects===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = unAssignedProjects.get(key); EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // logger.debug("1073 :unassigned :(Both in assigned and unassigned projects===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else { // logger.debug("Worked hours===> <168"); BigDecimal totalUnAssingnedHours = BigDecimal.ZERO; BigDecimal assingnedHours = BigDecimal.ZERO; for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id BigDecimal timeByProject = unAssignedProjects.get(key); BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN); totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // Assign to assisted count for unAssignedProjects Integer projectId = key; List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); ProjectMaster projectMaster = projectList.get(0); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); // logger.debug("769: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } totalUnAssingnedHours = BigDecimal.ONE.subtract(totalUnAssingnedHours); // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours); for (Map.Entry<Integer, BigDecimal> entry : assignedProjects.entrySet()) { assingnedHours = assingnedHours.add(entry.getValue()); } // logger.debug("assingnedHours===> "+assingnedHours); for (Integer key : assignedProjects.keySet()) { Integer projectId = key; BigDecimal timeByProject = assignedProjects.get(key); // logger.debug("1119 :projectId : timeByProject===> "+projectId+" : "+timeByProject); EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); BigDecimal averageWorkedHours = timeByProject.divide(assingnedHours, 2, RoundingMode.HALF_EVEN); // logger.debug("1121 :assingnedHours : totalUnAssingnedHours===> "+assingnedHours+" : "+totalUnAssingnedHours); BigDecimal actualWorkedHours = averageWorkedHours.multiply(totalUnAssingnedHours); actualWorkedHours = actualWorkedHours.setScale(2, RoundingMode.CEILING); // logger.debug("1124 :averageWorkedHours : actualWorkedHours===> "+averageWorkedHours+" : "+actualWorkedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, actualWorkedHours, assistedTimeZero, apportionedTimeZero, actualWorkedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } } else if (assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) { // logger.debug("In unassigned projects only===>"); if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) { // logger.debug("Worked hours===> >=168"); for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = unAssignedProjects.get(key); EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // logger.debug("1148 :In unassigned projects only===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else { // logger.debug("Worked hours===> <168"); BigDecimal totalUnAssingnedHours = BigDecimal.ZERO; BigDecimal assingnedHours = BigDecimal.ZERO; for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id BigDecimal timeByProject = unAssignedProjects.get(key); BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours); // Assign to assisted count for unAssignedProjects Integer projectId = key; List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); ProjectMaster projectMaster = projectList.get(0); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); // logger.debug("1173: Assisted hours (In unassigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } logger.debug("1209 totalUnAssingnedHours===> " + totalUnAssingnedHours); BigDecimal remainProportion = BigDecimal.ONE.subtract(totalUnAssingnedHours); logger.debug("remainProportion===> " + remainProportion); getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList, employee, month, year, costCentre, countType, remainProportion, unAssignedProjects, countTypeId, employeePcTagsTeamStructMap); } } } // logger.debug("<====getSingleProjectDetail END====>"); }
From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java
/** * @param yearId/*from w w w . j av a 2 s . com*/ * @param monthId * @param costCentreId * @param empcntClientProjectDataList * @param employee * @param month * @param year * @param costCentre * @param countType * @param allignedTimeOne * @param assistedTimeOne * @param apportionedTimeOne * @param totalTimeOne */ private void getZeroProjectsDetail(Integer yearId, Integer monthId, String costCentreId, List<EmpcntClientProjectData> empOpenCntClientProjectDataList, List<EmpcntClientProjectData> empCloseCntClientProjectDataList, EmployeeMaster employee, TabMonth month, TabYear year, CostCentre costCentre, CountClassification countType, BigDecimal allignedTimeZero, BigDecimal assistedTimeZero, BigDecimal apportionedTimeOne, BigDecimal totalTimeOne, Integer countTypeId, Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) { logger.debug("<====getZeroProjectsDetail START====>"); Integer employeeId = employee.getEmployeeId(); BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS); logger.debug("getZeroProjectsDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::" + costCentreId + "::" + deviderHour); // Get list of project from execution data for that employee List<Integer> projectIdList = executionDataDao.findByPersonYearMonthCostCentre(employeeId, yearId, monthId, costCentreId); // logger.debug("execution data projects===>" + projectIdList.size()); if (projectIdList.isEmpty()) { BigDecimal remainProportion = BigDecimal.ONE; Map<Integer, BigDecimal> assignedProjectsHour = new HashMap<Integer, BigDecimal>(); getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList, employee, month, year, costCentre, countType, remainProportion, assignedProjectsHour, countTypeId, employeePcTagsTeamStructMap); } else { // logger.debug("Else Project details present in execution data ===>"); // Get valid projects list=>project is both revenue data and // execution data Set<Integer> validAllProjects = new HashSet<Integer>(); for (Integer projectId : projectIdList) { List<CollageProjectRevenue> listValues = collageProjectRevenueDao .findByYearIdMonthIdProjectIdCostCentreId(yearId, monthId, projectId, costCentreId); if (!listValues.isEmpty()) { validAllProjects.add(projectId); } } // logger.debug("validAllProjects :size===>" + // validAllProjects.size()); // Total hour worked by an Employee List<BigDecimal> toatalHours = executionDataDao.findByPersonIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId); BigDecimal toatlTime = toatalHours.get(0); // logger.debug("ToatalHours===>" + toatlTime); // Separate assigned projects from execution data projects Map<Integer, BigDecimal> assignedProjectsHour = new HashMap<Integer, BigDecimal>(); Map<Integer, Integer> assignedProjectsCompany = new HashMap<Integer, Integer>(); List<Object[]> allProjectTimeList = executionDataDao .findByEmployeeIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId); for (Object[] result : allProjectTimeList) { Integer projectId = (Integer) result[0]; BigDecimal hour = (BigDecimal) result[1]; Integer companyId = (Integer) result[2]; if (validAllProjects.contains(projectId)) { // logger.debug("UnAssignedProjects===>" + // projectId+"::"+hour+"::"+companyId); assignedProjectsHour.put(projectId, hour); assignedProjectsCompany.put(projectId, companyId); } } /* * Do the calculation as per time spent on projects and put it to * assisted count */ // logger.debug("validEmployeeProjectCount!=validAllProjectCount :(Both in assigned and unassigned projects)"); if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) { // logger.debug("Worked hours===> >=168"); for (Integer key : assignedProjectsCompany.keySet()) { // Get time spent on each project by employee id Integer projectId = key; Integer companyIdByProject = assignedProjectsCompany.get(key); ProjectMaster projectMaster = new ProjectMaster(); projectMaster.setProjectId(projectId); CompanyMaster companyMaster = new CompanyMaster(); companyMaster.setCompanyId(companyIdByProject); // logger.debug("1254 :Both in assigned and unassigned projects======>"+totalTimeOne); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero, assistedTimeZero, apportionedTimeOne, totalTimeOne); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else { // logger.debug("Worked hours===> <168"); BigDecimal revenueProportion = BigDecimal.ZERO; for (Integer key : assignedProjectsHour.keySet()) { Integer projectId = key; // logger.debug("projectId===> "+projectId); BigDecimal timeByProject = assignedProjectsHour.get(key); Integer companyIdByProject = assignedProjectsCompany.get(key); ProjectMaster projectMaster = new ProjectMaster(); projectMaster.setProjectId(projectId); CompanyMaster companyMaster = new CompanyMaster(); companyMaster.setCompanyId(companyIdByProject); // logger.debug("timeByProject===> "+timeByProject); BigDecimal assistedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN); assistedHours = assistedHours.setScale(2, RoundingMode.CEILING); // logger.debug("assignedProjectsHour===> "+assingnedHours); revenueProportion = revenueProportion.add(assistedHours); logger.debug("1338 :======>" + revenueProportion); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero, assistedHours, allignedTimeZero, assistedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } /* * Revenue count put it to apportioned count */ // logger.debug("revenueProportion===> "+revenueProportion); if (revenueProportion.compareTo(BigDecimal.ONE) == -1) { BigDecimal remainProportion = BigDecimal.ONE.subtract(revenueProportion); logger.debug("remainProportion===> " + remainProportion); getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList, employee, month, year, costCentre, countType, remainProportion, assignedProjectsHour, countTypeId, employeePcTagsTeamStructMap); } } } // logger.debug("<====getZeroProjectDetail END====>"); }