Example usage for org.apache.commons.lang ArrayUtils toPrimitive

List of usage examples for org.apache.commons.lang ArrayUtils toPrimitive

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils toPrimitive.

Prototype

public static boolean[] toPrimitive(Boolean[] array) 

Source Link

Document

Converts an array of object Booleans to primitives.

Usage

From source file:org.neo4j.nlp.impl.util.VectorUtil.java

public static double getFeatureMatchDistribution(GraphDatabaseService db, Long patternId) {
    Transaction tx = db.beginTx();//  w  w  w . j a  v  a 2s. c o m
    Node startNode = db.getNodeById(patternId);

    // Feature match distribution
    List<Double> matches = IteratorUtil
            .asCollection(db.traversalDescription().depthFirst()
                    .relationships(withName("HAS_CLASS"), Direction.OUTGOING).evaluator(Evaluators.fromDepth(1))
                    .evaluator(Evaluators.toDepth(1)).traverse(startNode).relationships())
            .stream().map(p -> ((Integer) p.getProperty("matches")).doubleValue()).collect(Collectors.toList());

    tx.success();
    tx.close();

    double variance = 1.0;

    if (matches.size() > 1) {
        Double[] matchArr = matches.toArray(new Double[matches.size()]);
        // Get the standard deviation
        DescriptiveStatistics ds = new DescriptiveStatistics();
        matches.forEach(m -> ds.addValue(m.doubleValue() / StatUtils.sum(ArrayUtils.toPrimitive(matchArr))));
        variance = ds.getStandardDeviation();
    }

    return variance;
}

From source file:org.nuxeo.ecm.platform.convert.ooomanager.OOoManagerComponent.java

@Override
public void startOOoManager() throws IOException {
    DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();

    starting = true;//  w w  w  . j  a  v  a2  s .com

    try {
        // Properties configuration
        String connectionProtocol = Framework.getProperty(CONNECTION_PROTOCOL_PROPERTY_KEY);
        if (connectionProtocol != null && !"".equals(connectionProtocol)) {
            if (OfficeConnectionProtocol.PIPE.toString().equals(connectionProtocol)) {
                ConfigBuilderHelper.hackClassLoader();
                configuration.setConnectionProtocol(OfficeConnectionProtocol.PIPE);
            } else if (OfficeConnectionProtocol.SOCKET.toString().equals(connectionProtocol)) {
                configuration.setConnectionProtocol(OfficeConnectionProtocol.SOCKET);
            }
        }
        String maxTasksPerProcessProperty = Framework.getProperty(MAX_TASKS_PER_PROCESS_PROPERTY_KEY);
        if (maxTasksPerProcessProperty != null && !"".equals(maxTasksPerProcessProperty)) {
            Integer maxTasksPerProcess = Integer.valueOf(maxTasksPerProcessProperty);
            configuration.setMaxTasksPerProcess(maxTasksPerProcess);
        }
        String officeHome = Framework.getProperty(OFFICE_HOME_PROPERTY_KEY);
        if (officeHome != null && !"".equals(officeHome)) {
            configuration.setOfficeHome(officeHome);
        }

        String taskExecutionTimeoutProperty = Framework.getProperty(TASK_EXECUTION_TIMEOUT_PROPERTY_KEY);
        if (taskExecutionTimeoutProperty != null && !"".equals(taskExecutionTimeoutProperty)) {
            Long taskExecutionTimeout = Long.valueOf(taskExecutionTimeoutProperty);
            configuration.setTaskExecutionTimeout(taskExecutionTimeout);
        }
        String taskQueueTimeoutProperty = Framework.getProperty(TASK_QUEUE_TIMEOUT_PROPERTY_KEY);
        if (taskQueueTimeoutProperty != null && !"".equals(taskQueueTimeoutProperty)) {
            Long taskQueueTimeout = Long.valueOf(taskQueueTimeoutProperty);
            configuration.setTaskQueueTimeout(taskQueueTimeout);
        }
        String templateProfileDir = Framework.getProperty(TEMPLATE_PROFILE_DIR_PROPERTY_KEY);
        if (templateProfileDir != null && !"".equals(templateProfileDir)) {
            File templateDirectory = new File(templateProfileDir);
            if (!templateDirectory.exists()) {
                try {
                    FileUtils.forceMkdir(templateDirectory);
                } catch (IOException e) {
                    throw new RuntimeException("I/O Error: could not create JOD templateDirectory");
                }
            }
            configuration.setTemplateProfileDir(templateDirectory);
        }

        // Descriptor configuration
        String pipeNamesProperty = Framework.getProperty(OFFICE_PIPES_PROPERTY_KEY);
        String[] pipeNames = null;
        if (pipeNamesProperty != null) {
            String[] unvalidatedPipeNames = pipeNamesProperty.split(",\\s*");
            ArrayList<String> validatedPipeNames = new ArrayList<>();
            // Basic validation to avoid empty strings
            for (int i = 0; i < unvalidatedPipeNames.length; i++) {
                String tmpPipeName = unvalidatedPipeNames[i].trim();
                if (tmpPipeName.length() > 0) {
                    validatedPipeNames.add(tmpPipeName);
                }
            }
            pipeNames = validatedPipeNames.toArray(new String[0]);
        } else {
            pipeNames = descriptor.getPipeNames();
        }
        if (pipeNames != null && pipeNames.length != 0) {
            configuration.setPipeNames(pipeNames);
        }
        String portNumbersProperty = Framework.getProperty(OFFICE_PORTS_PROPERTY_KEY);
        int[] portNumbers = null;
        if (portNumbersProperty != null) {
            String[] portStrings = portNumbersProperty.split(",\\s*");
            ArrayList<Integer> portList = new ArrayList<>();
            for (int i = 0; i < portStrings.length; i++) {
                try {
                    portList.add(Integer.parseInt(portStrings[i].trim()));
                } catch (NumberFormatException e) {
                    log.error("Ignoring malformed port number: " + portStrings[i]);
                }
            }
            portNumbers = ArrayUtils.toPrimitive(portList.toArray(new Integer[0]));
        } else {
            portNumbers = descriptor.getPortNumbers();
        }
        if (portNumbers != null && portNumbers.length != 0) {
            configuration.setPortNumbers(portNumbers);
        }
        try {
            officeManager = configuration.buildOfficeManager();
            officeManager.start();
            started = true;
            log.debug("Starting ooo manager.");
        } catch (IllegalStateException | OfficeException e) {
            started = false;
            Throwable t = unwrapException(e);
            log.warn("OpenOffice was not found, JOD Converter " + "won't be available: " + t.getMessage());
        }
    } finally {
        starting = false;
    }
}

