Example usage for java.text NumberFormat parse

List of usage examples for java.text NumberFormat parse

Introduction

In this page you can find the example usage for java.text NumberFormat parse.

Prototype

public Number parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a number.

Usage

From source file:us.levk.math.linear.HugeRealMatrix.java

/**
 * Parse a matrix from a stream/*ww w .j  ava2s.  co  m*/
 * 
 * @param stream
 * @param columnDelimiters
 * @param rowDelimiters
 * @param parser
 * @throws IOException
 * @throws ParseException
 */
public HugeRealMatrix(InputStream stream, char[] columnDelimiters, char[] rowDelimiters, NumberFormat parser)
        throws IOException, ParseException {
    StringBuilder word = new StringBuilder();
    Set<Integer> columnDelims = new HashSet<>();
    Set<Integer> rowDelims = new HashSet<>();
    for (char b : columnDelimiters)
        columnDelims.add((int) b);
    for (char b : rowDelimiters)
        rowDelims.add((int) b);
    String name = randomFileName();
    try (RandomAccessFile file = new RandomAccessFile(name, "rw")) {
        int columns = 0;
        int rows = 0;
        int prevColumns = -1;
        PushbackInputStream in = new PushbackInputStream(stream, 1024);
        startMatrixParse(in, columnDelims, rowDelims);
        boolean newRow = true;
        for (int c;;) {
            if (newRow) {
                startRowParse(in, rows, columnDelims, parser);
                newRow = false;
            }
            c = in.read();
            if (columnDelims.contains(c) || rowDelims.contains(c) || c < 0) {
                try {
                    double value = parser.parse(word.toString().trim()).doubleValue();
                    file.writeDouble(value);
                } catch (ParseException e) {
                    if (columns == 0)
                        break;
                    else
                        throw e;
                }
                columns++;
                word = new StringBuilder();
                if (rowDelims.contains(c) || c < 0) {
                    rows++;
                    if (columns != prevColumns && prevColumns >= 0)
                        throw new IOException("Jagged row detected, previous row " + prevColumns
                                + " columns, current row " + columns + " columns");
                    prevColumns = columns;
                    columns = 0;
                    if (c < 0)
                        break;
                    else
                        newRow = true;
                }
            } else
                word.append((char) c);
        }
        endMatrixParse(in, prevColumns, rows);
        this.name = name;
        this.file = file;
        this.columnDimension = prevColumns;
        this.rowDimension = rows;
        long size = 8L * rowDimension * columnDimension;
        for (long offset = 0; offset < size; offset += MAPPING_SIZE)
            mappings.add(file.getChannel().map(READ_WRITE, offset, min(size - offset, MAPPING_SIZE)));
    } catch (IOException | ParseException | RuntimeException | Error e) {
        new File(name).delete();
        throw e;
    }
}

From source file:cross.io.xml.FragmentXMLSerializer.java

/**
 * @param name/*from  ww w. j  a  v a2  s .  c o m*/
 * @param dims
 * @param data
 * @return
 */
private Array handleData(final String name, final Dimension[] dims, final Element data, final Range[] ranges) {
    EvalTools.notNull(dims, this);
    final String dec = new String(Base64.decode(data.getText(), Base64.GZIP));
    final StreamTokenizer st = new StreamTokenizer(new StringReader(dec));
    final NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
    final int[] shape = new int[dims.length];
    int d = 0;
    for (final Dimension dim : dims) {
        shape[d++] = dim.getLength();
    }
    Array a = null;
    IndexIterator idx = null;
    int tok = -1;
    // log.info("DataType of array: {}",
    // dt.getPrimitiveClassType().getName());
    Mode m = Mode.UNDEF;
    Object o = null;
    try {
        while ((tok = st.nextToken()) != StreamTokenizer.TT_EOL) {
            if (tok == StreamTokenizer.TT_WORD) {

                if (m == Mode.UNDEF) {
                    try {
                        o = nf.parse(st.sval);

                        if (o instanceof Double) {
                            m = Mode.DOUBLE;
                            a = Array.factory(DataType.DOUBLE, shape);
                        } else if (o instanceof Float) {
                            m = Mode.FLOAT;
                            a = Array.factory(DataType.FLOAT, shape);
                        } else if (o instanceof Long) {
                            m = Mode.LONG;
                            a = Array.factory(DataType.LONG, shape);
                        } else if (o instanceof Integer) {
                            m = Mode.INTEGER;
                            a = Array.factory(DataType.INT, shape);
                        } else if (o instanceof Byte) {
                            m = Mode.BYTE;
                            a = Array.factory(DataType.BYTE, shape);
                        } else if (o instanceof Short) {
                            m = Mode.SHORT;
                            a = Array.factory(DataType.SHORT, shape);
                        }
                    } catch (final ParseException pe) {
                        if (st.sval.equalsIgnoreCase("true") || st.sval.equalsIgnoreCase("false")) {
                            m = Mode.BOOLEAN;
                            a = Array.factory(DataType.BOOLEAN, shape);
                        } else {
                            m = Mode.STRING;
                            a = Array.factory(DataType.STRING, shape);
                        }
                    }
                } else {
                    if (idx == null) {
                        idx = a.getIndexIterator();
                    }
                    switch (m) {
                    case DOUBLE: {
                        idx.setDoubleNext((Double) o);
                        break;
                    }
                    case FLOAT: {
                        idx.setFloatNext((Float) o);
                        break;
                    }
                    case INTEGER: {
                        idx.setIntNext((Integer) o);
                        break;
                    }
                    case LONG: {
                        idx.setLongNext((Long) o);
                        break;
                    }
                    case BYTE: {
                        idx.setByteNext((Byte) o);
                        break;
                    }
                    case SHORT: {
                        idx.setShortNext((Short) o);
                        break;
                    }
                    case BOOLEAN: {
                        idx.setBooleanNext(Boolean.parseBoolean(st.sval));
                        break;
                    }
                    case STRING: {
                        idx.setObjectNext(st.sval);
                        break;
                    }
                    case OBJECT: {
                        throw new IllegalArgumentException("Could not handle type");
                    }
                    }
                }
            }
        }
    } catch (final IOException e) {
        log.warn("Could not read data for {}", name);
    }
    if (a != null && ranges != null && ranges.length != 0) {
        try {
            return a.section(Arrays.asList(ranges));
        } catch (InvalidRangeException ex) {
            log.warn("Invalid range while trying to subset array: ", ex);
        }
    }
    return a;
}

