List of usage examples for org.apache.commons.lang ArrayUtils getLength
public static int getLength(Object array)
Returns the length of the specified array.
From source file:mitm.common.util.SizeLimitedWriter.java
@Override public void write(char cbuf[]) throws IOException { if (!isLimitReached(ArrayUtils.getLength(cbuf))) { delegate.write(cbuf);/*from w ww . j a v a 2s .c o m*/ } }
From source file:gda.data.DetectorDataWrapper.java
Object[] calcElements() { Object[] elements = new Object[] { detectorDataVal }; // if( isCounterTimer){ if (detectorDataVal instanceof Object[]) { elements = (Object[]) detectorDataVal; } else if (detectorDataVal instanceof PySequence) { PySequence seq = (PySequence) detectorDataVal; int len = seq.__len__(); elements = new Object[len]; for (int i = 0; i < len; i++) { elements[i] = seq.__finditem__(i); }//from w ww . j av a 2 s . c o m } else if (detectorDataVal instanceof PyList) { PyList seq = (PyList) detectorDataVal; int len = seq.__len__(); elements = new Object[len]; for (int i = 0; i < len; i++) { elements[i] = seq.__finditem__(i); } } else if (detectorDataVal.getClass().isArray()) { int len = ArrayUtils.getLength(detectorDataVal); elements = new Object[len]; for (int i = 0; i < len; i++) { elements[i] = Array.get(detectorDataVal, i); } } // } return elements; }
From source file:mitm.djigzo.web.pages.dlp.patterns.PatternsUsage.java
public List<Usage> getSource() { List<Usage> usages = new LinkedList<PatternsUsage.Usage>(); try {/*from w ww . j av a 2 s. c o m*/ List<String> infos = policyPatternManagerWS.getInUseInfo(patternName); if (CollectionUtils.isNotEmpty(infos)) { for (String info : infos) { String[] data = StringUtils.split(info, ','); if (ArrayUtils.getLength(data) == 3) { usages.add(new Usage(data[0], data[1], data[2])); } } } } catch (WebServiceCheckedException e) { errorMessage = e.getMessage(); error = true; } return usages; }
From source file:edu.cornell.med.icb.goby.modes.CompactFileStatsMode.java
/** * Print statistics about an alignment file in the Goby compact form. * * @param file The file to display statistics about * @throws IOException if the file cannot be read *//*from www . j av a2 s . c o m*/ private void describeCompactAlignment(final File file) throws IOException { final String basename = AlignmentReaderImpl.getBasename(file.toString()); stream.printf("Compact Alignment basename = %s%n", basename); final AlignmentReaderImpl reader = new AlignmentReaderImpl(basename); reader.readHeader(); stream.println("Info from header:"); stream.printf("Alignment written with Goby version=%s %n", reader.getGobyVersion()); stream.printf("Alignment produced by aligner=%s version=%s %n", reader.getAlignerName(), reader.getAlignerVersion()); stream.printf("Sorted: %b%n", reader.isSorted()); stream.printf("Indexed: %b%n", reader.isIndexed()); stream.printf("Number of target sequences = %,d%n", reader.getNumberOfTargets()); final int[] targetLengthsFromHeader = reader.getTargetLength(); stream.printf("Number of target length entries = %,d%n", ArrayUtils.getLength(reader.getTargetLength())); stream.printf("smallestSplitQueryIndex = %d%n", reader.getSmallestSplitQueryIndex()); stream.printf("largestSplitQueryIndex = %d%n", reader.getLargestSplitQueryIndex()); // simple statistics for target lengths final SummaryStatistics targetLengthStats = new SummaryStatistics(); if (targetLengthsFromHeader != null) { for (final double d : targetLengthsFromHeader) { targetLengthStats.addValue(d); } } stream.printf("Min target length = %,d%n", (int) targetLengthStats.getMin()); stream.printf("Max target length = %,d%n", (int) targetLengthStats.getMax()); stream.printf("Mean target length = %,.2f%n", targetLengthStats.getMean()); stream.println(); stream.printf("Number of query sequences = %,d%n", reader.getNumberOfQueries()); final SummaryStatistics queryLengthStats = new SummaryStatistics(); stream.println("Query lengths stored in entries = " + reader.isQueryLengthStoredInEntries()); stream.println("Constant query lengths = " + reader.isConstantQueryLengths()); stream.printf("Has query identifiers = %s%n", reader.getQueryIdentifiers() != null && !reader.getQueryIdentifiers().isEmpty()); final IndexedIdentifier targetIdentifiers = reader.getTargetIdentifiers(); final boolean hasTargetIdentifiers = targetIdentifiers != null && !targetIdentifiers.isEmpty(); stream.printf("Has target identifiers = %s%n", hasTargetIdentifiers); stream.printf("Has query index permutation = %s%n", reader.getQueryIndicesWerePermuted()); stream.printf("Has query index occurrences = %s%n", reader.hasQueryIndexOccurrences()); stream.printf("Has all read quality scores = %s%n", reader.getHasAllReadQualityScores()); stream.printf("Has ambiguity = %s%n", reader.hasAmbiguity()); if (verbose) { if (hasTargetIdentifiers) { for (Map.Entry<MutableString, Integer> entry : targetIdentifiers.entrySet()) { stream.printf(" Target %s=%d with a length of %d%n", entry.getKey(), entry.getValue(), targetLengthsFromHeader[entry.getValue()]); } } else { for (Map.Entry<MutableString, Integer> entry : targetIdentifiers.entrySet()) { stream.printf(" Target %d with a length of %d%n", entry.getValue(), targetLengthsFromHeader[entry.getValue()]); } } } stream.println(); if (reader.getReadOriginInfo().size() > 0) { stream.println("---- Read Origin Info ------"); for (final Alignments.ReadOriginInfo info : reader.getReadOriginInfo().getPbList()) { stream.println("["); stream.print(info.toString()); stream.println("]"); } } else { stream.println("Alignment has no Read Origin Info/Read Groups"); } if (headerOnly) return; // the query indices that aligned. Includes those final DistinctIntValueCounterBitSet alignedQueryIndices = new DistinctIntValueCounterBitSet(); describeAmbigousReads(basename, reader.getNumberOfQueries(), alignedQueryIndices); int maxQueryIndex = -1; int maxTargetIndex = -1; int numEntries = 0; long numLogicalAlignmentEntries = 0; long total = 0; double avgScore = 0; int sumNumVariations = 0; int numPaired = 0; int numProperlyPaired = 0; int numFirstInPair = 0; int numSecondInPair = 0; boolean hasSoftClips = false; for (final Alignments.AlignmentEntry entry : reader) { numberOfReads++; // Across all files numEntries++; // Across this file numLogicalAlignmentEntries += Math.max(entry.getMultiplicity(), 1); total += entry.getQueryAlignedLength(); avgScore += entry.getScore(); maxQueryIndex = Math.max(maxQueryIndex, entry.getQueryIndex()); maxTargetIndex = Math.max(maxTargetIndex, entry.getTargetIndex()); cumulativeReadLength += entry.getQueryAlignedLength(); minReadLength = Math.min(minReadLength, entry.getQueryAlignedLength()); maxReadLength = Math.max(maxReadLength, entry.getQueryAlignedLength()); sumNumVariations += entry.getSequenceVariationsCount(); alignedQueryIndices.observe(entry.getQueryIndex()); hasSoftClips |= entry.hasSoftClippedBasesLeft(); hasSoftClips |= entry.hasSoftClippedBasesRight(); // check entry then header for the query length final double queryLength = entry.getQueryLength(); queryLengthStats.addValue(queryLength); numPaired += EntryFlagHelper.isPaired(entry) ? 1 : 0; numProperlyPaired += EntryFlagHelper.isProperlyPaired(entry) ? 1 : 0; numFirstInPair += EntryFlagHelper.isFirstInPair(entry) ? 1 : 0; numSecondInPair += EntryFlagHelper.isSecondInPair(entry) ? 1 : 0; } avgScore /= (double) numLogicalAlignmentEntries; final int numQuerySequences = reader.getNumberOfQueries(); stream.printf("num query indices = %,d%n", numQuerySequences); final int numTargetSequences = maxTargetIndex + 1; final double avgNumVariationsPerQuery = ((double) sumNumVariations) / (double) numQuerySequences; stream.printf("num target indices = %,d%n", numTargetSequences); stream.printf("Number of alignment entries = %,d%n", numLogicalAlignmentEntries); stream.printf("Number of query indices that matched = %,d%n", alignedQueryIndices.count()); stream.printf("Percent matched = %4.1f %% %n", (double) alignedQueryIndices.count() / (double) ((long) numQuerySequences) * 100.0d); stream.printf("Avg query alignment length = %,f%n", numEntries > 0 ? divide(total, numEntries) : -1); stream.printf("Avg score alignment = %f%n", avgScore); stream.printf("Avg number of variations per query sequence = %3.2f %n", avgNumVariationsPerQuery); // size, the number of bytes in the entries file. final long size = new File(basename + ".entries").length(); stream.printf("Average bytes per entry = %f%n", divide(size, numLogicalAlignmentEntries)); stream.printf("Min query length = %,d%n", (int) queryLengthStats.getMin()); stream.printf("Max query length = %,d%n", (int) queryLengthStats.getMax()); final double meanQueryLength = queryLengthStats.getMean(); stream.printf("Mean query length = %,.2f%n", meanQueryLength); final int averageReadLength = (int) (Math.round(meanQueryLength)); stream.printf("Average bits per read base, assuming average read length %d = %f%n", averageReadLength, divide(size, numLogicalAlignmentEntries * averageReadLength)); stream.printf("Percent paired reads = %,.2f %% %n", divide(numPaired, numQuerySequences * 2) * 100d); stream.printf("Percent properly paired reads = %,.2f %% %n", divide(numProperlyPaired, numQuerySequences * 2) * 100d); stream.printf("Percent first in pair = %,.2f %% %n", divide(numFirstInPair, numEntries) * 100d); stream.printf("Percent second in pair = %,.2f %% %n", divide(numSecondInPair, numEntries) * 100d); stream.printf("Aligment entries have some softClips: %b %n", hasSoftClips); }
From source file:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java
private void getPFXTransacted(Collection<X509Certificate> certificates, char[] password, boolean includeRoot, OutputStream pfx) throws KeyStoreException { try {/*from w w w. j ava 2 s . c o m*/ KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); keyStore.load(null); for (X509Certificate certificate : certificates) { if (certificate == null) { continue; } X509CertStoreEntry entry = keyAndCertStore.getByCertificate(certificate); if (entry != null && entry.getCertificate() != null) { KeyAndCertificate keyAndCertificate = keyAndCertStore.getKeyAndCertificate(entry); if (keyAndCertificate != null) { if (!certificate.equals(keyAndCertificate.getCertificate())) { throw new IllegalStateException("Certificate mismatch."); } X509Certificate[] chain = null; /* * Build a certificate chain so we add the chain (if valid) */ try { CertificatePathBuilder pathBuilder = pathBuilderFactory.createCertificatePathBuilder(); CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(certificate); X509Certificate root = null; if (includeRoot && pathBuilderResult instanceof PKIXCertPathBuilderResult) { TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult) .getTrustAnchor(); if (trustAnchor != null) { root = trustAnchor.getTrustedCert(); } } CertPath certPath = pathBuilderResult.getCertPath(); if (certPath != null && CollectionUtils.isNotEmpty(certPath.getCertificates())) { List<X509Certificate> completePath = new LinkedList<X509Certificate>(); for (Certificate fromPath : certPath.getCertificates()) { if (!(fromPath instanceof X509Certificate)) { /* * only X509Certificates are supported */ continue; } completePath.add((X509Certificate) fromPath); } if (root != null && includeRoot) { completePath.add(root); } chain = new X509Certificate[completePath.size()]; chain = completePath.toArray(chain); } } catch (CertPathBuilderException e) { logger.warn( "Could not build a path. Message: " + ExceptionUtils.getRootCauseMessage(e)); } if (ArrayUtils.getLength(chain) == 0) { chain = new X509Certificate[] { certificate }; } String alias = X509CertificateInspector.getThumbprint(certificate); if (keyAndCertificate.getPrivateKey() != null) { keyStore.setKeyEntry(alias, keyAndCertificate.getPrivateKey(), password, chain); } else { keyStore.setCertificateEntry(alias, certificate); } } } } keyStore.store(pfx, password); } catch (NoSuchAlgorithmException e) { throw new KeyStoreException(e); } catch (CertificateException e) { throw new KeyStoreException(e); } catch (IOException e) { throw new KeyStoreException(e); } catch (CertStoreException e) { throw new KeyStoreException(e); } catch (NoSuchProviderException e) { throw new NoSuchProviderRuntimeException(e); } catch (SecurityFactoryFactoryException e) { throw new KeyStoreException(e); } }
From source file:edu.cornell.med.icb.goby.alignments.Merge.java
private int constructTargetIndexPermutations(int mergedReferenceIndex, final IndexedIdentifier mergedTargetIdentifiers, final Int2IntMap mergedTargetLengths, final AlignmentReaderImpl reader) { final int[] targetLengths = reader.getTargetLength(); final int targetLengthCount = ArrayUtils.getLength(targetLengths); // merge targets : each target in the merged alignment will receives a merged targetIndex. final Int2IntMap tempPermutation = new Int2IntOpenHashMap(); final IndexedIdentifier targetIdentifers = reader.getTargetIdentifiers(); final DoubleIndexedIdentifier backward = new DoubleIndexedIdentifier(targetIdentifers); for (int i = 0; i < reader.getNumberOfTargets(); i++) { MutableString id = backward.size() != 0 ? backward.getId(i) : new MutableString(String.valueOf(mergedTargetIdentifiers.size())); final int newIndex = mergedTargetIdentifiers.registerIdentifier(id); tempPermutation.put(i, newIndex); final MutableString targetId = backward.getId(i); if (targetId != null) { if (LOG.isDebugEnabled()) { LOG.debug("tempPermutation associating targetId: " + targetId + " to index " + newIndex); }//from www . j a v a2s . co m mergedTargetIdentifiers.registerIdentifier(targetId); final int targetLength; if (i < targetLengthCount) { targetLength = targetLengths[i]; } else { targetLength = 0; } mergedTargetLengths.put(newIndex, targetLength); } else { } } // transfer target index permutation to array for fast access: // final int size = tempPermutation.size(); int size = 0; for (final int key : tempPermutation.keySet()) { size = Math.max(key + 1, size); } if (LOG.isDebugEnabled()) { LOG.debug("Creating array with size " + size); } final int[] newPermutation = new int[size]; for (final int key : tempPermutation.keySet()) { if (LOG.isDebugEnabled()) { LOG.debug("about to get key : " + key); } newPermutation[key] = tempPermutation.get(key); } referenceIndexPermutation.add(newPermutation); return mergedTargetIdentifiers.size(); }
From source file:gda.device.detector.analyser.EpicsMCASimple.java
@Override public int[] getDataDimensions() throws DeviceException { //TODO get value of .NUSE return new int[] { ArrayUtils.getLength(getData()) }; }
From source file:gda.data.scan.datawriter.NexusDataWriter.java
private static int getIntfromBuffer(Object buf) { if (buf instanceof Object[]) buf = ((Object[]) buf)[0]; if (buf instanceof Number) return ((Number) buf).intValue(); if (buf.getClass().isArray()) { int len = ArrayUtils.getLength(buf); if (len == 1) { Object object = Array.get(buf, 0); return getIntfromBuffer(object); }/*w w w . j a va 2s .c om*/ } return Integer.parseInt(buf.toString()); }
From source file:gda.device.scannable.ScannableUtils.java
/** * Converts a position object to an array of doubles. It position is an Angle quantity it is converted to degrees, * if a linear quantity it is converted to mm, else it is just treated as a number. * /* ww w .j a v a 2 s .c o m*/ * @param position * @return array of doubles */ public static Double[] objectToArray(Object position) { Double[] posArray = new Double[0]; if (position instanceof Double[]) { return (Double[]) position; } if (position instanceof Number[]) { int length = ArrayUtils.getLength(position); posArray = new Double[length]; for (int i = 0; i < length; i++) { posArray[i] = ((Number[]) position)[i].doubleValue(); } return posArray; } else if (position instanceof Object[]) { int length = ((Object[]) position).length; posArray = new Double[length]; for (int i = 0; i < length; i++) { Object obj = ((Object[]) position)[i]; Double val = null; if (obj instanceof String) { val = Double.parseDouble((String) obj); } else if (obj instanceof Number) { val = ((Number) obj).doubleValue(); } else if (obj instanceof PyObject) { val = (Double) ((PyObject) obj).__tojava__(Double.class); } posArray[i] = val; } return posArray; } // if its a Java array else if (position.getClass().isArray()) { int length = ArrayUtils.getLength(position); for (int i = 0; i < length; i++) { posArray = (Double[]) ArrayUtils.add(posArray, Array.getDouble(position, i)); } return posArray; } // if its a Jython array else if (position instanceof PySequence) { int length = ((PySequence) position).__len__(); for (int i = 0; i < length; i++) { posArray = (Double[]) ArrayUtils.add(posArray, getDouble(position, i)); } } // if its a Jython array else if (position instanceof List) { @SuppressWarnings("rawtypes") int length = ((List) position).size(); for (int i = 0; i < length; i++) { posArray = (Double[]) ArrayUtils.add(posArray, getDouble(position, i)); } } // if its a Quantity else if (position instanceof Quantity) { posArray = (Double[]) ArrayUtils.add(posArray, ((Quantity) position).getAmount()); } // if its a String, then try to convert to a double else if (position instanceof String) { Quantity posAsQ = QuantityFactory.createFromString((String) position); Double posAsDouble = posAsQ != null ? posAsQ.getAmount() : Double.parseDouble((String) position); posArray = (Double[]) ArrayUtils.add(posArray, posAsDouble); } // else assume its some object whose toString() method returns a String which can be converted else { posArray = (Double[]) ArrayUtils.add(posArray, Double.parseDouble(position.toString())); } return posArray; }
From source file:gda.data.metadata.NXMetaDataProvider.java
public Object[] separateGetPositionOutputIntoElementalPosObjects(Object scannableGetPositionOut) { if (scannableGetPositionOut == null) return new Object[] {}; Object[] elements = new Object[] { scannableGetPositionOut }; if (scannableGetPositionOut instanceof Object[]) { elements = (Object[]) scannableGetPositionOut; } else if (scannableGetPositionOut instanceof PySequence) { PySequence seq = (PySequence) scannableGetPositionOut; int len = seq.__len__(); elements = new Object[len]; for (int i = 0; i < len; i++) { elements[i] = seq.__finditem__(i); }/*from ww w.j a va 2 s.c om*/ } else if (scannableGetPositionOut instanceof PyList) { PyList seq = (PyList) scannableGetPositionOut; int len = seq.__len__(); elements = new Object[len]; for (int i = 0; i < len; i++) { elements[i] = seq.__finditem__(i); } } else if (scannableGetPositionOut.getClass().isArray()) { int len = ArrayUtils.getLength(scannableGetPositionOut); elements = new Object[len]; for (int i = 0; i < len; i++) { elements[i] = Array.get(scannableGetPositionOut, i); } } else if (scannableGetPositionOut instanceof PlottableDetectorData) { elements = ((PlottableDetectorData) scannableGetPositionOut).getDoubleVals(); } return elements; }