From source file:org.opendaylight.openflowplugin.outputtest.OutputTestCommandProvider.java

public void _sendPacketOutputMsg(CommandInterpreter ci) {
    /* Sending package OUT with action */
    LOG.debug("SendOutMsgWithAction");
    if (sessionInitiated) {
        String inNodeKey = ci.nextArgument();
        String inPort = ci.nextArgument();
        String outPort = "0xfffffffd";

        ArrayList<Byte> _arrayList = new ArrayList<Byte>(40);
        ArrayList<Byte> list = _arrayList;
        String _string = new String("sendOutputMsg_TEST");
        byte[] msg = _string.getBytes();
        int index = 0;
        for (final byte b : msg) {
            {/*from w  w w  .  j  av a2s . c om*/
                list.add(Byte.valueOf(b));
                boolean _lessThan = (index < 7);
                if (_lessThan) {
                    int _plus = (index + 1);
                    index = _plus;
                } else {
                    index = 0;
                }
            }
        }
        boolean _lessThan = (index < 8);
        boolean _while = _lessThan;
        while (_while) {
            {
                Byte _byte = new Byte("0");
                list.add(_byte);
                int _plus = (index + 1);
                index = _plus;
            }
            boolean _lessThan_1 = (index < 8);
            _while = _lessThan_1;
        }
        NodeRef ref = OutputTestUtil.createNodeRef(inNodeKey);

        TransmitPacketInputBuilder packet_out = new TransmitPacketInputBuilder();

        NodeConnectorRef _createNodeConnRef_1 = OutputTestUtil.createNodeConnRef(inNodeKey, inPort);
        NodeConnectorRef _nodeConnectorRef_1 = new NodeConnectorRef(_createNodeConnRef_1);
        NodeConnectorRef nIngressConRef = _nodeConnectorRef_1;

        NodeConnectorRef _createNodeConnRef_2 = OutputTestUtil.createNodeConnRef(inNodeKey, outPort);
        NodeConnectorRef _nodeConnectorRef_2 = new NodeConnectorRef(_createNodeConnRef_2);
        NodeConnectorRef nEngressConRef = _nodeConnectorRef_2;

        final ArrayList<Byte> _converted_list = list;
        byte[] _primitive = ArrayUtils
                .toPrimitive(((Byte[]) Conversions.unwrapArray(_converted_list, Byte.class)));

        List<Action> actionList = new ArrayList<Action>();
        ActionBuilder ab = new ActionBuilder();

        OutputActionBuilder output = new OutputActionBuilder();
        output.setMaxLength(new Integer(0xffff));
        Uri value = new Uri(OutputPortValues.CONTROLLER.toString());
        output.setOutputNodeConnector(value);
        ab.setAction(new OutputActionCaseBuilder().setOutputAction(output.build()).build());
        ab.setOrder(0);
        ab.setKey(new ActionKey(0));
        actionList.add(ab.build());

        packet_out.setCookie(null);
        packet_out.setAction(actionList);
        packet_out.setPayload(_primitive);
        packet_out.setNode(ref);
        packet_out.setIngress(nIngressConRef);
        packet_out.setEgress(nEngressConRef);
        packet_out.setBufferId(new Long(0xffffffffL));

        packetProcessingService.transmitPacket(packet_out.build());
    } else {
        ci.println("Session not initiated, try again in a few seconds");
    }
}

