List of usage examples for java.lang Float valueOf
@HotSpotIntrinsicCandidate public static Float valueOf(float f)
From source file:com.netsteadfast.greenstep.bsc.service.logic.impl.ImportDataLogicServiceImpl.java
@ServiceMethodAuthority(type = { ServiceMethodType.INSERT, ServiceMethodType.UPDATE }) @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { RuntimeException.class, IOException.class, Exception.class }) @Override/*from w w w .j a v a2 s . c o m*/ public DefaultResult<Boolean> importPerspectivesCsv(String uploadOid) throws ServiceException, Exception { List<Map<String, String>> csvResults = UploadSupportUtils.getTransformSegmentData(uploadOid, "TRAN002"); if (csvResults.size() < 1) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_NO_EXIST)); } boolean success = false; DefaultResult<Boolean> result = new DefaultResult<Boolean>(); StringBuilder msg = new StringBuilder(); Map<String, Object> paramMap = new HashMap<String, Object>(); for (int i = 0; i < csvResults.size(); i++) { int row = i + 1; Map<String, String> data = csvResults.get(i); String perId = data.get("PER_ID"); String visId = data.get("VIS_ID"); String name = data.get("NAME"); String weight = data.get("WEIGHT"); String target = data.get("TARGET"); String min = data.get("MIN"); String description = data.get("DESCRIPTION"); if (super.isBlank(perId)) { msg.append("row: " + row + " perspective-id is blank." + Constants.HTML_BR); continue; } if (super.isBlank(visId)) { msg.append("row: " + row + " vision-id is blank." + Constants.HTML_BR); continue; } if (super.isBlank(name)) { msg.append("row: " + row + " name is blank." + Constants.HTML_BR); continue; } if (super.isBlank(weight)) { msg.append("row: " + row + " weight is blank." + Constants.HTML_BR); continue; } if (super.isBlank(target)) { msg.append("row: " + row + " target is blank." + Constants.HTML_BR); continue; } if (super.isBlank(min)) { msg.append("row: " + row + " min is blank." + Constants.HTML_BR); continue; } if (!NumberUtils.isNumber(weight)) { msg.append("row: " + row + " weight is not number." + Constants.HTML_BR); continue; } if (!NumberUtils.isNumber(target)) { msg.append("row: " + row + " target is not number." + Constants.HTML_BR); continue; } if (!NumberUtils.isNumber(min)) { msg.append("row: " + row + " min is not number." + Constants.HTML_BR); continue; } paramMap.clear(); paramMap.put("visId", visId); if (this.visionService.countByParams(paramMap) < 1) { throw new ServiceException("row: " + row + " vision is not found " + visId); } DefaultResult<VisionVO> visionResult = this.visionService.findForSimpleByVisId(visId); if (visionResult.getValue() == null) { throw new ServiceException(visionResult.getSystemMessage().getValue()); } PerspectiveVO perspective = new PerspectiveVO(); perspective.setPerId(perId); perspective.setVisId(visId); perspective.setName(name); perspective.setWeight(new BigDecimal(weight)); perspective.setTarget(Float.valueOf(target)); perspective.setMin(Float.valueOf(min)); perspective.setDescription(description); paramMap.clear(); paramMap.put("perId", perId); if (this.perspectiveService.countByParams(paramMap) > 0) { // update DefaultResult<PerspectiveVO> oldResult = this.perspectiveService.findByUK(perspective); perspective.setOid(oldResult.getValue().getOid()); this.perspectiveLogicService.update(perspective, visionResult.getValue().getOid()); } else { // insert this.perspectiveLogicService.create(perspective, visionResult.getValue().getOid()); } success = true; } if (msg.length() > 0) { result.setSystemMessage(new SystemMessage(msg.toString())); } else { result.setSystemMessage(new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.UPDATE_SUCCESS))); } result.setValue(success); return result; }
From source file:com.golemgame.properties.fengGUI.FunctionTab.java
protected void buildGUI() { Container tabFrame = super.getTab(); tabFrame.setLayoutManager(new BorderLayout()); pane = new KnottedFunctionPane(); //Add an internal frame with controls for choosing a function Container controlFrame = FengGUI.createContainer(tabFrame); controlFrame.setLayoutData(BorderLayoutData.NORTH); controlFrame.setLayoutManager(new BorderLayout()); Container controlsNorth = FengGUI.createContainer(controlFrame); controlsNorth.setLayoutData(BorderLayoutData.NORTH); controlsNorth.setLayoutManager(new RowLayout(false)); dropDown = FengGUI.<PropertyStore>createComboBox(controlsNorth); dropDown.setLayoutData(BorderLayoutData.NORTH); dropDown.getAppearance().setPadding(new Spacing(0, 5)); Container nameContainer = FengGUI.createContainer(controlsNorth); nameContainer.setLayoutManager(new BorderLayout()); Label nameLabel = FengGUI.createLabel(nameContainer, StringConstants.get("PROPERTIES.FUNCTIONS.NAME", "Function Name ")); nameLabel.setLayoutData(BorderLayoutData.WEST); functionName = FengGUI.createTextEditor(nameContainer); functionName.setMinSize(300, 10);/*from ww w.java2 s . c o m*/ functionName.setLayoutData(BorderLayoutData.CENTER); controlFrame.layout(); dropDown.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent selectionChangedEvent) { if (selectionChangedEvent.isSelected()) { IToggable<PropertyStore> selected = dropDown.getSelectedItem(); if (selected == slopeItem) { pane.setEnabled(false); interpreter.setFunctionType(FunctionType.Differentiate); functionName.setText(StringConstants.get("FUNCTIONS.SLOPE", "(Slope)")); } else if (selected == areaItem) {//disabled pane.setEnabled(false); interpreter.setFunctionType(FunctionType.AntiDifferentiate); functionName.setText(StringConstants.get("FUNCTIONS.AREA", "(Area)")); } else if (selected != null && selected.getValue() != null) { pane.setEnabled(true); interpreter.setFunctionType(FunctionType.Function); loadFrom(selected.getValue().deepCopy()); /*FunctionSettingsInterpreter settings = new FunctionSettingsInterpreter(new PropertyStore()); settings.setFunction(selected.getValue()); setFunction(settings);*/ } } } }); controlFrame.updateMinSize(); controlFrame.pack(); Container functionContainer = FengGUI.createContainer(tabFrame); functionContainer.setLayoutData(BorderLayoutData.CENTER); functionContainer.setLayoutManager(new BorderLayout()); // pane.setMinSize(20, 20); functionContainer.addWidget(pane); pane.setLayoutData(BorderLayoutData.CENTER); // pane.getAppearance().setBorder(new Spacing(5,5)); horizontal = new ScalingRuler(true, pane); horizontal.setLayoutData(BorderLayoutData.SOUTH); functionContainer.addWidget(horizontal); Container eastContainer = FengGUI.createContainer(functionContainer); eastContainer.setLayoutManager(new BorderLayout()); eastContainer.setLayoutData(BorderLayoutData.EAST); vertical = new ScalingRuler(false, pane); vertical.setLayoutData(BorderLayoutData.CENTER); eastContainer.addWidget(vertical); horizontal.getMinSize().setHeight(15); horizontal.setSizeToMinSize(); vertical.getMinSize().setWidth(horizontal.getHeight()); Spacer spacer = new Spacer(1, horizontal.getHeight()); eastContainer.addWidget(spacer); spacer.setLayoutData(BorderLayoutData.SOUTH); Container south = FengGUI.createContainer(getTab()); //Add controls at the bottom south.setLayoutData(BorderLayoutData.SOUTH); south.setLayoutManager(new RowLayout(false)); periodContainer = FengGUI.createContainer(south); periodContainer.setLayoutManager(new RowLayout()); FengGUI.createLabel(periodContainer, "Length(s):"); time = FengGUI.createTextEditor(periodContainer); // FengGUI.createLabel(settingsContainer,"Power (w):"); power = FengGUI.createTextEditor();//dont add power right now. periodicity = FengGUI.createCheckBox(periodContainer, "Periodic:"); final Container saveContainer = FengGUI.createContainer(south); saveContainer.setLayoutManager(new BorderLayout()); Container saveButtonContainer = FengGUI.createContainer(saveContainer); saveButtonContainer.setLayoutData(BorderLayoutData.EAST); saveButtonContainer.setLayoutManager(new RowLayout()); Button saveButton = FengGUI.createButton(saveButtonContainer); saveButton.setText("Save Function"); saveButton.addButtonPressedListener(new IButtonPressedListener() { @SuppressWarnings("unchecked") public void buttonPressed(ButtonPressedEvent e) { PropertyStore newFunction = new PropertyStore(); set(newFunction); PropertyStore effectStore = StateManager.getMachineSpace().getFunctionRepository().getStore(); //capture the current settings, then add them to the main machine repository (overwriting any existing setting of the same name). final PropertyState beforePropertyState = new SimplePropertyState(effectStore, FunctionSettingsRepositoryInterpreter.FUNCTIONS); StateManager.getMachineSpace().getFunctionRepository().addFunction(newFunction); final PropertyState afterPropertyState = new SimplePropertyState(effectStore, FunctionSettingsRepositoryInterpreter.FUNCTIONS); Action<?> action = new Action() { @Override public String getDescription() { return "Save Function"; } @Override public Type getType() { return null; } @Override public boolean doAction() { afterPropertyState.restore(); afterPropertyState.refresh(); return true; } @Override public boolean undoAction() { beforePropertyState.restore(); beforePropertyState.refresh(); return true; } }; action.setDependencySet(getPropertyStoreAdjuster().getDependencySet()); UndoManager.getInstance().addAction(action); buildFunctions(); dropDown.getLabel().setText(newFunction.getString(FunctionSettingsInterpreter.FUNCTION_NAME)); loadFrom(newFunction.deepCopy()); } }); currentKnotContainer = FengGUI.createContainer(saveContainer); currentKnotContainer.setVisible(false); currentKnotContainer.setLayoutManager(new RowLayout(true)); FengGUI.createLabel(currentKnotContainer, "Vertex Position: ").setExpandable(false); FengGUI.createLabel(currentKnotContainer, "X").setExpandable(false); currentX = FengGUI.createTextEditor(currentKnotContainer); FengGUI.createLabel(currentKnotContainer, "Y").setExpandable(false); currentY = FengGUI.createTextEditor(currentKnotContainer); currentY.addTextChangedListener(new ITextChangedListener() { public void textChanged(TextChangedEvent textChangedEvent) { try { float pos; float scaleY = (float) pane.getTransformFunction().getScaleY(); if (scaleY != 0f && !Float.isInfinite(scaleY) && !Float.isNaN(scaleY)) { pos = (Float.valueOf((currentY.getText())) - (float) pane.getTransformFunction().getTranslateY()) * (float) pane.getTransformFunction().getScaleY(); } else { return; //pos = (float) pane.getTransformFunction().getTranslateY(); } Knot cur = pane.getCurrent(); if (cur != null) { if (cur.getTranslation().y != pos) { cur.getTranslation().y = pos; pane.updateKnots(); } } } catch (NumberFormatException e) { } } }); currentX.addTextChangedListener(new ITextChangedListener() { public void textChanged(TextChangedEvent textChangedEvent) { try { float pos; float scaleX = (float) pane.getTransformFunction().getScaleX(); if (scaleX != 0f && !Float.isInfinite(scaleX) && !Float.isNaN(scaleX)) { pos = (Float.valueOf((currentX.getText())) - (float) pane.getTransformFunction().getTranslateX()) * (float) pane.getTransformFunction().getScaleX(); } else { return; } Knot cur = pane.getCurrent(); if (cur != null) { if (cur.getTranslation().x != pos) { cur.getTranslation().x = pos; pane.updateKnots(); } } } catch (NumberFormatException e) { } } }); pane.registerCurrentKnotListener(new CurrentKnotListener() { public void currentKnotChanged(Knot current) { if (current == null) { currentKnotContainer.setVisible(false); } else { currentKnotContainer.setVisible(true); float scaleX = (float) pane.getTransformFunction().getScaleX(); if (scaleX != 0f && !Float.isInfinite(scaleX) && !Float.isNaN(scaleX)) scaleX = 1f / scaleX; else scaleX = 0f; float scaleY = (float) pane.getTransformFunction().getScaleY(); if (scaleY != 0f && !Float.isInfinite(scaleY) && !Float.isNaN(scaleY)) scaleY = 1f / scaleY; else scaleY = 0f; currentX.setText(String.valueOf( current.getTranslation().x * scaleX + pane.getTransformFunction().getTranslateX())); currentY.setText(String.valueOf( current.getTranslation().y * scaleY + pane.getTransformFunction().getTranslateY())); saveContainer.layout(); } } }); functionContainer.pack(); tabFrame.pack(); }
From source file:com.cloud.api.dispatch.ParamProcessWorker.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private void setFieldValue(final Field field, final BaseCmd cmdObj, final Object paramObj, final Parameter annotation) throws IllegalArgumentException, ParseException { try {// w ww .j a v a 2 s. co m field.setAccessible(true); final CommandType fieldType = annotation.type(); switch (fieldType) { case BOOLEAN: field.set(cmdObj, Boolean.valueOf(paramObj.toString())); break; case DATE: // This piece of code is for maintaining backward compatibility // and support both the date formats(Bug 9724) if (cmdObj instanceof ListEventsCmd || cmdObj instanceof DeleteEventsCmd || cmdObj instanceof ArchiveEventsCmd || cmdObj instanceof ArchiveAlertsCmd || cmdObj instanceof DeleteAlertsCmd || cmdObj instanceof GetUsageRecordsCmd) { final boolean isObjInNewDateFormat = isObjInNewDateFormat(paramObj.toString()); if (isObjInNewDateFormat) { final DateFormat newFormat = newInputFormat; synchronized (newFormat) { field.set(cmdObj, newFormat.parse(paramObj.toString())); } } else { final DateFormat format = inputFormat; synchronized (format) { Date date = format.parse(paramObj.toString()); if (field.getName().equals("startDate")) { date = messageDate(date, 0, 0, 0); } else if (field.getName().equals("endDate")) { date = messageDate(date, 23, 59, 59); } field.set(cmdObj, date); } } } else { final DateFormat format = inputFormat; synchronized (format) { format.setLenient(false); field.set(cmdObj, format.parse(paramObj.toString())); } } break; case FLOAT: // Assuming that the parameters have been checked for required before now, // we ignore blank or null values and defer to the command to set a default // value for optional parameters ... if (paramObj != null && isNotBlank(paramObj.toString())) { field.set(cmdObj, Float.valueOf(paramObj.toString())); } break; case DOUBLE: // Assuming that the parameters have been checked for required before now, // we ignore blank or null values and defer to the command to set a default // value for optional parameters ... if (paramObj != null && isNotBlank(paramObj.toString())) { field.set(cmdObj, Double.valueOf(paramObj.toString())); } break; case INTEGER: // Assuming that the parameters have been checked for required before now, // we ignore blank or null values and defer to the command to set a default // value for optional parameters ... if (paramObj != null && isNotBlank(paramObj.toString())) { field.set(cmdObj, Integer.valueOf(paramObj.toString())); } break; case LIST: final List listParam = new ArrayList(); final StringTokenizer st = new StringTokenizer(paramObj.toString(), ","); while (st.hasMoreTokens()) { final String token = st.nextToken(); final CommandType listType = annotation.collectionType(); switch (listType) { case INTEGER: listParam.add(Integer.valueOf(token)); break; case UUID: if (token.isEmpty()) break; final Long internalId = translateUuidToInternalId(token, annotation); listParam.add(internalId); break; case LONG: { listParam.add(Long.valueOf(token)); } break; case SHORT: listParam.add(Short.valueOf(token)); break; case STRING: listParam.add(token); break; } } field.set(cmdObj, listParam); break; case UUID: final Long internalId = translateUuidToInternalId(paramObj.toString(), annotation); field.set(cmdObj, internalId); break; case LONG: field.set(cmdObj, Long.valueOf(paramObj.toString())); break; case SHORT: field.set(cmdObj, Short.valueOf(paramObj.toString())); break; case STRING: if ((paramObj != null)) { if (paramObj.toString().length() > annotation.length()) { s_logger.error("Value greater than max allowed length " + annotation.length() + " for param: " + field.getName()); throw new InvalidParameterValueException("Value greater than max allowed length " + annotation.length() + " for param: " + field.getName()); } else { field.set(cmdObj, paramObj.toString()); } } break; case TZDATE: field.set(cmdObj, DateUtil.parseTZDateString(paramObj.toString())); break; case MAP: default: field.set(cmdObj, paramObj); break; } } catch (final IllegalAccessException ex) { s_logger.error("Error initializing command " + cmdObj.getCommandName() + ", field " + field.getName() + " is not accessible."); throw new CloudRuntimeException("Internal error initializing parameters for command " + cmdObj.getCommandName() + " [field " + field.getName() + " is not accessible]"); } }
From source file:net.firejack.platform.core.config.meta.construct.ConfigElementFactory.java
private Object getDefaultValue(FieldType fieldType, String strValue) { if (StringUtils.isBlank(strValue) || fieldType == null) { return null; }/*from w w w. j a v a 2 s . c o m*/ if (fieldType.isString()) { return strValue; } else if (fieldType.isInteger()) { if (StringUtils.isNumeric(strValue)) { return Integer.valueOf(strValue); } else { return strValue; } } else if (fieldType.isLong()) { if (StringUtils.isNumeric(strValue)) { return Long.valueOf(strValue); } else { return strValue; } } else if (fieldType.isReal()) { return fieldType == FieldType.CURRENCY || fieldType == FieldType.DECIMAL_NUMBER ? Double.valueOf(strValue) : Float.valueOf(strValue); } else if (fieldType.isTimeRelated()) { return strValue; // todo need to discuss } else if (fieldType == FieldType.FLAG) { return Boolean.valueOf(strValue); } else { throw new UnsupportedOperationException( "Can't de-serialize default value of type [" + fieldType.name() + "]"); } }
From source file:cat.albirar.framework.dynabean.impl.DynaBeanImpl.java
/** * Test if the value is for a primitive type and return an object representation with default (0) value. If value is * null and the type is primitive, return a representation of default value for the primitive corresponding type. * /*from w w w . j av a2 s . c o m*/ * @param value the value, can be null * @param pb The property bean descriptor * @return The value or the default value representation for the primitive type (0) */ private Object nullSafeValue(Object value, DynaBeanPropertyDescriptor pb) { if (!pb.isPrimitive()) { return value; } if (pb.getPropertyType().getName().equals("byte")) { return (value == null ? Byte.valueOf((byte) 0) : (Byte) value); } if (pb.getPropertyType().getName().equals("short")) { return (value == null ? Short.valueOf((short) 0) : (Short) value); } if (pb.getPropertyType().getName().equals("int")) { return (value == null ? Integer.valueOf(0) : (Integer) value); } if (pb.getPropertyType().getName().equals("long")) { return (value == null ? Long.valueOf(0L) : (Long) value); } if (pb.getPropertyType().getName().equals("float")) { return (value == null ? Float.valueOf(0F) : (Float) value); } if (pb.getPropertyType().getName().equals("double")) { return (value == null ? Double.valueOf(0D) : (Double) value); } if (pb.getPropertyType().getName().equals("char")) { return (value == null ? Character.valueOf('\u0000') : (Character) value); } return (value == null ? Boolean.FALSE : (Boolean) value); }
From source file:com.isencia.passerelle.message.TokenHelper.java
/** * Tries to get a Float from the token, by: * <ul>/*from w w w.j a va2 s .c o m*/ * <li>checking if the token is not an ObjectToken, containing a Float * <li>checking if the token is not an ObjectToken, and converting the object.toString() into a Float * <li>checking if the token is not a StringToken, and converting the string into a Float * <li>checking if the token is not a ScalarToken, and reading its double value and converting it to a float * </ul> * Remark that converting a double to a float may lead to loss of precision. Furthermore, if the double value in the * token is bigger than Float.MAX_VALUE, the converted float will just be "infinity". * * @param token * @return */ public static Float getFloatFromToken(Token token) throws PasserelleException { if (logger.isTraceEnabled()) { logger.trace(token.toString()); // TODO Check if correct converted } Float res = null; if (token != null) { try { if (token instanceof ObjectToken) { Object obj = ((ObjectToken) token).getValue(); if (obj instanceof Float) { res = (Float) obj; } else if (obj != null) { try { res = Float.valueOf(obj.toString()); } catch (NumberFormatException e) { throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR, "Invalid Float format in " + token, e); } } } else { if (token instanceof StringToken) { String tokenMessage = ((StringToken) token).stringValue(); if (tokenMessage != null) { try { res = Float.valueOf(tokenMessage); } catch (NumberFormatException e) { throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR, "Invalid Float format in " + token, e); } } } else if (token instanceof ScalarToken) { try { res = new Float(((ScalarToken) token).doubleValue()); } catch (IllegalActionException e) { throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR, "Invalid token for obtaining Float value in " + token, e); } } else { throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR, "Invalid token for obtaining Float value in " + token, null); } } } catch (Exception e) { throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR, "Error building Float from token in " + token, e); } } if (logger.isTraceEnabled()) { logger.trace("exit :" + res); } return res; }
From source file:hivemall.topicmodel.OnlineLDAModel.java
@Nonnull public SortedMap<Float, List<String>> getTopicWords(@Nonnegative final int k, @Nonnegative int topN) { double lambdaSum = 0.d; final SortedMap<Float, List<String>> sortedLambda = new TreeMap<Float, List<String>>( Collections.reverseOrder()); for (Map.Entry<String, float[]> e : _lambda.entrySet()) { final float lambda_k = e.getValue()[k]; lambdaSum += lambda_k;/*from w w w.j a va 2 s . co m*/ List<String> labels = sortedLambda.get(lambda_k); if (labels == null) { labels = new ArrayList<String>(); sortedLambda.put(lambda_k, labels); } labels.add(e.getKey()); } final SortedMap<Float, List<String>> ret = new TreeMap<Float, List<String>>(Collections.reverseOrder()); topN = Math.min(topN, _lambda.keySet().size()); int tt = 0; for (Map.Entry<Float, List<String>> e : sortedLambda.entrySet()) { float key = (float) (e.getKey().floatValue() / lambdaSum); ret.put(Float.valueOf(key), e.getValue()); if (++tt == topN) { break; } } return ret; }
From source file:net.sf.jasperreports.engine.util.JRStyledTextParser.java
/** * *//*from w w w . j a va 2 s .c om*/ private void parseStyle(JRStyledText styledText, Node parentNode) throws SAXException { NodeList nodeList = parentNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.TEXT_NODE) { styledText.append(node.getNodeValue()); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_style.equals(node.getNodeName())) { NamedNodeMap nodeAttrs = node.getAttributes(); Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); if (nodeAttrs.getNamedItem(ATTRIBUTE_fontName) != null) { styleAttrs.put(TextAttribute.FAMILY, nodeAttrs.getNamedItem(ATTRIBUTE_fontName).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isBold) != null) { styleAttrs.put(TextAttribute.WEIGHT, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isBold).getNodeValue()) ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isItalic) != null) { styleAttrs.put(TextAttribute.POSTURE, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isItalic).getNodeValue()) ? TextAttribute.POSTURE_OBLIQUE : TextAttribute.POSTURE_REGULAR); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isUnderline) != null) { styleAttrs.put(TextAttribute.UNDERLINE, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isUnderline).getNodeValue()) ? TextAttribute.UNDERLINE_ON : null); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isStrikeThrough) != null) { styleAttrs.put(TextAttribute.STRIKETHROUGH, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isStrikeThrough).getNodeValue()) ? TextAttribute.STRIKETHROUGH_ON : null); } if (nodeAttrs.getNamedItem(ATTRIBUTE_size) != null) { styleAttrs.put(TextAttribute.SIZE, Float.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_size).getNodeValue())); } if (nodeAttrs.getNamedItem(ATTRIBUTE_pdfFontName) != null) { styleAttrs.put(JRTextAttribute.PDF_FONT_NAME, nodeAttrs.getNamedItem(ATTRIBUTE_pdfFontName).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_pdfEncoding) != null) { styleAttrs.put(JRTextAttribute.PDF_ENCODING, nodeAttrs.getNamedItem(ATTRIBUTE_pdfEncoding).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isPdfEmbedded) != null) { styleAttrs.put(JRTextAttribute.IS_PDF_EMBEDDED, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isPdfEmbedded).getNodeValue())); } if (nodeAttrs.getNamedItem(ATTRIBUTE_forecolor) != null) { Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_forecolor).getNodeValue(), Color.black); styleAttrs.put(TextAttribute.FOREGROUND, color); } if (nodeAttrs.getNamedItem(ATTRIBUTE_backcolor) != null) { Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_backcolor).getNodeValue(), Color.black); styleAttrs.put(TextAttribute.BACKGROUND, color); } int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_bold.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_italic.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_underline.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_sup.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_sub.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_font.equalsIgnoreCase(node.getNodeName())) { NamedNodeMap nodeAttrs = node.getAttributes(); Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); if (nodeAttrs.getNamedItem(ATTRIBUTE_size) != null) { styleAttrs.put(TextAttribute.SIZE, Float.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_size).getNodeValue())); } if (nodeAttrs.getNamedItem(ATTRIBUTE_color) != null) { Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_color).getNodeValue(), Color.black); styleAttrs.put(TextAttribute.FOREGROUND, color); } if (nodeAttrs.getNamedItem(ATTRIBUTE_fontFace) != null) { String fontFaces = nodeAttrs.getNamedItem(ATTRIBUTE_fontFace).getNodeValue(); StringTokenizer t = new StringTokenizer(fontFaces, ","); while (t.hasMoreTokens()) { String face = t.nextToken().trim(); if (AVAILABLE_FONT_FACE_NAMES.contains(face)) { styleAttrs.put(TextAttribute.FAMILY, face); break; } } } int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_br.equalsIgnoreCase(node.getNodeName())) { styledText.append("\n"); int startIndex = styledText.length(); resizeRuns(styledText.getRuns(), startIndex, 1); parseStyle(styledText, node); styledText.addRun( new JRStyledText.Run(new HashMap<Attribute, Object>(), startIndex, styledText.length())); if (startIndex < styledText.length()) { styledText.append("\n"); resizeRuns(styledText.getRuns(), startIndex, 1); } } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_li.equalsIgnoreCase(node.getNodeName())) { String tmpText = styledText.getText(); if (tmpText.length() > 0 && !tmpText.endsWith("\n")) { styledText.append("\n"); } styledText.append(" \u2022 "); int startIndex = styledText.length(); resizeRuns(styledText.getRuns(), startIndex, 1); parseStyle(styledText, node); styledText.addRun( new JRStyledText.Run(new HashMap<Attribute, Object>(), startIndex, styledText.length())); // if the text in the next node does not start with a '\n', or // if the next node is not a <li /> one, we have to append a new line Node nextNode = node.getNextSibling(); String textContent = getFirstTextOccurence(nextNode); if (nextNode != null && !((nextNode.getNodeType() == Node.ELEMENT_NODE && NODE_li.equalsIgnoreCase(nextNode.getNodeName()) || (textContent != null && textContent.startsWith("\n"))))) { styledText.append("\n"); resizeRuns(styledText.getRuns(), startIndex, 1); } } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_a.equalsIgnoreCase(node.getNodeName())) { if (hyperlink == null) { NamedNodeMap nodeAttrs = node.getAttributes(); Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); hyperlink = new JRBasePrintHyperlink(); hyperlink.setHyperlinkType(HyperlinkTypeEnum.REFERENCE); styleAttrs.put(JRTextAttribute.HYPERLINK, hyperlink); if (nodeAttrs.getNamedItem(ATTRIBUTE_href) != null) { hyperlink.setHyperlinkReference(nodeAttrs.getNamedItem(ATTRIBUTE_href).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_type) != null) { hyperlink.setLinkType(nodeAttrs.getNamedItem(ATTRIBUTE_type).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_target) != null) { hyperlink.setLinkTarget(nodeAttrs.getNamedItem(ATTRIBUTE_target).getNodeValue()); } int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); hyperlink = null; } else { throw new SAXException("Hyperlink <a> tags cannot be nested."); } } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_param.equalsIgnoreCase(node.getNodeName())) { if (hyperlink == null) { throw new SAXException("Hyperlink <param> tags must appear inside an <a> tag only."); } else { NamedNodeMap nodeAttrs = node.getAttributes(); JRPrintHyperlinkParameter parameter = new JRPrintHyperlinkParameter(); if (nodeAttrs.getNamedItem(ATTRIBUTE_name) != null) { parameter.setName(nodeAttrs.getNamedItem(ATTRIBUTE_name).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_valueClass) != null) { parameter.setValueClass(nodeAttrs.getNamedItem(ATTRIBUTE_valueClass).getNodeValue()); } String strValue = node.getTextContent(); if (strValue != null) { Object value = JRValueStringUtils.deserialize(parameter.getValueClass(), strValue); parameter.setValue(value); } hyperlink.addHyperlinkParameter(parameter); } } else if (node.getNodeType() == Node.ELEMENT_NODE) { String nodeName = "<" + node.getNodeName() + ">"; throw new SAXException("Tag " + nodeName + " is not a valid styled text tag."); } } }
From source file:edu.ucsc.barrel.cdf_gen.SpectrumExtract.java
public static float[] makeedges(int spec_i, float xtal_temp, float dpu_temp, float peak511) { String payload = CDF_Gen.getSetting("currentPayload").substring(0, 2); float[] edges_in = (CDF_Gen.data.getVersion() > 3 ? RAW_EDGES[spec_i] : OLD_RAW_EDGES[spec_i]); //initialize array for calibrated edges float[] edges_out = new float[edges_in.length]; //get dpu coefficients from calibration file float[][] dpu_coeffs = { { -5f, -0.1f }, { -0.5f, -0.001f }, { -0.1f, 0.0001f } }; boolean payload_found = false; File energy_cal = new File("energy.cal"); if (!energy_cal.exists()) { }/*from w ww . j a v a 2 s.c o m*/ try { FileReader fr = new FileReader(energy_cal); BufferedReader br = new BufferedReader(fr); String line; String[] line_parts; while ((line = br.readLine()) != null) { //split off comments line_parts = line.split(";"); //split the payload ID from the rest line_parts = line_parts[0].split(":"); line_parts[0] = line_parts[0].trim(); if (!payload.equals(line_parts[0])) { continue; } //we have the right payload, check for the right number of values payload_found = true; line_parts[1] = line_parts[1].trim(); line_parts = line_parts[1].split(","); if (line_parts.length != 6) { continue; } //the correct number of values were in the file //overwrite defaults dpu_coeffs = new float[][] { { Float.valueOf(line_parts[0]), Float.valueOf(line_parts[1]) }, { Float.valueOf(line_parts[2]), Float.valueOf(line_parts[3]) }, { Float.valueOf(line_parts[4]), Float.valueOf(line_parts[5]) } }; br.close(); break; } br.close(); } catch (IOException ex) { System.out.println("Can not find energy calibration file."); System.out.println("Using default values."); } //just return standard edges if there are no dpu coefficients if (!payload_found) { return stdEdges(spec_i, SCALE_FACTOR); } //set model parameters float xtal_compensate = 1.022f - 1.0574e-4f * (float) Math.pow(xtal_temp - 10.7f, 2); float[] dpu_compensate = new float[] { ((dpu_coeffs[0][0]) + (dpu_temp * dpu_coeffs[0][1])), ((dpu_coeffs[1][0]) + (dpu_temp * dpu_coeffs[1][1])), ((dpu_coeffs[2][0]) + (dpu_temp * dpu_coeffs[2][1])) }; float factor = dpu_compensate[2] / dpu_compensate[1]; //calculate a correction from 511keV location float fac511 = 1.0f; if (peak511 != (Float) CDFVar.getIstpVal("FLOAT_FILL")) { float start = (peak511 / xtal_compensate - dpu_compensate[0]) / dpu_compensate[1]; fac511 = 511.0f / binvert(start, factor); } //calculate energies for the desired spectral product float[] start = new float[edges_in.length]; for (int i = 0; i < start.length; i++) { start[i] = (edges_in[i] / xtal_compensate - dpu_compensate[0]) / dpu_compensate[1]; } edges_out = binvert(start, factor); for (int i = 0; i < edges_out.length; i++) { edges_out[i] *= fac511; } return edges_out; }