Example usage for org.apache.commons.lang3.math NumberUtils isNumber

List of usage examples for org.apache.commons.lang3.math NumberUtils isNumber

Introduction

In this page you can find the example usage for org.apache.commons.lang3.math NumberUtils isNumber.

Prototype

public static boolean isNumber(final String str) 

Source Link

Document

Checks whether the String a valid Java number.

Valid numbers include hexadecimal marked with the 0x or 0X qualifier, octal numbers, scientific notation and numbers marked with a type qualifier (e.g.

Usage

From source file:nz.co.fortytwo.freeboard.server.FreeboardProcessor.java

/**
 * Converts a msg string into a hashmap//from   w w w.j  av a 2  s .  co  m
 * @param msg
 * @return
 */
public HashMap<String, Object> stringToHashMap(String msg) {
    if (logger.isDebugEnabled())
        logger.debug("Mesg to map:" + msg);
    HashMap<String, Object> map = new HashMap<String, Object>();
    //AIS
    //!AIVDM,1,1,,B,15MwkRUOidG?GElEa<iQk1JV06Jd,0*6D
    if (msg.startsWith("$")) {
        if (logger.isDebugEnabled())
            logger.debug("Mesg to NMEA in map:" + msg);
        map.put(Constants.NMEA, msg);
    } else if (msg.startsWith("!AIVDM")) {
        if (logger.isDebugEnabled())
            logger.debug("Mesg to NMEA in map:" + msg);
        map.put(Constants.AIS, msg);
    } else {
        if (logger.isDebugEnabled())
            logger.debug("Mesg split in map:" + msg);
        String[] bodyArray = msg.split(",");
        //reuse
        String[] pair;
        for (String s : bodyArray) {
            if (StringUtils.isNotBlank(s)) {
                pair = s.split(":");
                if (pair == null || pair.length != 2)
                    continue;

                if (NumberUtils.isNumber(pair[1])) {
                    Object val;
                    if (pair[1].indexOf(".") > 0) {
                        val = Double.valueOf(pair[1]);
                    } else {
                        val = Integer.valueOf(pair[1]);
                    }
                    map.put(pair[0], val);
                } else {
                    map.put(pair[0], pair[1]);
                }
            }
        }
    }
    return map;
}

From source file:nz.co.fortytwo.freeboard.zk.ConfigViewModel.java

@Listen("onClick = button#cfgSave")
public void cfgSaveClick(MouseEvent event) {
    if (logger.isDebugEnabled()) {
        logger.debug(" cfgSave button event = " + event);
    }//from   w  w w.java 2 s  .c o m
    try {
        Properties config = Util.getConfig(null);
        if (isValidPort(portsToScan.getText())) {
            config.setProperty(Constants.SERIAL_PORTS, portsToScan.getValue());
        } else {
            Messagebox.show(
                    "Device ports to scan is invalid. In Linux (pi) '/dev/ttyUSB0,/dev/ttyUSB1,etc', in MS Windows 'COM1,COM2,COM3,etc'");
        }
        if (isValidBaudRate(portBaudRate.getValue())) {
            config.setProperty(Constants.SERIAL_PORT_BAUD, portBaudRate.getValue());
            Util.saveConfig();
        } else {
            Messagebox.show("Device baud rate (speed) must be one of 4800,9600,19200,38400,57600");
        }
        if (NumberUtils.isNumber(cfgWindOffset.getValue())) {
            config.setProperty(Constants.WIND_ZERO_OFFSET, cfgWindOffset.getValue());
            Util.saveConfig();
            // notify others
            producer.sendBody(Constants.WIND_ZERO_ADJUST_CMD + ":" + cfgWindOffset.getValue() + ",");
        } else {
            Messagebox.show("Wind offset must be numeric");
        }

        config.setProperty(Constants.PREFER_RMC, (String) useRmcGroup.getSelectedItem().getValue());
        config.setProperty(Constants.DNS_USE_CHOICE, (String) useHomeGroup.getSelectedItem().getValue());

        if (NumberUtils.isNumber(cfgDepthOffset.getValue())) {

            config.setProperty(Constants.DEPTH_ZERO_OFFSET, cfgDepthOffset.getValue());
            // notify others
            producer.sendBody(Constants.DEPTH_ZERO_ADJUST_CMD + ":" + cfgDepthOffset.getValue() + ",");
        } else {
            Messagebox.show("Depth offset must be numeric");
        }
        config.setProperty(Constants.PREFER_RMC, (String) useRmcGroup.getSelectedItem().getValue());
        config.setProperty(Constants.SOG_UNIT, (String) (cfgSOGUnit.getSelectedItem().getValue()));
        config.setProperty(Constants.SOW_UNIT, (String) (cfgSOWUnit.getSelectedItem().getValue()));
        config.setProperty(Constants.DEPTH_UNIT, (String) (cfgDepthUnit.getSelectedItem().getValue()));
        Util.saveConfig();

        if (NumberUtils.isNumber(cfgAlarmDepth.getValue())) {
            config.setProperty(Constants.ALARM_DEPTH, cfgAlarmDepth.getValue());
            Util.saveConfig();

        } else {
            Messagebox.show("Alarm depth must be numeric");
        }

        //            if (NumberUtils.isNumber(cfgSparklinePts.getValue())) {
        //                config.setProperty(Constants.SPARKLINE_PTS, cfgSparklinePts.getValue());
        //                Util.saveConfig();
        //            } else {
        //                Messagebox.show("Sparkline points must be numeric");
        //            }
        if (NumberUtils.isNumber(cfgSparklineMin.getValue())) {
            config.setProperty(Constants.SPARKLINE_MIN, cfgSparklineMin.getValue());
            Util.saveConfig();
        } else {
            Messagebox.show("Sparkline minimum must be numeric");
        }
        if (NumberUtils.isNumber(radiiBoatCircles.getValue())) {
            config.setProperty(Constants.RADII_BOAT_CIRCLES, radiiBoatCircles.getValue());
            Util.saveConfig();
        } else {
            Messagebox.show("Boat circle radii minimum must be numeric (m)");
        }
        if (NumberUtils.isNumber(numBoatCircles.getValue())) {
            config.setProperty(Constants.NUM_BOAT_CIRCLES, numBoatCircles.getValue());
            Util.saveConfig();
        } else {
            Messagebox.show("Number of Boat Circles must be numeric");
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

}

From source file:nz.co.fortytwo.freeboard.zk.ConfigViewModel.java

private boolean isValidBaudRate(String value) {
    if (!NumberUtils.isNumber(value)) {
        return false;
    }/*from   ww w. java  2  s  .  c  om*/
    int rate = Integer.valueOf(value);
    if (rate == 4800 || rate == 9600 || rate == 19200 || rate == 38400 || rate == 57600) {
        return true;
    }
    return false;
}

From source file:nz.co.fortytwo.signalk.util.Util.java

public static SignalKModel populateModel(SignalKModel model, String mapDump) throws IOException {
    Properties props = new Properties();
    props.load(new StringReader(mapDump.substring(1, mapDump.length() - 1).replace(", ", "\n")));
    for (Map.Entry<Object, Object> e : props.entrySet()) {
        if (e.getValue().equals("true") || e.getValue().equals("false")) {
            model.put((String) e.getKey(), Boolean.getBoolean((String) e.getValue()));
        } else if (NumberUtils.isNumber((String) e.getValue())) {
            model.put((String) e.getKey(), NumberUtils.createDouble((String) e.getValue()));
        } else {//from ww  w  . j a v  a 2 s.  c  o m
            model.put((String) e.getKey(), e.getValue());
        }
    }
    return model;
}

From source file:org.activiti.app.service.util.TaskUtil.java

public static void fillPermissionInformation(TaskRepresentation taskRepresentation, TaskInfo task,
        User currentUser, IdentityService identityService, HistoryService historyService,
        RepositoryService repositoryService) {

    String processInstanceStartUserId = null;
    boolean initiatorCanCompleteTask = true;
    boolean isMemberOfCandidateGroup = false;
    boolean isMemberOfCandidateUsers = false;

    if (task.getProcessInstanceId() != null) {

        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(task.getProcessInstanceId()).singleResult();

        if (historicProcessInstance != null
                && StringUtils.isNotEmpty(historicProcessInstance.getStartUserId())) {
            processInstanceStartUserId = historicProcessInstance.getStartUserId();
            BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
            FlowElement flowElement = bpmnModel.getFlowElement(task.getTaskDefinitionKey());
            if (flowElement != null && flowElement instanceof UserTask) {
                UserTask userTask = (UserTask) flowElement;
                List<ExtensionElement> extensionElements = userTask.getExtensionElements()
                        .get("initiator-can-complete");
                if (CollectionUtils.isNotEmpty(extensionElements)) {
                    String value = extensionElements.get(0).getElementText();
                    if (StringUtils.isNotEmpty(value)) {
                        initiatorCanCompleteTask = Boolean.valueOf(value);
                    }// ww w . j av a2 s . c  o m
                }

                Map<String, Object> variableMap = new HashMap<String, Object>();
                if ((CollectionUtils.isNotEmpty(userTask.getCandidateGroups())
                        && userTask.getCandidateGroups().size() == 1
                        && userTask.getCandidateGroups().get(0)
                                .contains("${taskAssignmentBean.assignTaskToCandidateGroups('"))
                        || (CollectionUtils.isNotEmpty(userTask.getCandidateUsers())
                                && userTask.getCandidateUsers().size() == 1
                                && userTask.getCandidateUsers().get(0)
                                        .contains("${taskAssignmentBean.assignTaskToCandidateUsers('"))) {

                    List<HistoricVariableInstance> processVariables = historyService
                            .createHistoricVariableInstanceQuery()
                            .processInstanceId(task.getProcessInstanceId()).list();
                    if (CollectionUtils.isNotEmpty(processVariables)) {
                        for (HistoricVariableInstance historicVariableInstance : processVariables) {
                            variableMap.put(historicVariableInstance.getVariableName(),
                                    historicVariableInstance.getValue());
                        }
                    }
                }

                if (CollectionUtils.isNotEmpty(userTask.getCandidateGroups())) {
                    List<Group> groups = identityService.createGroupQuery().groupMember(currentUser.getId())
                            .list();
                    if (CollectionUtils.isNotEmpty(groups)) {

                        List<String> groupIds = new ArrayList<String>();
                        if (userTask.getCandidateGroups().size() == 1 && userTask.getCandidateGroups().get(0)
                                .contains("${taskAssignmentBean.assignTaskToCandidateGroups('")) {

                            String candidateGroupString = userTask.getCandidateGroups().get(0);
                            candidateGroupString = candidateGroupString
                                    .replace("${taskAssignmentBean.assignTaskToCandidateGroups('", "");
                            candidateGroupString = candidateGroupString.replace("', execution)}", "");
                            String groupsArray[] = candidateGroupString.split(",");
                            for (String group : groupsArray) {
                                if (group.contains("field(")) {
                                    String fieldCandidate = group.trim().substring(6, group.length() - 1);
                                    Object fieldValue = variableMap.get(fieldCandidate);
                                    if (fieldValue != null && NumberUtils.isNumber(fieldValue.toString())) {
                                        groupIds.add(fieldValue.toString());
                                    }

                                } else {
                                    groupIds.add(group);
                                }
                            }

                        } else {
                            groupIds.addAll(userTask.getCandidateGroups());
                        }

                        for (Group group : groups) {
                            if (groupIds.contains(String.valueOf(group.getId()))) {
                                isMemberOfCandidateGroup = true;
                                break;
                            }
                        }
                    }
                }

                if (CollectionUtils.isNotEmpty(userTask.getCandidateUsers())) {
                    if (userTask.getCandidateUsers().size() == 1 && userTask.getCandidateUsers().get(0)
                            .contains("${taskAssignmentBean.assignTaskToCandidateUsers('")) {

                        String candidateUserString = userTask.getCandidateUsers().get(0);
                        candidateUserString = candidateUserString
                                .replace("${taskAssignmentBean.assignTaskToCandidateUsers('", "");
                        candidateUserString = candidateUserString.replace("', execution)}", "");
                        String users[] = candidateUserString.split(",");
                        for (String user : users) {
                            if (user.contains("field(")) {
                                String fieldCandidate = user.substring(6, user.length() - 1);
                                Object fieldValue = variableMap.get(fieldCandidate);
                                if (fieldValue != null && NumberUtils.isNumber(fieldValue.toString())
                                        && String.valueOf(currentUser.getId()).equals(fieldValue.toString())) {

                                    isMemberOfCandidateGroup = true;
                                    break;
                                }

                            } else if (user.equals(String.valueOf(currentUser.getId()))) {
                                isMemberOfCandidateGroup = true;
                                break;
                            }
                        }

                    } else if (userTask.getCandidateUsers().contains(String.valueOf(currentUser.getId()))) {
                        isMemberOfCandidateUsers = true;
                    }
                }
            }
        }
    }

    taskRepresentation.setProcessInstanceStartUserId(processInstanceStartUserId);
    taskRepresentation.setInitiatorCanCompleteTask(initiatorCanCompleteTask);
    taskRepresentation.setMemberOfCandidateGroup(isMemberOfCandidateGroup);
    taskRepresentation.setMemberOfCandidateUsers(isMemberOfCandidateUsers);
}

From source file:org.activiti.form.engine.impl.cmd.GetVariablesFromFormSubmissionCmd.java

@SuppressWarnings("unchecked")
protected Object transformFormFieldValueToVariableValue(FormField formField, Object formFieldValue) {

    Object result = formFieldValue;
    if (formField.getType().equals(FormFieldTypes.DATE)) {
        if (StringUtils.isNotEmpty((String) formFieldValue)) {
            try {
                result = LocalDate.parse((String) formFieldValue);

            } catch (Exception e) {
                e.printStackTrace();// w w w.  ja  v  a 2 s  .c o  m
                result = null;
            }
        }

    } else if (formField.getType().equals(FormFieldTypes.INTEGER) && formFieldValue instanceof String) {
        String strFieldValue = (String) formFieldValue;
        if (StringUtils.isNotEmpty(strFieldValue) && NumberUtils.isNumber(strFieldValue)) {
            result = Long.valueOf(strFieldValue);

        } else {
            result = (Long) null;
        }

    } else if (formField.getType().equals(FormFieldTypes.AMOUNT) && formFieldValue instanceof String) {
        try {
            result = Double.parseDouble((String) formFieldValue);

        } catch (NumberFormatException e) {
            result = null;
        }

    } else if (formField.getType().equals(FormFieldTypes.DROPDOWN)) {
        if (formFieldValue != null && formFieldValue instanceof Map<?, ?>) {
            result = ((Map<?, ?>) formFieldValue).get("id");
            if (result == null) {
                // fallback to name for manual config options
                result = ((Map<?, ?>) formFieldValue).get("name");
            }
        }

    } else if (formField.getType().equals(FormFieldTypes.UPLOAD)) {
        result = (String) formFieldValue;

    } else if (formField.getType().equals(FormFieldTypes.PEOPLE)
            || formField.getType().equals(FormFieldTypes.FUNCTIONAL_GROUP)) {
        if (formFieldValue != null && formFieldValue instanceof Map<?, ?>) {
            Map<String, Object> value = (Map<String, Object>) formFieldValue;
            Object id = value.get("id");
            if (id instanceof Number) {
                result = ((Number) id).longValue();

            } else {
                // Wrong type, ignore
                result = null;
            }
        } else {
            // Incorrect or empty map, ignore
            result = null;
        }
    }

    // Default: no processing needs to be done, can be stored as-is
    return result;
}

From source file:org.apache.flink.api.java.utils.ParameterTool.java

/**
 * Returns {@link ParameterTool} for the given arguments. The arguments are keys followed by values.
 * Keys have to start with '-' or '--'/*from w  ww .ja v a  2  s. co m*/
 * <p>
 * <strong>Example arguments:</strong>
 * --key1 value1 --key2 value2 -key3 value3
 *
 * @param args Input array arguments
 * @return A {@link ParameterTool}
 */
public static ParameterTool fromArgs(String[] args) {
    Map<String, String> map = new HashMap<String, String>(args.length / 2);

    String key = null;
    String value = null;
    boolean expectValue = false;
    for (String arg : args) {
        // check for -- argument
        if (arg.startsWith("--")) {
            if (expectValue) {
                // we got into a new key, even though we were a value --> current key is one without value
                if (value != null) {
                    throw new IllegalStateException("Unexpected state");
                }
                map.put(key, NO_VALUE_KEY);
                // key will be overwritten in the next step
            }
            key = arg.substring(2);
            expectValue = true;
        } // check for - argument
        else if (arg.startsWith("-")) {
            // we are waiting for a value, so this is a - prefixed value (negative number)
            if (expectValue) {

                if (NumberUtils.isNumber(arg)) {
                    // negative number
                    value = arg;
                    expectValue = false;
                } else {
                    if (value != null) {
                        throw new IllegalStateException("Unexpected state");
                    }
                    // We waited for a value but found a new key. So the previous key doesnt have a value.
                    map.put(key, NO_VALUE_KEY);
                    key = arg.substring(1);
                    expectValue = true;
                }
            } else {
                // we are not waiting for a value, so its an argument
                key = arg.substring(1);
                expectValue = true;
            }
        } else {
            if (expectValue) {
                value = arg;
                expectValue = false;
            } else {
                throw new RuntimeException("Error parsing arguments '" + Arrays.toString(args) + "' on '" + arg
                        + "'. Unexpected value. Please prefix values with -- or -.");
            }
        }

        if (value == null && key == null) {
            throw new IllegalStateException("Value and key can not be null at the same time");
        }
        if (key != null && value == null && !expectValue) {
            throw new IllegalStateException("Value expected but flag not set");
        }
        if (key != null && value != null) {
            map.put(key, value);
            key = null;
            value = null;
            expectValue = false;
        }
        if (key != null && key.length() == 0) {
            throw new IllegalArgumentException(
                    "The input " + Arrays.toString(args) + " contains an empty argument");
        }

        if (key != null && !expectValue) {
            map.put(key, NO_VALUE_KEY);
            key = null;
            expectValue = false;
        }
    }
    if (key != null) {
        map.put(key, NO_VALUE_KEY);
    }

    return fromMap(map);
}

From source file:org.apache.marmotta.kiwi.loader.mysql.MySQLLoadUtil.java

public static InputStream flushNodes(Iterable<KiWiNode> nodeBacklog) throws IOException {
    StringWriter out = new StringWriter();
    CsvListWriter writer = new CsvListWriter(out, nodesPreference);

    // reuse the same array to avoid unnecessary object allocation
    Object[] rowArray = new Object[11];
    List<Object> row = Arrays.asList(rowArray);

    for (KiWiNode n : nodeBacklog) {
        if (n instanceof KiWiUriResource) {
            KiWiUriResource u = (KiWiUriResource) n;
            createNodeList(rowArray, u.getId(), u.getClass(), u.stringValue(), null, null, null, null, null,
                    null, null, u.getCreated());
        } else if (n instanceof KiWiAnonResource) {
            KiWiAnonResource a = (KiWiAnonResource) n;
            createNodeList(rowArray, a.getId(), a.getClass(), a.stringValue(), null, null, null, null, null,
                    null, null, a.getCreated());
        } else if (n instanceof KiWiIntLiteral) {
            KiWiIntLiteral l = (KiWiIntLiteral) n;
            createNodeList(rowArray, l.getId(), l.getClass(), l.getContent(), l.getDoubleContent(),
                    l.getIntContent(), null, null, null, l.getDatatype(), l.getLocale(), l.getCreated());
        } else if (n instanceof KiWiDoubleLiteral) {
            KiWiDoubleLiteral l = (KiWiDoubleLiteral) n;
            createNodeList(rowArray, l.getId(), l.getClass(), l.getContent(), l.getDoubleContent(), null, null,
                    null, null, l.getDatatype(), l.getLocale(), l.getCreated());
        } else if (n instanceof KiWiBooleanLiteral) {
            KiWiBooleanLiteral l = (KiWiBooleanLiteral) n;
            createNodeList(rowArray, l.getId(), l.getClass(), l.getContent(), null, null, null, null,
                    l.booleanValue(), l.getDatatype(), l.getLocale(), l.getCreated());
        } else if (n instanceof KiWiDateLiteral) {
            KiWiDateLiteral l = (KiWiDateLiteral) n;
            createNodeList(rowArray, l.getId(), l.getClass(), l.getContent(), null, null, l.getDateContent(),
                    l.getDateContent().getZone().getOffset(l.getDateContent()) / 1000, null, l.getDatatype(),
                    l.getLocale(), l.getCreated());
        } else if (n instanceof KiWiStringLiteral) {
            KiWiStringLiteral l = (KiWiStringLiteral) n;

            Double dbl_value = null;
            Long lng_value = null;
            if (l.getContent().length() < 64 && NumberUtils.isNumber(l.getContent())) {
                try {
                    dbl_value = Double.parseDouble(l.getContent());
                    lng_value = Long.parseLong(l.getContent());
                } catch (NumberFormatException ex) {
                    // ignore, keep NaN
                }/*from   w w  w  .  j a va2  s  .  c  o  m*/
            }
            createNodeList(rowArray, l.getId(), l.getClass(), l.getContent(), dbl_value, lng_value, null, null,
                    null, l.getDatatype(), l.getLocale(), l.getCreated());
        } else {
            log.warn("unknown node type, cannot flush to import stream: {}", n.getClass());
        }

        writer.write(row, nodeProcessors);
    }
    writer.close();

    return IOUtils.toInputStream(out.toString());
}

From source file:org.apache.marmotta.kiwi.loader.pgsql.PGCopyUtil.java

public static void flushNodes(Iterable<KiWiNode> nodeBacklog, OutputStream out) throws IOException {
    CsvListWriter writer = new CsvListWriter(new OutputStreamWriter(out), nodesPreference);

    // reuse the same array to avoid unnecessary object allocation
    Object[] rowArray = new Object[11];
    List<Object> row = Arrays.asList(rowArray);

    for (KiWiNode n : nodeBacklog) {
        if (n instanceof KiWiUriResource) {
            KiWiUriResource u = (KiWiUriResource) n;
            createNodeList(rowArray, u.getId(), u.getClass(), u.stringValue(), null, null, null, null, null,
                    null, null, u.getCreated());
        } else if (n instanceof KiWiAnonResource) {
            KiWiAnonResource a = (KiWiAnonResource) n;
            createNodeList(rowArray, a.getId(), a.getClass(), a.stringValue(), null, null, null, null, null,
                    null, null, a.getCreated());
        } else if (n instanceof KiWiIntLiteral) {
            KiWiIntLiteral l = (KiWiIntLiteral) n;
            createNodeList(rowArray, l.getId(), l.getClass(), l.getContent(), l.getDoubleContent(),
                    l.getIntContent(), null, null, null, l.getDatatype(), l.getLocale(), l.getCreated());
        } else if (n instanceof KiWiDoubleLiteral) {
            KiWiDoubleLiteral l = (KiWiDoubleLiteral) n;
            createNodeList(rowArray, l.getId(), l.getClass(), l.getContent(), l.getDoubleContent(), null, null,
                    null, null, l.getDatatype(), l.getLocale(), l.getCreated());
        } else if (n instanceof KiWiBooleanLiteral) {
            KiWiBooleanLiteral l = (KiWiBooleanLiteral) n;
            createNodeList(rowArray, l.getId(), l.getClass(), l.getContent(), null, null, null, null,
                    l.booleanValue(), l.getDatatype(), l.getLocale(), l.getCreated());
        } else if (n instanceof KiWiDateLiteral) {
            KiWiDateLiteral l = (KiWiDateLiteral) n;
            createNodeList(rowArray, l.getId(), l.getClass(), l.getContent(), null, null, l.getDateContent(),
                    l.getDateContent().getZone().getOffset(l.getDateContent()) / 1000, null, l.getDatatype(),
                    l.getLocale(), l.getCreated());
        } else if (n instanceof KiWiStringLiteral) {
            KiWiStringLiteral l = (KiWiStringLiteral) n;

            Double dbl_value = null;
            Long lng_value = null;
            if (l.getContent().length() < 64 && NumberUtils.isNumber(l.getContent())) {
                try {
                    dbl_value = Double.parseDouble(l.getContent());
                    lng_value = Long.parseLong(l.getContent());
                } catch (NumberFormatException ex) {
                    // ignore, keep NaN
                }//w  w w  . jav a 2s  .  co  m
            }
            createNodeList(rowArray, l.getId(), l.getClass(), l.getContent(), dbl_value, lng_value, null, null,
                    null, l.getDatatype(), l.getLocale(), l.getCreated());
        } else {
            log.warn("unknown node type, cannot flush to import stream: {}", n.getClass());
        }

        writer.write(row, nodeProcessors);
    }
    writer.close();
}

From source file:org.apache.marmotta.kiwi.persistence.KiWiConnection.java

/**
 * Store a new node in the database. The method will retrieve a new database id for the node and update the
 * passed object. Afterwards, the node data will be inserted into the database using appropriate INSERT
 * statements. The caller must make sure the connection is committed and closed properly.
 * <p/>/*from  w w  w.  java2s.  c o m*/
 * If the node already has an ID, the method will do nothing (assuming that it is already persistent)
 *
 *
 * @param node
 * @throws SQLException
 */
public synchronized void storeNode(KiWiNode node) throws SQLException {

    // ensure the data type of a literal is persisted first
    if (node instanceof KiWiLiteral) {
        KiWiLiteral literal = (KiWiLiteral) node;
        if (literal.getType() != null && literal.getType().getId() < 0) {
            storeNode(literal.getType());
        }
    }

    requireJDBCConnection();

    // retrieve a new node id and set it in the node object
    if (node.getId() < 0) {
        node.setId(getNextSequence());
    }

    // distinguish the different node types and run the appropriate updates
    if (node instanceof KiWiUriResource) {
        KiWiUriResource uriResource = (KiWiUriResource) node;

        PreparedStatement insertNode = getPreparedStatement("store.uri");
        insertNode.setLong(1, node.getId());
        insertNode.setString(2, uriResource.stringValue());
        insertNode.setTimestamp(3, new Timestamp(uriResource.getCreated().getTime()), calendarUTC);

        insertNode.executeUpdate();

    } else if (node instanceof KiWiAnonResource) {
        KiWiAnonResource anonResource = (KiWiAnonResource) node;

        PreparedStatement insertNode = getPreparedStatement("store.bnode");
        insertNode.setLong(1, node.getId());
        insertNode.setString(2, anonResource.stringValue());
        insertNode.setTimestamp(3, new Timestamp(anonResource.getCreated().getTime()), calendarUTC);

        insertNode.executeUpdate();
    } else if (node instanceof KiWiDateLiteral) {
        KiWiDateLiteral dateLiteral = (KiWiDateLiteral) node;

        PreparedStatement insertNode = getPreparedStatement("store.tliteral");
        insertNode.setLong(1, node.getId());
        insertNode.setString(2, dateLiteral.stringValue());
        insertNode.setTimestamp(3, new Timestamp(dateLiteral.getDateContent().getMillis()), calendarUTC);
        insertNode.setInt(4,
                dateLiteral.getDateContent().getZone().getOffset(dateLiteral.getDateContent()) / 1000);
        if (dateLiteral.getType() != null)
            insertNode.setLong(5, dateLiteral.getType().getId());
        else
            throw new IllegalStateException("a date literal must have a datatype");
        insertNode.setTimestamp(6, new Timestamp(dateLiteral.getCreated().getTime()), calendarUTC);

        insertNode.executeUpdate();
    } else if (node instanceof KiWiIntLiteral) {
        KiWiIntLiteral intLiteral = (KiWiIntLiteral) node;

        PreparedStatement insertNode = getPreparedStatement("store.iliteral");
        insertNode.setLong(1, node.getId());
        insertNode.setString(2, intLiteral.getContent());
        insertNode.setDouble(3, intLiteral.getDoubleContent());
        insertNode.setLong(4, intLiteral.getIntContent());
        if (intLiteral.getType() != null)
            insertNode.setLong(5, intLiteral.getType().getId());
        else
            throw new IllegalStateException("an integer literal must have a datatype");
        insertNode.setTimestamp(6, new Timestamp(intLiteral.getCreated().getTime()), calendarUTC);

        insertNode.executeUpdate();
    } else if (node instanceof KiWiDoubleLiteral) {
        KiWiDoubleLiteral doubleLiteral = (KiWiDoubleLiteral) node;

        PreparedStatement insertNode = getPreparedStatement("store.dliteral");
        insertNode.setLong(1, node.getId());
        insertNode.setString(2, doubleLiteral.getContent());
        insertNode.setDouble(3, doubleLiteral.getDoubleContent());
        if (doubleLiteral.getType() != null)
            insertNode.setLong(4, doubleLiteral.getType().getId());
        else
            throw new IllegalStateException("a double literal must have a datatype");
        insertNode.setTimestamp(5, new Timestamp(doubleLiteral.getCreated().getTime()), calendarUTC);

        insertNode.executeUpdate();
    } else if (node instanceof KiWiBooleanLiteral) {
        KiWiBooleanLiteral booleanLiteral = (KiWiBooleanLiteral) node;

        PreparedStatement insertNode = getPreparedStatement("store.bliteral");
        insertNode.setLong(1, node.getId());
        insertNode.setString(2, booleanLiteral.getContent());
        insertNode.setBoolean(3, booleanLiteral.booleanValue());
        if (booleanLiteral.getType() != null)
            insertNode.setLong(4, booleanLiteral.getType().getId());
        else
            throw new IllegalStateException("a boolean literal must have a datatype");
        insertNode.setTimestamp(5, new Timestamp(booleanLiteral.getCreated().getTime()), calendarUTC);

        insertNode.executeUpdate();
    } else if (node instanceof KiWiStringLiteral) {
        KiWiStringLiteral stringLiteral = (KiWiStringLiteral) node;

        Double dbl_value = null;
        Long lng_value = null;
        if (stringLiteral.getContent().length() < 64 && NumberUtils.isNumber(stringLiteral.getContent()))
            try {
                dbl_value = Double.parseDouble(stringLiteral.getContent());
                lng_value = Long.parseLong(stringLiteral.getContent());
            } catch (NumberFormatException ex) {
                // ignore, keep NaN
            }

        PreparedStatement insertNode = getPreparedStatement("store.sliteral");
        insertNode.setLong(1, node.getId());
        insertNode.setString(2, stringLiteral.getContent());
        if (dbl_value != null) {
            insertNode.setDouble(3, dbl_value);
        } else {
            insertNode.setObject(3, null);
        }
        if (lng_value != null) {
            insertNode.setLong(4, lng_value);
        } else {
            insertNode.setObject(4, null);
        }

        if (stringLiteral.getLocale() != null) {
            insertNode.setString(5, stringLiteral.getLocale().getLanguage().toLowerCase());
        } else {
            insertNode.setObject(5, null);
        }
        if (stringLiteral.getType() != null) {
            insertNode.setLong(6, stringLiteral.getType().getId());
        } else {
            insertNode.setObject(6, null);
        }
        insertNode.setTimestamp(7, new Timestamp(stringLiteral.getCreated().getTime()), calendarUTC);

        insertNode.executeUpdate();
    } else {
        log.warn("unrecognized node type: {}", node.getClass().getCanonicalName());
    }

    cacheNode(node);
}