From source file:org.opendaylight.openflowplugin.outputtest.OutputTestUtil.java

public static TransmitPacketInput buildTransmitInputPacket(final String nodeId, final String outPort,
        final String inPort) {
    List<Byte> list = new ArrayList<Byte>(40);
    byte[] msg = OUTPUT_MSG.getBytes();

    int index = 0;
    for (byte b : msg) {
        list.add(b);/*from  w ww  . ja v a  2 s. c o m*/
        index = index < 7 ? index + 1 : 0;
    }

    while (index < 8) {
        list.add((byte) 0);
        index++;
    }
    NodeRef ref = createNodeRef(nodeId);
    NodeConnectorRef nEgressConfRef = new NodeConnectorRef(createNodeConnRef(nodeId, outPort));

    NodeConnectorRef nIngressConRef = new NodeConnectorRef(createNodeConnRef(nodeId, inPort));

    TransmitPacketInputBuilder tPackBuilder = new TransmitPacketInputBuilder();

    final List<Byte> convertedList = list;
    byte[] primitive = ArrayUtils.toPrimitive(convertedList.toArray(new Byte[0]));
    tPackBuilder.setPayload(primitive);

    tPackBuilder.setNode(ref);
    // TODO VD P2 missing cookies in Test
    tPackBuilder.setConnectionCookie(null);
    tPackBuilder.setEgress(nEgressConfRef);
    tPackBuilder.setIngress(nIngressConRef);
    return tPackBuilder.build();
}

From source file:org.openfact.common.converts.DocumentUtils.java

public static Document byteToDocument(Byte[] document) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from  w ww  .  j av a  2s  .c  o  m*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document docParse = builder.parse(new ByteArrayInputStream(ArrayUtils.toPrimitive(document)));
    return docParse;
}

From source file:org.openhab.binding.BluetoothLE.protocol.BluetoothLESimulator.java

@Override
public Object getData() throws Exception {
    Thread.sleep(5000); // do not run havoc :-)

    simulateFreeTecDevices(freeTecDevice1);
    simulateFreeTecDevices(freeTecDevice2);

    currentDevice++;//from  ww w .ja va 2 s.com
    if (currentDevice >= devices.size())
        currentDevice = 0;
    byte[] bytes = ArrayUtils.toPrimitive(devices.get(currentDevice));

    return getData(bytes, bytes.length);
}

From source file:org.openhab.binding.elerotransmitterstick.internal.stick.SerialConnection.java

