List of usage examples for java.lang Long doubleValue
public double doubleValue()
From source file:org.silverpeas.web.upload.AjaxFileUploadServlet.java
/** * Return the current status of the upload. * * @param session the HttpSession./*from w w w . java2s. com*/ * @param response where the status is to be written. * @throws IOException */ private void doStatus(HttpSession session, HttpServletResponse response) throws IOException { boolean isSavingUploadedFiles = isSavingUploadedFile(session); Long bytesProcessed = null; Long totalSize = null; FileUploadListener.FileUploadStats fileUploadStats = (FileUploadListener.FileUploadStats) session .getAttribute(FILE_UPLOAD_STATS); if (fileUploadStats != null) { bytesProcessed = fileUploadStats.getBytesRead(); totalSize = fileUploadStats.getTotalSize(); } // Make sure the status response is not cached by the browser response.addHeader("Expires", "0"); response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.addHeader("Pragma", "no-cache"); String fatalError = (String) session.getAttribute(UPLOAD_FATAL_ERROR); if (StringUtil.isDefined(fatalError)) { List<String> paths = (List<String>) session.getAttribute(FILE_UPLOAD_PATHS); String uploadedFilePaths = getUploadedFilePaths(paths); response.getWriter().println("<b>Upload uncomplete.</b>"); response.getWriter().println("<script type='text/javascript'>window.parent.stop('" + fatalError + "', " + uploadedFilePaths + "); stop('" + fatalError + "', " + uploadedFilePaths + ");</script>"); return; } if (bytesProcessed != null) { long percentComplete = (long) Math .floor((bytesProcessed.doubleValue() / totalSize.doubleValue()) * 100.0); response.getWriter().println("<b>Upload Status:</b><br>"); if (!bytesProcessed.equals(totalSize)) { response.getWriter().println("<div class=\"prog-border\"><div class=\"prog-bar\" style=\"width: " + percentComplete + "%;\"></div></div>"); } else { response.getWriter() .println("<div class=\"prog-border\"><div class=\"prog-bar\" style=\"width: 100%;" + "\"></div></div>"); if (!isSavingUploadedFiles) { List<String> paths = (List<String>) session.getAttribute(FILE_UPLOAD_PATHS); String uploadedFilePaths = getUploadedFilePaths(paths); String errors = (String) session.getAttribute(UPLOAD_ERRORS); if (StringUtil.isDefined(errors)) { response.getWriter().println("<b>Upload complete with error(s).</b><br>"); } else { response.getWriter().println("<b>Upload complete.</b><br>"); errors = ""; } response.getWriter() .println("<script type='text/javascript'>window.parent.stop('" + errors + "', " + uploadedFilePaths + "); stop('" + errors + "', " + uploadedFilePaths + ");</script>"); } } } }
From source file:com.mgmtp.perfload.perfalyzer.binning.MeasuringResponseTimesBinningStrategy.java
@Override public void binData(final Scanner scanner, final WritableByteChannel destChannel) throws IOException { while (scanner.hasNextLine()) { tokenizer.reset(scanner.nextLine()); String[] tokens = tokenizer.getTokenArray(); long timestampMillis = Long.parseLong(tokens[0]); Long responseTime = Long.valueOf(tokens[2]); String type = tokens[MEASURING_NORMALIZED_COL_REQUEST_TYPE]; String uriAlias = tokens[MEASURING_NORMALIZED_COL_URI_ALIAS]; String result = tokens[MEASURING_NORMALIZED_COL_RESULT]; String executionId = tokens[MEASURING_NORMALIZED_COL_EXECUTION_ID]; String key = type + "||" + uriAlias; UriMeasurings measurings = measuringsMap.get(key); if (measurings == null) { measurings = new UriMeasurings(); measurings.type = type;/*w ww. ja v a 2s .c om*/ measurings.uriAlias = uriAlias; measuringsMap.put(key, measurings); } if (responseTime > 0) { // response time distribution is calculated by grouping by response time // only positive values allowed on logarithmic axis // response time might by -1 in case of an error MutableInt mutableInt = measurings.responseDistributions.get(responseTime); if (mutableInt == null) { mutableInt = new MutableInt(); measurings.responseDistributions.put(responseTime, mutableInt); } mutableInt.increment(); } // collect all response times for a URI, so quantiles can be calculated later measurings.responseTimes.add(responseTime.doubleValue()); if ("ERROR".equals(result)) { measurings.errorCount.increment(); errorExecutions.add(executionId); } if (!isNullOrEmpty(executionId)) { ExecutionMeasurings execMeasurings = perExecutionResponseTimes.get(executionId); if (execMeasurings == null) { execMeasurings = new ExecutionMeasurings(); execMeasurings.sumResponseTimes = new MutableLong(responseTime); perExecutionResponseTimes.put(executionId, execMeasurings); } else { perExecutionResponseTimes.get(executionId).sumResponseTimes.add(responseTime); } // always update timestamp so we eventually have the last timestamp of the execution execMeasurings.timestampMillis = timestampMillis; } } }
From source file:eu.smartenit.sbox.eca.ReferenceVectorCalculator.java
/** * Calculates the reference vector using simplex method. * /*w w w . j av a 2s .co m*/ * @param S1 The DC traffic manipulation freedom * @param S2 The DC traffic manipulation freedom * @param aList The list of candidate areas * @param sourceAsNumber The number of the source AS * @return Returns an RVector containing the reference vector values. */ private LocalRVector calculateReferenceVector(double[] S1, double[] S2, List<Area> aList, int sourceAsNumber) { List<PointValuePair> solutionList = new ArrayList<PointValuePair>(); for (Area a : aList) { Long x1Lower = a.getD1().getLowerBound(); // Corresponds to alpha1i Long x1Upper = a.getD1().getUpperBound(); // Corresponds to alpha1i+1 Long x2Lower = a.getD2().getLowerBound(); // Corresponds to alpha2i Long x2Upper = a.getD2().getUpperBound(); // Corresponds to alpha2i+1 Segment segment1 = costFunctionMap1.get(x1Lower); // Corresponds to the suitable cf segment for alpha1 Segment segment2 = costFunctionMap2.get(x2Lower); // Corresponds to the suitable cf segment for alpha2 // Function f: f1(x1) + f2(x2) + c //c corresponds to the sum of the constant part of f1 and f2 // Constraints c1: x1 > alpha1i // c2: x1 <= alpha1i+1 // c3: x2 > alpha2j // c4: x2 <= alpha2j+1 // c5: x1 + x2 == X_V[x1] + X_V[x2] // c6: x1 >= X_V[x1] + S1[x1] // c7: x1 <= X_V[x1] + S2[x1] // c8: x2 >= X_V[x2] + S2[x2] // c9: x2 <= X_V[x2] + S1[x2] LinearObjectiveFunction f = new LinearObjectiveFunction( new double[] { segment1.getB(), segment2.getB() }, (segment1.getA() + segment2.getA())); //f1(x1) + f2(x2) Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, x1Lower.doubleValue())); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, x1Upper.doubleValue())); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, x2Lower.doubleValue())); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, x2Upper.doubleValue())); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, X_V[x1] + X_V[x2])); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, X_V[x1] + S1[x1])); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, X_V[x1] + S2[x1])); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, X_V[x2] + S2[x2])); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, X_V[x2] + S1[x2])); try { PointValuePair solution = new SimplexSolver().optimize(f, constraints, GoalType.MINIMIZE, true); solutionList.add(solution); double x = solution.getPoint()[0]; double y = solution.getPoint()[1]; double value = solution.getValue(); logger.info("\n"); logger.info("Area [" + x1Lower + ", " + x1Upper + ", " + x2Lower + ", " + x2Upper + "]"); logger.info("Cost function: " + segment1.getB() + "x1 " + segment2.getB() + "x2 " + " + " + (segment1.getA() + segment2.getA())); logger.info("Reference vector x1=" + x + " x2=" + y + " f1(x1) + f2(x2)=" + value); } catch (NoFeasibleSolutionException e) { logger.info("\n"); logger.info("Area [" + x1Lower + ", " + x1Upper + ", " + x2Lower + ", " + x2Upper + "]"); logger.info("Cost function: " + segment1.getB() + "x1 " + segment2.getB() + "x2 " + " + " + (segment1.getA() + segment2.getA())); logger.error("No feasible solution found: for area " + a); } } PointValuePair minimalSolution = getMinimalSolution(solutionList); LocalRVector referenceVector = constructReferenceVector(minimalSolution, sourceAsNumber); logger.info("Chosen reference vector: " + referenceVector.getVectorValues().get(0).getValue() + " " + referenceVector.getVectorValues().get(1).getValue()); return referenceVector; }
From source file:org.apache.solr.update.processor.AddSchemaFieldsUpdateProcessorFactoryTest.java
public void testParseAndAddMultipleFieldsRoundTrip() throws Exception { IndexSchema schema = h.getCore().getLatestSchema(); final String fieldName1 = "newfield7"; final String fieldName2 = "newfield8"; final String fieldName3 = "newfield9"; final String fieldName4 = "newfield10"; assertNull(schema.getFieldOrNull(fieldName1)); assertNull(schema.getFieldOrNull(fieldName2)); assertNull(schema.getFieldOrNull(fieldName3)); assertNull(schema.getFieldOrNull(fieldName4)); String field1String1 = "-13,258.0"; Float field1Value1 = -13258.0f; String field1String2 = "84,828,800,808.0"; Double field1Value2 = 8.4828800808E10; String field1String3 = "999"; Long field1Value3 = 999L; String field2String1 = "55,123"; Integer field2Value1 = 55123; String field2String2 = "1,234,567,890,123,456,789"; Long field2Value2 = 1234567890123456789L; String field3String1 = "blah-blah"; String field3Value1 = field3String1; String field3String2 = "-5.28E-3"; Double field3Value2 = -5.28E-3; String field4String1 = "1999-04-17 17:42"; DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").withZoneUTC(); DateTime dateTime = dateTimeFormatter.parseDateTime(field4String1); Date field4Value1 = dateTime.toDate(); DateTimeFormatter dateTimeFormatter2 = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss").withZoneUTC(); String field4Value1String = dateTimeFormatter2.print(dateTime) + "Z"; SolrInputDocument d = processAdd("parse-and-add-fields", doc(f("id", "6"), f(fieldName1, field1String1, field1String2, field1String3), f(fieldName2, field2String1, field2String2), f(fieldName3, field3String1, field3String2), f(fieldName4, field4String1))); assertNotNull(d);//from w ww . j a va2 s . c o m schema = h.getCore().getLatestSchema(); assertNotNull(schema.getFieldOrNull(fieldName1)); assertNotNull(schema.getFieldOrNull(fieldName2)); assertNotNull(schema.getFieldOrNull(fieldName3)); assertNotNull(schema.getFieldOrNull(fieldName4)); assertEquals("tdouble", schema.getFieldType(fieldName1).getTypeName()); assertEquals("tlong", schema.getFieldType(fieldName2).getTypeName()); assertEquals("text", schema.getFieldType(fieldName3).getTypeName()); assertEquals("tdate", schema.getFieldType(fieldName4).getTypeName()); assertU(commit()); assertQ(req("id:6"), "//arr[@name='" + fieldName1 + "']/double[.='" + field1Value1.toString() + "']", "//arr[@name='" + fieldName1 + "']/double[.='" + field1Value2.toString() + "']", "//arr[@name='" + fieldName1 + "']/double[.='" + field1Value3.doubleValue() + "']", "//arr[@name='" + fieldName2 + "']/long[.='" + field2Value1.toString() + "']", "//arr[@name='" + fieldName2 + "']/long[.='" + field2Value2.toString() + "']", "//arr[@name='" + fieldName3 + "']/str[.='" + field3String1 + "']", "//arr[@name='" + fieldName3 + "']/str[.='" + field3String2 + "']", "//arr[@name='" + fieldName4 + "']/date[.='" + field4Value1String + "']"); }
From source file:org.hyperic.hq.ui.taglib.display.DateDecorator.java
/** * Decorates a date represented as a long. * //from w w w . jav a2 s. com * @param obj * a long representing the time as a long * @return formatted date */ public String decorate(Object obj) { String tempVal = getName(); Long newDate = null; if (tempVal != null) { try { newDate = Long.valueOf(tempVal); } catch (NumberFormatException nfe) { log.debug("number format exception parsing long for: " + tempVal); return ""; } } else { newDate = (Long) obj; } tempVal = getActive(); if (tempVal != null) { try { int tmpIntActive = Integer.parseInt(tempVal); if (tmpIntActive == 0) { return ""; } } catch (NumberFormatException nfe) { log.debug("invalid property"); } } HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest(); if (newDate != null && newDate.equals(new Long(0))) { String resString; if (this.getIsGroup() != null && this.getIsGroup().booleanValue()) { resString = RequestUtils.message(request, "resource.common.monitor.visibility.config.DIFFERENT"); } else { resString = RequestUtils.message(request, "resource.common.monitor.visibility.config.NONE"); } return resString; } StringBuffer buf = new StringBuffer(512); if (obj == null) { // there may be cases where we have no date set when rendering a // table, so just show n/a (see PR 8443) buf.append(RequestUtils.message(request, bundle, request.getLocale().toString(), DateDecorator.defaultKey)); return buf.toString(); } Boolean b = getIsElapsedTime(); if (null == b) { b = Boolean.FALSE; } int unit = b.booleanValue() ? UnitsConstants.UNIT_DURATION : UnitsConstants.UNIT_DATE; String formatString = RequestUtils.message((HttpServletRequest) getPageContext().getRequest(), Constants.UNIT_FORMAT_PREFIX_KEY + "epoch-millis"); DateFormatter.DateSpecifics dateSpecs; dateSpecs = new DateFormatter.DateSpecifics(); dateSpecs.setDateFormat(new SimpleDateFormat(formatString)); FormattedNumber fmtd = UnitsFormat.format( new UnitNumber(newDate.doubleValue(), unit, UnitsConstants.SCALE_MILLI), getPageContext().getRequest().getLocale(), dateSpecs); buf.append(fmtd.toString()); return buf.toString(); }
From source file:com.gtwm.pb.model.manageData.DataManagement.java
/** * Fetch direct from the database/* w w w . ja v a2 s. c o m*/ */ private ChartDataInfo fetchChartData(ChartInfo chart, Map<BaseField, String> reportFilterValues) throws CantDoThatException, SQLException { Set<ChartAggregateInfo> aggregateFunctions = chart.getAggregateFunctions(); Set<ChartGroupingInfo> groupings = chart.getGroupings(); logger.debug("Chart groupings are " + groupings); List<ChartDataRowInfo> reportSummaryRows; reportSummaryRows = new LinkedList<ChartDataRowInfo>(); Connection conn = null; PreparedStatement statement = null; try { conn = this.dataSource.getConnection(); conn.setAutoCommit(false); // First, cache the set of display values for relation fields Map<ReportFieldInfo, Map<String, String>> displayLookups = new HashMap<ReportFieldInfo, Map<String, String>>(); for (ChartGroupingInfo grouping : groupings) { ReportFieldInfo groupingReportField = grouping.getGroupingReportField(); BaseField baseField = groupingReportField.getBaseField(); if (baseField instanceof RelationField) { String relatedKey = ((RelationField) baseField).getRelatedField().getInternalFieldName(); String relatedDisplay = ((RelationField) baseField).getDisplayField().getInternalFieldName(); String relatedSource = ((RelationField) baseField).getRelatedTable().getInternalTableName(); Map<String, String> displayLookup = getKeyToDisplayMapping(conn, relatedSource, relatedKey, relatedDisplay); displayLookups.put(groupingReportField, displayLookup); } } // Create some maps to store min. and max. values of each // aggregate column // These numbers can be used e.g. to scale values when charting // summary data Map<ChartAggregateInfo, Number> maxAggValues = new HashMap<ChartAggregateInfo, Number>(); Map<ChartAggregateInfo, Number> minAggValues = new HashMap<ChartAggregateInfo, Number>(); Map<ChartAggregateInfo, Number> grandTotals = new HashMap<ChartAggregateInfo, Number>(); // Also a map for working with in the loop Map<ReportFieldInfo, Date> previousDateValues = new HashMap<ReportFieldInfo, Date>(); Calendar calendar = Calendar.getInstance(); // Get database data BaseReportInfo report = chart.getReport(); ReportData.enableOptimisations(conn, report, true); statement = chart.getChartSqlPreparedStatement(conn, reportFilterValues, false); long startTime = System.currentTimeMillis(); ResultSet summaryResults = statement.executeQuery(); while (summaryResults.next()) { ChartDataRowInfo resultRow = new ChartDataRow(); int resultColumn = 0; for (ChartGroupingInfo grouping : groupings) { ReportFieldInfo groupingReportField = grouping.getGroupingReportField(); SummaryGroupingModifier groupingModifier = grouping.getGroupingModifier(); BaseField baseField = groupingReportField.getBaseField(); resultColumn++; String value = ""; DatabaseFieldType dbType = baseField.getDbType(); if (baseField instanceof RelationField) { value = summaryResults.getString(resultColumn); Map<String, String> displayLookup = displayLookups.get(groupingReportField); value = displayLookup.get(value); } else if (dbType.equals(DatabaseFieldType.TIMESTAMP)) { if (groupingModifier != null) { value = summaryResults.getString(resultColumn); } else { Date dbValue = summaryResults.getTimestamp(resultColumn); if (dbValue != null) { if (groupingReportField instanceof ReportCalcFieldInfo) { // See DateFieldDefn constructor for // format // explanation value = ((ReportCalcFieldInfo) groupingReportField).formatDate(dbValue); } else { DateField dateField = (DateField) baseField; value = (dateField.formatDate(dbValue)); if (Integer.valueOf(dateField.getDateResolution()) .equals(Calendar.DAY_OF_MONTH)) { Date previousDbValue = previousDateValues.get(groupingReportField); if (previousDbValue != null) { calendar.setTime(previousDbValue); int previousDayOfYear = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTime(dbValue); int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR); int difference = Math.abs(dayOfYear - previousDayOfYear); if (difference > 1) { value += " (" + (difference - 1) + " day gap)"; } } previousDateValues.put(groupingReportField, dbValue); } } } } } else if (dbType.equals(DatabaseFieldType.FLOAT)) { double floatValue = summaryResults.getDouble(resultColumn); if (baseField instanceof DecimalField) { value = ((DecimalField) baseField).formatFloat(floatValue); } else if (groupingReportField instanceof ReportCalcFieldInfo) { value = ((ReportCalcFieldInfo) groupingReportField).formatFloat(floatValue); } else { value = summaryResults.getString(resultColumn); } } else if (dbType.equals(DatabaseFieldType.BOOLEAN)) { if (summaryResults.getBoolean(resultColumn)) { value = "true"; } else { value = "false"; } } else { value = summaryResults.getString(resultColumn); } resultRow.addGroupingValue(grouping, value); } for (ChartAggregateInfo aggregateFunction : aggregateFunctions) { resultColumn++; DatabaseFieldType dbType = aggregateFunction.getReportField().getBaseField().getDbType(); Double value = null; // deal with aggregate results which are timestamps // rather than doubles if ((!aggregateFunction.getAggregateFunction().equals(AggregateFunction.COUNT)) && (dbType.equals(DatabaseFieldType.TIMESTAMP))) { java.sql.Timestamp timestampValue = summaryResults.getTimestamp(resultColumn); if (timestampValue != null) { Long longValue = timestampValue.getTime(); value = longValue.doubleValue(); } } else { value = summaryResults.getDouble(resultColumn); } if (value != null) { int precision = 1; ReportFieldInfo aggReportField = aggregateFunction.getReportField(); if (aggReportField instanceof ReportCalcFieldInfo) { DatabaseFieldType dbFieldType = ((ReportCalcFieldInfo) aggReportField).getDbType(); if (dbFieldType.equals(DatabaseFieldType.FLOAT)) { precision = ((ReportCalcFieldInfo) aggReportField).getDecimalPrecision(); } } else if (aggReportField.getBaseField() instanceof DecimalField) { precision = ((DecimalField) aggReportField.getBaseField()).getPrecision(); } Number currentGrandTotal = grandTotals.get(aggregateFunction); if (currentGrandTotal == null) { currentGrandTotal = new Double(0); } double currentGrandTotalDbl = currentGrandTotal.doubleValue() + value; grandTotals.put(aggregateFunction, Double.valueOf(currentGrandTotalDbl)); value = MathUtils.round(value, precision); resultRow.addAggregateValue(aggregateFunction, value); Number currentMin = minAggValues.get(aggregateFunction); Number currentMax = maxAggValues.get(aggregateFunction); if (currentMin == null) { minAggValues.put(aggregateFunction, value); } else if (value.doubleValue() < currentMin.doubleValue()) { minAggValues.put(aggregateFunction, value); } if (currentMax == null) { maxAggValues.put(aggregateFunction, value); } else if (value.doubleValue() > currentMax.doubleValue()) { maxAggValues.put(aggregateFunction, value); } } } reportSummaryRows.add(resultRow); } summaryResults.close(); statement.close(); ReportData.enableOptimisations(conn, report, false); float durationSecs = (System.currentTimeMillis() - startTime) / ((float) 1000); if (durationSecs > AppProperties.longSqlTime) { logger.debug("Long SELECT SQL execution time of " + durationSecs + " seconds for summary '" + chart + "', statement = " + statement); } return new ChartData(reportSummaryRows, minAggValues, maxAggValues, grandTotals); } catch (SQLException sqlex) { throw new SQLException( "Error getting report summary data " + chart + ": " + sqlex + ". SQL = " + statement); } finally { if (conn != null) { conn.close(); } } }
From source file:org.hawkular.alerts.api.model.condition.EventCondition.java
private boolean processExpression(String expression, Event value) { if (null == expression || expression.isEmpty() || null == value) { return false; }// w w w . jav a2s .c o m String[] tokens = expression.split(" "); if (tokens.length < 3) { return false; } String eventField = tokens[0]; String operator = tokens[1]; String constant = tokens[2]; for (int i = 3; i < tokens.length; ++i) { constant += " "; constant += tokens[i]; } String sEventValue = null; Long lEventValue = null; String sConstantValue = null; Double dConstantValue = null; if (eventField == null || eventField.isEmpty()) { return false; } if (TENANT_ID.equals(eventField)) { sEventValue = value.getTenantId(); } else if (ID.equals(eventField)) { sEventValue = value.getId(); } else if (CTIME.equals(eventField)) { lEventValue = value.getCtime(); } else if (TEXT.equals(eventField)) { sEventValue = value.getText(); } else if (CATEGORY.equals(eventField)) { sEventValue = value.getCategory(); } else if (eventField.startsWith(TAGS)) { // We get the key from tags.<key> string String key = eventField.substring(5); sEventValue = value.getTags().get(key); } if (sEventValue == null && lEventValue == null) { return false; } if (constant == null) { return false; } int constantLength = constant.length(); if (constant.charAt(0) == '\'' && constant.charAt(constantLength - 1) == '\'') { sConstantValue = constant.substring(1, constantLength - 1); } else if (constant.charAt(0) == '\'' && constant.charAt(constantLength - 1) != '\'') { return false; } else if (constant.charAt(0) != '\'' && constant.charAt(constantLength - 1) == '\'') { return false; } else { dConstantValue = Double.valueOf(constant); } if (EQ.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return sEventValue.equals(sConstantValue); } if (lEventValue != null && dConstantValue != null) { return lEventValue.longValue() == dConstantValue.doubleValue(); } return false; } else if (NON_EQ.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return !sEventValue.equals(sConstantValue); } if (lEventValue != null && dConstantValue != null) { return lEventValue.longValue() != dConstantValue.doubleValue(); } return false; } else if (STARTS.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return sEventValue.startsWith(sConstantValue); } return false; } else if (ENDS.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return sEventValue.endsWith(sConstantValue); } return false; } else if (CONTAINS.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return sEventValue.contains(sConstantValue); } return false; } else if (MATCHES.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return sEventValue.matches(sConstantValue); } return false; } else if (GT.equals(operator)) { Double dEventValue = lEventValue != null ? lEventValue.doubleValue() : null; dEventValue = sEventValue != null ? Double.valueOf(sEventValue) : dEventValue; if (dEventValue != null && dConstantValue != null) { return dEventValue > dConstantValue; } return false; } else if (GTE.equals(operator)) { Double dEventValue = lEventValue != null ? lEventValue.doubleValue() : null; dEventValue = sEventValue != null ? Double.valueOf(sEventValue) : dEventValue; if (dEventValue != null && dConstantValue != null) { return dEventValue >= dConstantValue; } return false; } else if (LT.equals(operator)) { Double dEventValue = lEventValue != null ? lEventValue.doubleValue() : null; dEventValue = sEventValue != null ? Double.valueOf(sEventValue) : dEventValue; if (dEventValue != null && dConstantValue != null) { return dEventValue < dConstantValue; } return false; } else if (LTE.equals(operator)) { Double dEventValue = lEventValue != null ? lEventValue.doubleValue() : null; dEventValue = sEventValue != null ? Double.valueOf(sEventValue) : dEventValue; if (dEventValue != null && dConstantValue != null) { return dEventValue <= dConstantValue; } return false; } return false; }
From source file:org.apache.ranger.service.XResourceService.java
public HashMap<String, Object> fetchGroupAccessMap(Long groupId, int permType, String path, int assetType, Long assetId, int isRecursive, List<Integer> resourceTypeList) { boolean isAccess = false; boolean isRecursivlyAllowed = false; HashMap<String, Object> accessMap = new HashMap<String, Object>(); List<XXResource> xXResourceList = new ArrayList<XXResource>(); if (assetType == AppConstants.ASSET_HDFS) { xXResourceList = rangerDaoManager.getXXResource().findByAssetId(assetId); } else {// ww w .j ava2 s. c om xXResourceList = rangerDaoManager.getXXResource().findByAssetIdAndResourceTypes(assetId, resourceTypeList); } String expandedName = xaBizUtil.replaceMetaChars(path); for (XXResource xResource : xXResourceList) { String resource = xResource.getName(); if (resource == null || resource.isEmpty()) { logger.debug("Resource name not found for resourceId : " + xResource.getId()); throw restErrorUtil.createRESTException("Resource name not found.", MessageEnums.DATA_NOT_FOUND); } String[] dbResourceNameList = resource.split(","); boolean matchFound = false; for (String dbResourceName : dbResourceNameList) { String[] requestResNameList = expandedName.split(","); for (String resourceName : requestResNameList) { if (xaBizUtil.comparePathsForExactMatch(resourceName, dbResourceName)) { matchFound = true; } else { // resource name has a file extension then don't // append "/*" // "/*" is required for directory matching if (xResource.getIsRecursive() == AppConstants.BOOL_TRUE) { matchFound = xaBizUtil.isRecursiveWildCardMatch(resourceName, dbResourceName); } else { matchFound = xaBizUtil.nonRecursiveWildCardMatch(resourceName, dbResourceName); } } if (matchFound) { break; } } if (matchFound) { break; } } if (matchFound) { // get the perms for this resource List<XXPermMap> permMapList = rangerDaoManager.getXXPermMap().findByResourceId(xResource.getId()); for (XXPermMap permMap : permMapList) { if (permMap.getPermType() == permType) { if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP && permMap.getGroupId().doubleValue() == groupId.doubleValue()) { isAccess = true; isRecursivlyAllowed = (xResource.getIsRecursive() == AppConstants.BOOL_TRUE); } } } } } accessMap.put("isAccess", isAccess); accessMap.put("isRecursive", isRecursivlyAllowed); return accessMap; }
From source file:org.rhq.enterprise.gui.legacy.taglib.display.DateDecorator.java
/** * Decorates a date represented as a long. * * @param obj a long representing the time as a long * * @return formatted date//ww w . j a v a 2s . com */ @Override public String decorate(Object obj) { Long newDate = null; if (getName() != null) { String tmpName = getName(); try { tmpName = (String) evalAttr("name", this.getName(), String.class); newDate = new Long(Long.parseLong(tmpName)); } catch (NumberFormatException nfe) { log.debug("number format exception parsing long for: " + tmpName); return ""; } catch (NullAttributeException ne) { log.debug("bean " + this.getName() + " not found"); return ""; } catch (JspException je) { log.debug("can't evaluate name [" + this.getName() + "]: ", je); return ""; } } else { newDate = (Long) obj; } if (getActive() != null) { try { String tmpActive = (String) evalAttr("active", this.getActive(), String.class); int tmpIntActive = Integer.parseInt(tmpActive); if (tmpIntActive == 0) { return ""; } } catch (NumberFormatException nfe) { log.debug("invalid property"); } catch (NullAttributeException ne) { log.debug("bean " + this.getActive() + " not found"); } catch (JspException je) { log.debug("can't evaluate name [" + this.getActive() + "]: ", je); } } if (isGroupEl != null) { try { Boolean tmp = (Boolean) evalAttr("isGroupEl", isGroupEl, Boolean.class); if (tmp != null) { isGroup = tmp; } } catch (NullAttributeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JspException e) { // TODO Auto-generated catch block e.printStackTrace(); } } HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest(); if ((newDate != null) && newDate.equals(new Long(0))) { String resString; if ((this.getIsGroup() != null) && isGroup.booleanValue()) { resString = RequestUtils.message(request, "resource.common.monitor.visibility.config.DIFFERENT"); } else { resString = RequestUtils.message(request, "resource.common.monitor.visibility.config.NONE"); } return resString; } StringBuffer buf = new StringBuffer(512); if (obj == null) { // there may be cases where we have no date set when rendering a // table, so just show n/a (see PR 8443) // infact let it be overridable what we show String resourceKey = getResourceKeyForNull(); if ((resourceKey == null) || "".equals(resourceKey)) { resourceKey = DateDecorator.defaultKey; } buf.append(RequestUtils.message(request, bundle, request.getLocale().toString(), resourceKey)); return buf.toString(); } Boolean b = getIsElapsedTime(); if (null == b) { b = Boolean.FALSE; } UnitsConstants unit = b.booleanValue() ? UnitsConstants.UNIT_DURATION : UnitsConstants.UNIT_DATE; String formatString; if ((format == null) || "".equals(format)) // old case with implicit format string { formatString = RequestUtils.message((HttpServletRequest) getPageContext().getRequest(), Constants.UNIT_FORMAT_PREFIX_KEY + "epoch-millis"); } else { formatString = format; } DateFormatter.DateSpecifics dateSpecs; dateSpecs = new DateFormatter.DateSpecifics(); dateSpecs.setDateFormat(new SimpleDateFormat(formatString)); FormattedNumber fmtd = UnitsFormat.format( new UnitNumber(newDate.doubleValue(), unit, ScaleConstants.SCALE_MILLI), getPageContext().getRequest().getLocale(), dateSpecs); buf.append(fmtd.toString()); return buf.toString(); }
From source file:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java
private boolean generateImageThumb(StudyFile file) { String fileLocation = file.getFileSystemLocation(); if (fileLocation == null || fileLocation.trim().equals("")) { return false; }/*from ww w . j a v a 2 s. co m*/ String thumbFileLocation = fileLocation + ".thumb"; // see if the thumb is already generated and saved: if (new File(thumbFileLocation).exists()) { return true; } // let's attempt to generate the thumb: // the default size of the thumbnail is 64 pixels horizontally. // The number 64 was picked arbitrarily; if a different size is // desired, it can be configured via the dvn.image.thumbnail.size // JVM option. Long thumbSize = Long.valueOf(64); String thumbSizeOption = System.getProperty("dvn.image.thumbnail.size"); if (thumbSizeOption != null) { Long thumbSizeOptionValue = null; try { thumbSizeOptionValue = new Long(thumbSizeOption); } catch (NumberFormatException nfe) { // if the supplied option value is invalid/unparseable, we // ignore it and fall back to the default value. } if (thumbSizeOptionValue != null && thumbSizeOptionValue.longValue() > 0) { thumbSize = thumbSizeOptionValue; } } // it is also possible to configure the thumbnail size for a // specific dataverse: VDC vdc = file.getStudy().getOwner(); if (vdc != null) { thumbSizeOption = System.getProperty("dvn.image.thumbnail.size." + vdc.getAlias()); if (thumbSizeOption != null) { Long thumbSizeOptionValue = null; try { thumbSizeOptionValue = new Long(thumbSizeOption); } catch (NumberFormatException nfe) { // if the supplied option value is invalid/unparseable, we // ignore it and fall back to the default value. } if (thumbSizeOptionValue != null && thumbSizeOptionValue.longValue() > 0) { thumbSize = thumbSizeOptionValue; } } } // This is the default location of the "convert" executable from the // ImageMagick package. If it's installed in a different locaiton, // it can be configured via the dvn.image.convert.exec JVM option. String imageMagickConvertExec = "/usr/bin/convert"; String imageMagickConvertExecOption = System.getProperty("dvn.image.convrt.exec"); if (imageMagickConvertExecOption != null) { if (!imageMagickConvertExecOption.trim().equals("")) { imageMagickConvertExec = imageMagickConvertExecOption.trim(); } } if (new File(imageMagickConvertExec).exists()) { String sizeOption = " -size " + thumbSize + "x" + thumbSize + " "; String ImageMagickCommandLine = imageMagickConvertExec + sizeOption + fileLocation + " -resize " + thumbSize + " -flatten png:" + thumbFileLocation; int exitValue = 1; try { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(ImageMagickCommandLine); exitValue = process.waitFor(); } catch (Exception e) { exitValue = 1; } if (exitValue == 0) { return true; } } // For whatever reason, creating the thumbnail with ImageMagick // has failed. // Let's try again, this time with Java's standard Image // library: try { BufferedImage fullSizeImage = ImageIO.read(new File(fileLocation)); if (fullSizeImage == null) { return false; } double scaleFactor = (thumbSize.doubleValue()) / (double) fullSizeImage.getWidth(null); int thumbHeight = (int) (fullSizeImage.getHeight(null) * scaleFactor); // We are willing to spend a few extra CPU cycles to generate // better-looking thumbnails, hence the SCALE_SMOOTH flag. // SCALE_FAST would trade quality for speed. java.awt.Image thumbImage = fullSizeImage.getScaledInstance(thumbSize.intValue(), thumbHeight, java.awt.Image.SCALE_SMOOTH); ImageWriter writer = null; Iterator iter = ImageIO.getImageWritersByFormatName("png"); if (iter.hasNext()) { writer = (ImageWriter) iter.next(); } else { return false; } BufferedImage lowRes = new BufferedImage(thumbSize.intValue(), thumbHeight, BufferedImage.TYPE_INT_RGB); lowRes.getGraphics().drawImage(thumbImage, 0, 0, null); ImageOutputStream ios = ImageIO.createImageOutputStream(new File(thumbFileLocation)); writer.setOutput(ios); // finally, save thumbnail image: writer.write(lowRes); writer.dispose(); ios.close(); thumbImage.flush(); fullSizeImage.flush(); lowRes.flush(); return true; } catch (Exception e) { // something went wrong, returning "false": dbgLog.info("ImageIO: caught an exception while trying to generate a thumbnail for " + fileLocation); return false; } }