From source file:dk.dma.msinm.legacy.nm.NmPdfExtractor.java

/**
 * Reads and updates the locations from the line
 * @param locLine the line containing the locations
 * @param lang the language/*w w  w . j  a  va2  s.c o  m*/
 * @param notice the notice to update
 */
void readLocation(String locLine, String lang, Message notice) {
    NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
    String posPattern = "(\\d+)I?\\s+(\\d+,?\\d+)J?\\s+(N|S)\\s+(\\d+)I?\\s+(\\d+,?\\d+)J?\\s+(E|W),?(.*)";
    Pattern p1 = Pattern.compile(posPattern);
    Pattern p2 = Pattern.compile("(\\d+)\\)\\s+" + posPattern);

    Location location = new Location();
    String[] lines = locLine.split("\n");
    for (int x = 0; x < lines.length; x++) {

        String line = lines[x].trim();
        if (line.endsWith(".")) {
            line = line.substring(0, line.length() - 1);
        }

        Matcher m1 = p1.matcher(line);
        Matcher m2 = p2.matcher(line);
        if (m1.matches() || m2.matches()) {
            Point pt = new Point();
            pt.setLocation(location);
            try {
                int i = 1;

                Matcher m;
                if (m1.matches()) {
                    m = m1;
                    pt.setIndex(x + 1);
                } else {
                    m = m2;
                    pt.setIndex(Integer.valueOf(m.group(i++)));
                }

                pt.setLat(parsePos(Integer.parseInt(m.group(i++)), format.parse(m.group(i++)).doubleValue(),
                        m.group(i++)));
                pt.setLon(parsePos(Integer.parseInt(m.group(i++)), format.parse(m.group(i++)).doubleValue(),
                        m.group(i++)));
                String desc = m.group(i).trim();
                if (StringUtils.isNotBlank(desc)) {
                    pt.checkCreateDesc(lang).setDescription(desc);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            location.getPoints().add(pt);
        } else {
            log.warn("No match " + lines[x]);
        }

    }

    if (location.getPoints().size() > 0) {
        location.setType(location.getPoints().size() == 1 ? Location.LocationType.POINT
                : (location.getPoints().size() == 2 ? Location.LocationType.POLYLINE
                        : Location.LocationType.POLYGON));
        notice.getLocations().add(location);
    }
}

From source file:org.ecoinformatics.seek.R.RExpression.java

private void _setOutputToken(String portName, String tokenValue) {
    opList = outputPortList();/*from  www .  j a  va 2  s  . co  m*/
    iter_o = opList.iterator();
    while (iter_o.hasNext()) {
        TypedIOPort tiop_o = (TypedIOPort) iter_o.next();
        String temp_o = tiop_o.getName();
        Token token = null;
        if ((!temp_o.equals("output")) && (!temp_o.equals("graphicsFileName"))) {
            if (temp_o.equals(portName)) {
                try {
                    if (tokenValue.equals("TRUE")) {
                        BooleanToken btt = BooleanToken.getInstance(true);
                        tiop_o.setTypeEquals(BaseType.BOOLEAN);
                        token = btt;
                    }
                    if (tokenValue.equals("FALSE")) {
                        BooleanToken btf = BooleanToken.getInstance(false);
                        tiop_o.setTypeEquals(BaseType.BOOLEAN);
                        token = btf;
                    }
                    if (tokenValue.equals("NA")) {
                        tiop_o.setTypeEquals(BaseType.STRING);
                        token = StringToken.NIL;
                        // this solution just sends a string token with
                        // value 'nil'
                        // in R, 'NA' is considered a boolean state
                        // i.e. 3 state logic, so this isn't really correct
                        // but nil support for Ptolemy BooleanTokens not yet
                        // available

                    }
                    if (tokenValue.startsWith("_dataframe_:")) {
                        StringToken st = new StringToken(tokenValue);
                        tiop_o.setTypeEquals(BaseType.STRING);
                        token = st;
                    }
                    if (tokenValue.startsWith("_object_:")) {
                        StringToken st = new StringToken(tokenValue);
                        tiop_o.setTypeEquals(BaseType.STRING);
                        token = st;
                    }
                    if (tokenValue.startsWith("_matrix_:")) {
                        int pos1, pos2;
                        pos1 = tokenValue.indexOf(".Dim");
                        pos1 = tokenValue.indexOf("c(", pos1);
                        pos2 = tokenValue.indexOf(",", pos1);
                        String nrowS = tokenValue.substring(pos1 + 2, pos2);
                        String ncolS = tokenValue.substring(pos2 + 1, tokenValue.indexOf(")", pos2 + 1));
                        int nrows = Integer.parseInt(nrowS.trim());
                        int ncols = Integer.parseInt(ncolS.trim());
                        pos1 = "_matrix_:".length();
                        pos1 = tokenValue.indexOf("c(", pos1);
                        pos2 = tokenValue.indexOf(")", pos1);
                        String valS = tokenValue.substring(pos1 + 2, pos2);
                        pos1 = 0;
                        for (int j = 0; j < nrows - 1; j++) {
                            for (int i = 0; i < ncols; i++) {
                                pos2 = valS.indexOf(",", pos1);
                                pos1 = pos2 + 1;
                            }
                            valS = valS.substring(0, pos1 - 1) + ";" + valS.substring(pos1, valS.length());
                        }
                        valS = "[" + valS + "]";
                        MatrixToken mt = null;
                        try {
                            mt = new IntMatrixToken(valS);
                        } catch (Exception ee) {
                            try {
                                mt = new DoubleMatrixToken(valS);
                            } catch (Exception eee) {
                                mt = new BooleanMatrixToken();
                            }
                        }
                        token = mt;
                    }
                    if (tokenValue.startsWith("\"")) { // these are strings
                        // now remove the start and end quotes
                        tokenValue = tokenValue.substring(1, tokenValue.length() - 1);
                        //remove the escapes that dput() added
                        tokenValue = StringEscapeUtils.unescapeJava(tokenValue);
                        StringToken st = new StringToken(tokenValue);
                        tiop_o.setTypeEquals(BaseType.STRING);
                        token = st;
                    }
                    NumberFormat nf = NumberFormat.getInstance();
                    try {
                        nf.parse(tokenValue);
                        DoubleToken dt = new DoubleToken(tokenValue);
                        tiop_o.setTypeEquals(BaseType.DOUBLE);
                        token = dt;
                    } catch (Exception eee) {
                        // just continue if not a number
                    }

                    if (tokenValue.startsWith("c(")) { // handles R vectors
                        // hack alert! this does not support R's c(1:10)
                        // syntax for arrays
                        String temp = "{" + tokenValue.substring(2, tokenValue.length());
                        temp = temp.replace(')', '}');
                        // convert NA values to 'nil'
                        temp = temp.replaceAll("NA", "nil");
                        ArrayToken at = new ArrayToken(temp);
                        tiop_o.setTypeEquals(new ArrayType(at.getElementType(), at.length()));
                        token = at;
                    }

                    // check for empty arrays
                    if (tokenValue.equals("character(0)")) {
                        token = new ArrayToken(BaseType.STRING);
                    }
                    if (tokenValue.equals("numeric(0)")) {
                        token = new ArrayToken(BaseType.DOUBLE);
                    }
                    if (tokenValue.equals("logical(0)")) {
                        token = new ArrayToken(BaseType.BOOLEAN);
                    }

                    // verify that we have a token
                    if (token == null) {
                        log.warn("No token could be created on portName: " + portName + ", for tokenValue: "
                                + tokenValue);
                        return;
                    }
                    // send whatever token we happened to generate - all
                    // channels
                    // (note: sinkPortList size does not necessarily == port
                    // width)
                    int numSinkPorts = tiop_o.sinkPortList().size();
                    int portWidth = tiop_o.getWidth();

                    // check the types of the sink ports for compatibility
                    for (int channelIndex = 0; channelIndex < numSinkPorts; channelIndex++) {
                        Type sinkType = ((TypedIOPort) tiop_o.sinkPortList().get(channelIndex)).getType();
                        // if (!sinkType.isCompatible(token.getType())) {
                        // change to equals for bug #3451:
                        if (!sinkType.equals(token.getType())) {
                            log.debug("[re]Setting sink type to: " + token.getType().toString());
                            // set the Type for the sinks
                            // POSSIBLE BUG - not sure why the automatic
                            // type resolution was failing for downstream
                            // port
                            ((TypedIOPort) tiop_o.sinkPortList().get(channelIndex))
                                    .setTypeEquals(token.getType());
                        }
                    }

                    // send the token to the channel[s] of the port
                    for (int channelIndex = 0; channelIndex < portWidth; channelIndex++) {
                        tiop_o.send(channelIndex, token);
                    }

                } catch (Exception w) {
                    log.error("Problem sending to output port! " + w);
                    w.printStackTrace();
                }

                return;
            }
        }
    }
}

From source file:org.jboss.dashboard.ui.components.chart.MeterChartEditor.java

public CommandResponse actionSubmit(CommandRequest request) throws Exception {
    MeterChartDisplayer meterDisplayer = (MeterChartDisplayer) getDataDisplayer();
    if (!meterDisplayer.getDataProvider().isReady())
        return null;

    super.actionSubmit(request);
    try {/*from  w w w  .  j  a  va2  s. co m*/
        Locale locale = LocaleManager.currentLocale();
        NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);

        // Parse the position.
        String positionType = request.getRequestObject().getParameter("positionType");
        if (positionType != null && !"".equals(positionType))
            meterDisplayer.setPositionType(positionType);

        // Meter
        if (meterDisplayer.getType().equals("meter")) {
            String minValueParam = request.getRequestObject().getParameter("minValue");
            String maxValueParam = request.getRequestObject().getParameter("maxValue");
            String maxMeterTicksParam = request.getRequestObject().getParameter("maxMeterTicks");
            String warningThresholdParam = request.getRequestObject().getParameter("meterWarningThreshold");
            String criticalThresholdParam = request.getRequestObject().getParameter("meterCriticalThreshold");
            if (minValueParam == null || "".equals(minValueParam.trim()))
                return null;
            if (maxValueParam == null || "".equals(maxValueParam.trim()))
                return null;
            if (warningThresholdParam == null || "".equals(warningThresholdParam.trim()))
                return null;
            if (criticalThresholdParam == null || "".equals(criticalThresholdParam.trim()))
                return null;
            if (maxMeterTicksParam == null || "".equals(maxMeterTicksParam.trim()))
                return null;

            double minValue = numberFormat.parse(minValueParam).doubleValue();
            double maxValue = numberFormat.parse(maxValueParam).doubleValue();
            double warningThreshold = numberFormat.parse(warningThresholdParam).doubleValue();
            double criticalThreshold = numberFormat.parse(criticalThresholdParam).doubleValue();
            int maxMeterTicks = numberFormat.parse(maxMeterTicksParam).intValue();
            if (minValue > maxValue)
                return null;
            if (warningThreshold < minValue || warningThreshold > maxValue)
                return null;
            if (criticalThreshold < minValue || criticalThreshold > maxValue)
                return null;
            if (warningThreshold > criticalThreshold)
                return null;
            if (maxMeterTicks < 0)
                return null;

            meterDisplayer.setMaxMeterTicks(maxMeterTicks);
            meterDisplayer.setMinValue(minValue);
            meterDisplayer.setWarningThreshold(warningThreshold);
            meterDisplayer.setCriticalThreshold(criticalThreshold);
            meterDisplayer.setMaxValue(maxValue);

            /* Intervals descriptions. Hide them until the global legend will be available.
            String descripNormalInterval = request.getRequestObject().getParameter("descripNormalInterval");
            String descripWarningInterval = request.getRequestObject().getParameter("descripWarningInterval");
            String descripCriticalInterval = request.getRequestObject().getParameter("descripCriticalInterval");
            if (descripCriticalInterval != null && !"".equals(descripCriticalInterval.trim())) meterDisplayer.setDescripCriticalInterval(descripCriticalInterval, locale);
            if (descripWarningInterval != null && !"".equals(descripWarningInterval.trim())) meterDisplayer.setDescripWarningInterval(descripWarningInterval, locale);
            if (descripNormalInterval != null && !"".equals(descripNormalInterval.trim())) meterDisplayer.setDescripNormalInterval(descripNormalInterval, locale);
            */
        }
        // Thermometer
        else if (meterDisplayer.getType().equals("thermometer")) {
            String thermoLowerBoundParam = request.getRequestObject().getParameter("thermoLowerBound");
            String thermoUpperBoundParam = request.getRequestObject().getParameter("thermoUpperBound");
            String thermoWarningThresholdParam = request.getRequestObject()
                    .getParameter("thermoWarningThreshold");
            String thermoCriticalThresholdParam = request.getRequestObject()
                    .getParameter("thermoCriticalThreshold");
            if (thermoLowerBoundParam == null || "".equals(thermoLowerBoundParam.trim()))
                return null;
            if (thermoUpperBoundParam == null || "".equals(thermoUpperBoundParam.trim()))
                return null;
            if (thermoWarningThresholdParam == null || "".equals(thermoWarningThresholdParam.trim()))
                return null;
            if (thermoCriticalThresholdParam == null || "".equals(thermoCriticalThresholdParam.trim()))
                return null;

            double thermoLowerBound = numberFormat.parse(thermoLowerBoundParam).doubleValue();
            double thermoUpperBound = numberFormat.parse(thermoUpperBoundParam).doubleValue();
            double thermoWarningThreshold = numberFormat.parse(thermoWarningThresholdParam).doubleValue();
            double thermoCriticalThreshold = numberFormat.parse(thermoCriticalThresholdParam).doubleValue();
            if (thermoLowerBound > thermoUpperBound)
                return null;
            if (thermoWarningThreshold < thermoLowerBound || thermoWarningThreshold > thermoUpperBound)
                return null;
            if (thermoCriticalThreshold < thermoLowerBound || thermoCriticalThreshold > thermoUpperBound)
                return null;
            if (thermoWarningThreshold > thermoCriticalThreshold)
                return null;

            meterDisplayer.setThermoLowerBound(thermoLowerBound);
            meterDisplayer.setWarningThermoThreshold(thermoWarningThreshold);
            meterDisplayer.setCriticalThermoThreshold(thermoCriticalThreshold);
            meterDisplayer.setThermoUpperBound(thermoUpperBound);
        }
        // Dial
        else if (meterDisplayer.getType().equals("dial")) {
            String pointerTypeParam = request.getRequestObject().getParameter("pointerType");
            String dialLowerBoundParam = request.getRequestObject().getParameter("dialLowerBound");
            String dialUpperBoundParam = request.getRequestObject().getParameter("dialUpperBound");
            String maxTicksParam = request.getRequestObject().getParameter("maxTicks");
            String minorTickCountParam = request.getRequestObject().getParameter("minorTickCount");
            if (pointerTypeParam == null || "".equals(pointerTypeParam.trim()))
                return null;
            if (dialLowerBoundParam == null || "".equals(dialLowerBoundParam.trim()))
                return null;
            if (dialUpperBoundParam == null || "".equals(dialUpperBoundParam.trim()))
                return null;
            if (maxTicksParam == null || "".equals(maxTicksParam.trim()))
                return null;
            if (minorTickCountParam == null || "".equals(minorTickCountParam.trim()))
                return null;

            double dialLowerBound = numberFormat.parse(dialLowerBoundParam).doubleValue();
            double dialUpperBound = numberFormat.parse(dialUpperBoundParam).doubleValue();
            int maxTicks = numberFormat.parse(maxTicksParam).intValue();
            int minorTickCount = numberFormat.parse(minorTickCountParam).intValue();
            if (dialLowerBound > dialUpperBound)
                return null;
            if (maxTicks < 0)
                return null;
            if (minorTickCount > 10)
                return null;

            meterDisplayer.setDialLowerBound(dialLowerBound);
            meterDisplayer.setDialUpperBound(dialUpperBound);
            meterDisplayer.setMaxTicks(numberFormat.parse(maxTicksParam).intValue());
            meterDisplayer.setMinorTickCount(minorTickCount);
        }
    } catch (Exception e) {
        log.warn("Cannot parse number meter specific properties.");
    }
    return null;
}

From source file:org.lockss.plugin.clockss.XPathXmlMetadataParser.java

private ArticleMetadata extractDataFromNode(Object startNode, XPathInfo[] xPathList)
        throws XPathExpressionException {

    ArticleMetadata returnAM = makeNewArticleMetadata();
    NumberFormat format = NumberFormat.getInstance();

    for (int i = 0; i < xPathList.length; i++) {
        log.debug3("evaluate xpath: " + xPathList[i].xKey.toString());
        QName definedType = xPathList[i].xVal.getType();
        Object itemResult = xPathList[i].xExpr.evaluate(startNode, XPathConstants.NODESET);
        NodeList resultNodeList = (NodeList) itemResult;
        log.debug3(resultNodeList.getLength() + " results for this xKey");
        for (int p = 0; p < resultNodeList.getLength(); p++) {
            Node resultNode = resultNodeList.item(p);
            if (resultNode == null) {
                continue;
            }//  w  w w  .  j  ava 2 s .  c o  m
            String value = null;
            if (definedType == XPathConstants.NODE) {
                // filter node
                value = xPathList[i].xVal.getValue(resultNode);
            } else if (definedType == XPathConstants.STRING) {
                // filter node text content
                String text = resultNode.getTextContent();
                if (!StringUtil.isNullString(text)) {
                    value = xPathList[i].xVal.getValue(text);
                }
            } else if (definedType == XPathConstants.BOOLEAN) {
                // filter boolean value of node text content
                String text = resultNode.getTextContent();
                if (!StringUtil.isNullString(text)) {
                    value = xPathList[i].xVal.getValue(Boolean.parseBoolean(text));
                }
            } else if (definedType == XPathConstants.NUMBER) {
                // filter number value of node text content
                try {
                    String text = resultNode.getTextContent();
                    if (!StringUtil.isNullString(text)) {
                        value = xPathList[i].xVal.getValue(format.parse(text));
                    }
                } catch (ParseException ex) {
                    // ignore invalid number
                    log.debug3("ignore invalid number", ex);
                }
            } else {
                log.debug("Unknown nodeValue type: " + definedType.toString());
            }

            if (!StringUtil.isNullString(value)) {
                log.debug3("  returning (" + xPathList[i].xKey + ", " + value);
                returnAM.putRaw(xPathList[i].xKey, value);
            }
        }
    }
    return returnAM;
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java

/**
 * This method find the fault count of the APIs
 *
 * @param providerName Name of the API provider
 * @param fromDate     starting date of the results
 * @param toDate       ending date of the results
 * @return list of APIResponseFaultCountDTO
 * @throws APIMgtUsageQueryServiceClientException throws if error occurred
 *///from   w w w  .ja v  a  2 s. c o  m
@Override
public List<APIResponseFaultCountDTO> getAPIResponseFaultCount(String providerName, String fromDate,
        String toDate) throws APIMgtUsageQueryServiceClientException {
    String tenantAwareProviderName = providerName;
    String tenantDomain = MultitenantUtils.getTenantDomain(tenantAwareProviderName);
    if (providerName.contains(APIUsageStatisticsClientConstants.ALL_PROVIDERS)) {
        providerName = APIUsageStatisticsClientConstants.ALL_PROVIDERS;
    }
    List<APIResponseFaultCount> faultyData = this.getAPIResponseFaultCountData(
            APIUsageStatisticsClientConstants.API_FAULTY_INVOCATION_AGG, tenantDomain, fromDate, toDate);
    List<API> providerAPIs = getAPIsByProvider(providerName);
    List<APIResponseFaultCountDTO> faultyCount = new ArrayList<APIResponseFaultCountDTO>();
    List<APIVersionUsageDTO> apiVersionUsageList;

    for (APIResponseFaultCount fault : faultyData) {
        for (API providerAPI : providerAPIs) {
            if (providerAPI.getId().getApiName().equals(fault.getApiName())
                    && providerAPI.getId().getVersion().equals(fault.getApiVersion())
                    && providerAPI.getContext().equals(fault.getContext())) {

                APIResponseFaultCountDTO faultyDTO = new APIResponseFaultCountDTO();
                faultyDTO.setApiName(fault.getApiName());
                faultyDTO.setVersion(fault.getApiVersion());
                faultyDTO.setContext(fault.getContext());
                faultyDTO.setCount(fault.getFaultCount());
                apiVersionUsageList = getUsageByAPIVersions(tenantAwareProviderName, fault.getApiName(),
                        fromDate, toDate);
                for (APIVersionUsageDTO apiVersionUsageDTO : apiVersionUsageList) {
                    if (apiVersionUsageDTO.getVersion().equals(fault.getApiVersion())) {
                        long requestCount = apiVersionUsageDTO.getCount();
                        double faultPercentage = ((double) fault.getFaultCount())
                                / (requestCount + fault.getFaultCount()) * 100;
                        DecimalFormat twoDForm = new DecimalFormat("#.##");
                        NumberFormat numberFormat = NumberFormat.getInstance(Locale.getDefault());
                        try {
                            faultPercentage = numberFormat.parse(twoDForm.format(faultPercentage))
                                    .doubleValue();
                        } catch (ParseException e) {
                            handleException("Parse exception while formatting time");
                        }
                        faultyDTO.setFaultPercentage(faultPercentage);
                        faultyDTO.setTotalRequestCount(requestCount + fault.getFaultCount());
                        break;
                    }
                }
                //if no success request within that period, fault percentage is 100%
                if (apiVersionUsageList.isEmpty()) {
                    faultyDTO.setFaultPercentage(100);
                    faultyDTO.setTotalRequestCount(fault.getFaultCount());
                }
                faultyCount.add(faultyDTO);
            }
        }
    }
    return faultyCount;
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRdbmsClientImpl.java

/**
 * This method find the fault count of the APIs
 * @param providerName Name of the API provider
 * @param fromDate     starting date of the results
 * @param toDate       ending date of the results
 * @return list of APIResponseFaultCountDTO
 * @throws APIMgtUsageQueryServiceClientException throws if error occurred
 *//*from   ww w .  j  av  a 2s  .  c  o m*/
@Override
public List<APIResponseFaultCountDTO> getAPIResponseFaultCount(String providerName, String fromDate,
        String toDate) throws APIMgtUsageQueryServiceClientException {

    List<APIResponseFaultCount> faultyData = this.getAPIResponseFaultCountData(
            APIUsageStatisticsClientConstants.API_FAULT_SUMMARY, fromDate, toDate);
    List<API> providerAPIs = getAPIsByProvider(providerName);
    List<APIResponseFaultCountDTO> faultyCount = new ArrayList<APIResponseFaultCountDTO>();
    List<APIVersionUsageDTO> apiVersionUsageList;

    for (APIResponseFaultCount fault : faultyData) {
        for (API providerAPI : providerAPIs) {
            if (providerAPI.getId().getApiName().equals(fault.getApiName())
                    && providerAPI.getId().getVersion().equals(fault.getApiVersion())
                    && providerAPI.getContext().equals(fault.getContext())) {

                APIResponseFaultCountDTO faultyDTO = new APIResponseFaultCountDTO();
                faultyDTO.setApiName(fault.getApiName());
                faultyDTO.setVersion(fault.getApiVersion());
                faultyDTO.setContext(fault.getContext());
                faultyDTO.setCount(fault.getFaultCount());
                apiVersionUsageList = getUsageByAPIVersions(providerName, fault.getApiName(), fromDate, toDate);
                for (APIVersionUsageDTO apiVersionUsageDTO : apiVersionUsageList) {
                    if (apiVersionUsageDTO.getVersion().equals(fault.getApiVersion())) {
                        long requestCount = apiVersionUsageDTO.getCount();
                        double faultPercentage = ((double) requestCount - fault.getFaultCount()) / requestCount
                                * 100;
                        DecimalFormat twoDForm = new DecimalFormat("#.##");
                        NumberFormat numberFormat = NumberFormat.getInstance(Locale.getDefault());
                        try {
                            faultPercentage = 100
                                    - numberFormat.parse(twoDForm.format(faultPercentage)).doubleValue();
                        } catch (ParseException e) {
                            throw new APIMgtUsageQueryServiceClientException(
                                    "Parse exception while formatting time");
                        }
                        faultyDTO.setFaultPercentage(faultPercentage);
                        faultyDTO.setTotalRequestCount(requestCount);
                        break;
                    }
                }
                faultyCount.add(faultyDTO);
            }
        }
    }
    return faultyCount;
}

From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.java

@Override
public ItemBean getItem(ItemBean itemBean, String viewPK, EntityModel entityModel, boolean staging,
        String language) throws ServiceException {
    try {//  w w w  .  java 2s.  c o m
        String dateFormat = "yyyy-MM-dd"; //$NON-NLS-1$
        String dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss"; //$NON-NLS-1$

        String dataCluster = getCurrentDataCluster(staging);
        String dataModel = getCurrentDataModel();
        String concept = itemBean.getConcept();
        // get item
        WSDataClusterPK wsDataClusterPK = new WSDataClusterPK(dataCluster);
        String[] ids = CommonUtil.extractIdWithDots(entityModel.getKeys(), itemBean.getIds());

        // parse schema firstly, then use element declaration (DataModelHelper.getEleDecl)
        DataModelHelper.parseSchema(dataModel, concept, entityModel, LocalUser.getLocalUser().getRoles());

        WSItem wsItem = CommonUtil.getPort()
                .getItem(new WSGetItem(new WSItemPK(wsDataClusterPK, itemBean.getConcept(), ids)));
        itemBean.setItemXml(wsItem.getContent());
        extractUsingTransformerThroughView(concept, viewPK, ids, dataModel, dataCluster,
                DataModelHelper.getEleDecl(), itemBean);
        itemBean.set("time", wsItem.getInsertionTime()); //$NON-NLS-1$
        if (wsItem.getTaskId() != null && !"".equals(wsItem.getTaskId()) //$NON-NLS-1$
                && !"null".equals(wsItem.getTaskId())) { //$NON-NLS-1$
            itemBean.setTaskId(wsItem.getTaskId());
        }

        SimpleDateFormat sdf = null;
        Map<String, String[]> formatMap = this.checkDisplayFormat(entityModel, language);
        Set<String> keySet = formatMap.keySet();
        for (String key : keySet) {
            String[] value = formatMap.get(key);
            org.dom4j.Document doc = org.talend.mdm.webapp.base.server.util.XmlUtil
                    .parseText(itemBean.getItemXml());
            TypeModel tm = entityModel.getMetaDataTypes().get(key);
            String xpath = tm.getXpath();
            org.dom4j.Node node = null;
            if (!key.equals(xpath)) {
                Namespace namespace = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$//$NON-NLS-2$
                List<?> nodeList = doc.selectNodes(xpath);
                if (nodeList != null && nodeList.size() > 0) {
                    for (int i = 0; i < nodeList.size(); i++) {
                        org.dom4j.Element current = (org.dom4j.Element) nodeList.get(i);
                        String realType = current.getParent()
                                .attributeValue(new QName("type", namespace, "xsi:type")); //$NON-NLS-1$ //$NON-NLS-2$
                        if (key.replaceAll(":" + realType, "").equals(xpath)) { //$NON-NLS-1$//$NON-NLS-2$
                            node = current;
                            break;
                        }
                    }
                }
            } else {
                node = doc.selectSingleNode(key);
            }

            if (node != null && itemBean.getOriginalMap() != null) {
                String dataText = node.getText();

                if (dataText != null) {
                    if (dataText.trim().length() != 0) {
                        if (dateTypeNames.contains(tm.getType().getBaseTypeName())) {
                            if (value[1].equalsIgnoreCase("DATE")) { //$NON-NLS-1$
                                sdf = new SimpleDateFormat(dateFormat, java.util.Locale.ENGLISH);
                            } else if (value[1].equalsIgnoreCase("DATETIME")) { //$NON-NLS-1$
                                sdf = new SimpleDateFormat(dateTimeFormat, java.util.Locale.ENGLISH);
                            }

                            try {
                                Date date = sdf.parse(dataText.trim());
                                itemBean.getOriginalMap().put(key, date);
                                Calendar calendar = Calendar.getInstance();
                                calendar.setTime(date);
                                String formatValue = com.amalto.webapp.core.util.Util.formatDate(value[0],
                                        calendar);
                                itemBean.getFormateMap().put(key, formatValue);
                            } catch (Exception e) {
                                itemBean.getOriginalMap().remove(key);
                                itemBean.getFormateMap().remove(key);
                            }
                        } else if (numberTypeNames.contains(tm.getType().getBaseTypeName())) {
                            try {
                                NumberFormat nf = NumberFormat.getInstance();
                                Number num = nf.parse(dataText.trim());
                                String formatValue = ""; //$NON-NLS-1$
                                if (tm.getType().getBaseTypeName()
                                        .equals(DataTypeConstants.DOUBLE.getBaseTypeName())) {
                                    formatValue = String.format(value[0], num.doubleValue()).trim();
                                } else if (tm.getType().getBaseTypeName()
                                        .equals(DataTypeConstants.FLOAT.getBaseTypeName())) {
                                    formatValue = String.format(value[0], num.floatValue()).trim();
                                } else if (tm.getType().getBaseTypeName()
                                        .equals(DataTypeConstants.DECIMAL.getBaseTypeName())) {
                                    formatValue = String.format(value[0], new BigDecimal(dataText.trim()))
                                            .trim();
                                } else {
                                    formatValue = String.format(value[0], num).trim();
                                }
                                itemBean.getOriginalMap().put(key, num);
                                itemBean.getFormateMap().put(key, formatValue);
                            } catch (Exception e) {
                                itemBean.getOriginalMap().remove(key);
                                itemBean.getFormateMap().remove(key);
                            }
                        }
                    }
                }
            }
        }

        // dynamic Assemble
        dynamicAssemble(itemBean, entityModel, language);

        return itemBean;
    } catch (WebBaseException e) {
        throw new ServiceException(BASEMESSAGE.getMessage(new Locale(language), e.getMessage(), e.getArgs()));
    } catch (Exception exception) {
        String errorMessage;
        if (CoreException.class.isInstance(exception.getCause())) {
            CoreException webCoreException = (CoreException) exception.getCause();
            errorMessage = getErrorMessageFromWebCoreException(webCoreException, itemBean.getConcept(),
                    itemBean.getIds(), new Locale(language));
        } else {
            errorMessage = exception.getLocalizedMessage();
        }
        LOG.error(errorMessage, exception);
        throw new ServiceException(errorMessage);
    }
}

From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.java

private Object[] getItemBeans(String dataClusterPK, ViewBean viewBean, EntityModel entityModel, String criteria,
        int skip, int max, String sortDir, String sortCol, String language) throws Exception {

    int totalSize = 0;
    String dateFormat = "yyyy-MM-dd"; //$NON-NLS-1$
    String dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss"; //$NON-NLS-1$

    List<ItemBean> itemBeans = new ArrayList<ItemBean>();
    String concept = ViewHelper.getConceptFromDefaultViewName(viewBean.getViewPK());
    Map<String, String[]> formatMap = this.checkDisplayFormat(entityModel, language);

    WSWhereItem wi = null;//w w  w  .  ja va 2 s.  co  m
    if (criteria != null) {
        wi = CommonUtil.buildWhereItems(criteria);
    }
    String[] results = CommonUtil.getPort().viewSearch(new WSViewSearch(new WSDataClusterPK(dataClusterPK),
            new WSViewPK(viewBean.getViewPK()), wi, -1, skip, max, sortCol, sortDir)).getStrings();
    // set foreignKey's EntityModel
    Map<String, EntityModel> map = new HashMap<String, EntityModel>();
    if (results.length > 0 && viewBean.getViewableXpaths() != null) {
        for (String xpath : viewBean.getViewableXpaths()) {
            TypeModel typeModel = entityModel.getMetaDataTypes().get(xpath);
            if (typeModel != null && typeModel.getForeignkey() != null) {
                map.put(xpath, getEntityModel(typeModel.getForeignkey().split("/")[0], language)); //$NON-NLS-1$
            }
        }
    }
    // TODO change ids to array?
    List<String> idsArray = new ArrayList<String>();
    for (int i = 0; i < results.length; i++) {
        if (i == 0) {
            try {
                // Qizx doesn't wrap the count in a XML element, so try to parse it
                totalSize = Integer.parseInt(results[i]);
            } catch (NumberFormatException e) {
                totalSize = Integer.parseInt(com.amalto.webapp.core.util.Util.parse(results[i])
                        .getDocumentElement().getTextContent());
            }
            continue;
        }
        Document doc = parseResultDocument(results[i], "result"); //$NON-NLS-1$
        idsArray.clear();
        for (String key : entityModel.getKeys()) {
            String id = com.amalto.core.util.Util.getFirstTextNode(doc.getDocumentElement(),
                    "." + key.substring(key.lastIndexOf('/'))); //$NON-NLS-1$
            if (id != null) {
                idsArray.add(id);
            }
        }
        Set<String> keySet = formatMap.keySet();
        Map<String, Object> originalMap = new HashMap<String, Object>();
        Map<String, String> formateValueMap = new HashMap<String, String>();
        for (String key : keySet) {
            String[] value = formatMap.get(key);
            TypeModel tm = entityModel.getMetaDataTypes().get(key);
            String xpath = tm.getXpath();
            String dataText = null;
            if (!key.equals(xpath)) {
                NodeList list = com.amalto.core.util.Util.getNodeList(doc.getDocumentElement(),
                        xpath.replaceFirst(concept + "/", "./")); //$NON-NLS-1$//$NON-NLS-2$
                if (list != null) {
                    for (int k = 0; k < list.getLength(); k++) {
                        Node node = list.item(k);
                        String realType = ((Element) node.getParentNode()).getAttribute("xsi:type"); //$NON-NLS-1$
                        if (key.replaceAll(":" + realType, "").equals(xpath)) { //$NON-NLS-1$//$NON-NLS-2$
                            dataText = node.getTextContent();
                            break;
                        }
                    }
                }
            } else {
                dataText = com.amalto.core.util.Util.getFirstTextNode(doc.getDocumentElement(),
                        key.replaceFirst(concept + "/", "./")); //$NON-NLS-1$ //$NON-NLS-2$
            }

            if (dataText != null) {
                if (dataText.trim().length() != 0) {
                    if (dateTypeNames.contains(tm.getType().getBaseTypeName())) {
                        SimpleDateFormat sdf = null;
                        if (value[1].equalsIgnoreCase("DATE")) { //$NON-NLS-1$
                            sdf = new SimpleDateFormat(dateFormat, java.util.Locale.ENGLISH);
                        } else if (value[1].equalsIgnoreCase("DATETIME")) { //$NON-NLS-1$
                            sdf = new SimpleDateFormat(dateTimeFormat, java.util.Locale.ENGLISH);
                        }

                        try {
                            Date date = sdf.parse(dataText.trim());
                            originalMap.put(key, date);
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(date);
                            String formatValue = com.amalto.webapp.core.util.Util.formatDate(value[0],
                                    calendar);
                            formateValueMap.put(key, formatValue);
                            com.amalto.core.util.Util
                                    .getNodeList(doc.getDocumentElement(),
                                            key.replaceFirst(concept + "/", "./")) //$NON-NLS-1$//$NON-NLS-2$
                                    .item(0).setTextContent(formatValue);
                        } catch (Exception e) {
                            originalMap.remove(key);
                            formateValueMap.remove(key);
                        }
                    } else if (numberTypeNames.contains(tm.getType().getBaseTypeName())) {
                        try {
                            NumberFormat nf = NumberFormat.getInstance();
                            Number num = nf.parse(dataText.trim());
                            String formatValue = ""; //$NON-NLS-1$
                            if (tm.getType().getBaseTypeName()
                                    .equals(DataTypeConstants.DOUBLE.getBaseTypeName())) {
                                formatValue = String.format(value[0], num.doubleValue()).trim();
                            } else if (tm.getType().getBaseTypeName()
                                    .equals(DataTypeConstants.FLOAT.getBaseTypeName())) {
                                formatValue = String.format(value[0], num.floatValue()).trim();
                            } else if (tm.getType().getBaseTypeName()
                                    .equals(DataTypeConstants.DECIMAL.getBaseTypeName())) {
                                formatValue = String.format(value[0], new BigDecimal(dataText.trim())).trim();
                            } else {
                                formatValue = String.format(value[0], num).trim();
                            }

                            originalMap.put(key, num);
                            formateValueMap.put(key, formatValue);
                            com.amalto.core.util.Util
                                    .getNodeList(doc.getDocumentElement(),
                                            key.replaceFirst(concept + "/", "./")) //$NON-NLS-1$//$NON-NLS-2$
                                    .item(0).setTextContent(formatValue);
                        } catch (Exception e) {
                            Log.info("format has error 111"); //$NON-NLS-1$
                            originalMap.remove(key);
                            formateValueMap.remove(key);
                        }
                    }
                }
            }
        }

        ItemBean itemBean = new ItemBean(concept, CommonUtil.joinStrings(idsArray, "."), //$NON-NLS-1$
                XMLUtils.nodeToString(doc.getDocumentElement(), true, true));
        itemBean.setOriginalMap(originalMap);
        itemBean.setFormateMap(formateValueMap);
        if (checkSmartViewExistsByLang(concept, language)) {
            itemBean.setSmartViewMode(ItemBean.SMARTMODE);
        } else if (checkSmartViewExistsByOpt(concept, language)) {
            itemBean.setSmartViewMode(ItemBean.PERSOMODE);
        }
        dynamicAssembleByResultOrder(itemBean, viewBean, entityModel, map, language);
        itemBeans.add(itemBean);
    }
    return new Object[] { itemBeans, totalSize };
}