private void analyzeBuffer() {
    // drop everything before the beginning of the packet header 0xAA
    while (!bytes.isEmpty() && bytes.get(0) != (byte) 0xAA) {
        logger.trace("dropping byte {} from buffer", bytes.get(0));
        bytes.remove(0);/*from  w  ww .ja  v a  2s  .  co m*/
    }

    if (logger.isTraceEnabled()) {
        logger.trace("buffer contains {} bytes: {}", bytes.size(),
                ArrayUtils.toPrimitive(bytes.toArray(new Byte[bytes.size()])));
    }
    if (bytes.size() > 1) {
        // second byte should be length byte (has to be either 0x04 or 0x05)
        int len = bytes.get(1);
        logger.trace("packet length is {} bytes.", len);

        if (len != 4 && len != 5) {
            // invalid length, drop packet
            bytes.remove(0);
            analyzeBuffer();
        } else if (bytes.size() > len + 1) {
            // we have a complete packet in the buffer, analyze it
            // third byte should be response type byte (has to be either EASY_CONFIRM or EASY_ACK)
            byte respType = bytes.get(2);

            synchronized (bytes) {
                if (respType == ResponseStatus.EASY_CONFIRM) {
                    logger.trace("response type is EASY_CONFIRM.");

                    long val = bytes.get(0) + bytes.get(1) + bytes.get(2) + bytes.get(3) + bytes.get(4)
                            + bytes.get(5);
                    if (val % 256 == 0) {
                        response = ResponseUtil.createResponse(bytes.get(3), bytes.get(4));
                    } else {
                        logger.warn("invalid response checksum. Skipping response.");
                    }

                    bytes.notify();
                } else if (respType == ResponseStatus.EASY_ACK) {
                    logger.trace("response type is EASY_ACK.");

                    long val = bytes.get(0) + bytes.get(1) + bytes.get(2) + bytes.get(3) + bytes.get(4)
                            + bytes.get(5) + bytes.get(6);
                    if (val % 256 == 0) {
                        response = ResponseUtil.createResponse(bytes.get(3), bytes.get(4), bytes.get(5));
                    } else {
                        logger.warn("invalid response checksum. Skipping response.");
                    }

                    bytes.notify();
                } else {
                    logger.warn("invalid response type {}. Skipping response.", respType);
                }
            }

            bytes.remove(0);
            analyzeBuffer();
        }
    }
}

From source file:org.openhab.binding.wr3223.internal.AbstractWR3223Connector.java

/**
 * Read bytes from input stream until ETX.
 *
 * @return The extracted answer./*  www. j  a  va 2  s  . c o  m*/
 * @throws IOException
 */
private byte[] readAnswer() throws IOException {
    List<Byte> answerList = new ArrayList<Byte>();
    Byte val;
    do {
        val = inputStream.readByte();
        answerList.add(val);
    } while (val != ETX);
    byte[] answer = ArrayUtils.toPrimitive(answerList.toArray(new Byte[0]));
    return answer;
}

From source file:org.openlmis.web.view.pdf.requisition.RequisitionPdfModel.java

private PdfPTable prepareTable(List<? extends Column> visibleColumns) throws DocumentException {
    java.util.List<Integer> widths = new ArrayList<>();
    for (Column column : visibleColumns) {
        widths.add(column.getColumnWidth());
    }/*from  w  w  w  .j  a  va 2 s .c om*/
    PdfPTable table = new PdfPTable(widths.size());

    table.setWidths(ArrayUtils.toPrimitive(widths.toArray(new Integer[widths.size()])));
    table.getDefaultCell().setBackgroundColor(HEADER_BACKGROUND);
    table.getDefaultCell().setPadding(CELL_PADDING);
    table.setWidthPercentage(WIDTH_PERCENTAGE);
    table.setSpacingBefore(TABLE_SPACING);
    table.setHeaderRows(2);
    table.setFooterRows(1);
    setTableHeader(table, visibleColumns);
    setBlankFooter(table, visibleColumns.size());
    return table;
}

From source file:org.opentox.jaqpot3.qsar.util.WekaInstancesProcess.java

public static Instances getFilteredInstances(Instances inputData, List<Feature> independentFeatures,
        Feature dependentFeature) throws JaqpotException {
    try {/*from   w  w  w.  j  a v a2  s  . com*/
        List<Integer> indexArray = getDescriptorsIndexArray(inputData, independentFeatures, dependentFeature);
        //apply filter for deleting the attributes other than these descriptors 
        int[] intArray = ArrayUtils.toPrimitive(indexArray.toArray(new Integer[indexArray.size()]));
        int m = 1;
        Remove rm = new Remove();
        rm.setOptions(new String[] { "-V" });
        rm.setAttributeIndicesArray(intArray);
        rm.setInputFormat(inputData);
        Instances filteredData = Filter.useFilter(inputData, rm);

        return filteredData;

    } catch (Exception ex) {
        throw new JaqpotException(ex);
    }
}