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

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

Introduction

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

Prototype

public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) 

Source Link

Document

Produces a new boolean array containing the elements between the start and end indices.

Usage

From source file:edu.jhu.pha.vospace.node.NodePath.java

public NodePath getParentPath() {
    return new NodePath((String[]) ArrayUtils.subarray(this.pathTokens, 0, this.pathTokens.length - 1));
}

From source file:au.org.ala.delta.key.directives.io.KeyItemsFileReader.java

private void processItemAttributes(Item item, byte[] allAttributesData) {

    Set<Integer> variableCharacters = _context.getVariableCharactersForTaxon(item.getItemNumber());

    // First pass, read attribute data from file, or set values specified by
    // TREAT CHARACTERS AS VARIABLE directive
    for (int i = 0; i < _header.getNumberOfCharacters(); i++) {
        int charNum = i + 1;
        MultiStateCharacter ch = (MultiStateCharacter) _dataset.getCharacter(charNum);
        MultiStateAttribute msAttr = (MultiStateAttribute) _dataset.addAttribute(item.getItemNumber(),
                ch.getCharacterId());//from   w  w  w  . j  a va 2  s .  c om

        List<String> presentStatesAsStrings = new ArrayList<String>();

        if (variableCharacters != null && variableCharacters.contains(charNum)) {
            // Character is variable so all states are present
            for (int j = 0; j < ch.getNumberOfStates(); j++) {
                int stateNumber = j + 1;
                presentStatesAsStrings.add(Integer.toString(stateNumber));
            }
        } else {
            int arrayOffset = i * ATTRIBUTE_DATA_LENGTH;
            byte[] attributeDataAsBytes = ArrayUtils.subarray(allAttributesData, arrayOffset,
                    arrayOffset + ATTRIBUTE_DATA_LENGTH);

            boolean[] attributeDataAsBooleans = Utils.byteArrayToBooleanArray(attributeDataAsBytes);

            // Pull out which states are present from the attribute data.
            // Attribute data is stored as 32 bit words, so 32 is the
            // maximum number
            // of available states, regardless of how many states the
            // character actually has.
            for (int j = 0; j < Math.min(ch.getNumberOfStates(), 32); j++) {
                int stateNumber = j + 1;
                if (attributeDataAsBooleans[j]) {
                    presentStatesAsStrings.add(Integer.toString(stateNumber));
                }
            }

            boolean inapplicable = attributeDataAsBooleans[INAPPLICABLE_BIT];

            if (inapplicable) {
                presentStatesAsStrings.add("-");
            }
        }

        // TODO bit of a hack here, as DefaultAttributeData can
        // currently
        // only be set using a String.
        // Will be able to fix this up when we switch to using a
        // SlotFile
        // based dataset.
        try {
            msAttr.setValueFromString(StringUtils.join(presentStatesAsStrings, "/"));
        } catch (DirectiveException e) {
            throw new RuntimeException(e);
        }
    }

    // Second pass, set inapplicable any dependent characters that are made
    // inapplicable by the values of their
    // controlling characters
    // First pass, read attribute data from file
    for (int i = 0; i < _header.getNumberOfCharacters(); i++) {
        MultiStateCharacter ch = (MultiStateCharacter) _dataset.getCharacter(i + 1);

        MultiStateAttribute msAttr = (MultiStateAttribute) _dataset.getAttribute(item.getItemNumber(),
                ch.getCharacterId());

        if (!msAttr.isInapplicable()) {
            ControllingInfo controllingInfo = _dataset.checkApplicability(ch, item);
            // if (controllingInfo.isStrictlyInapplicable() ||
            // (controllingInfo.isMaybeInapplicable() &&
            // !msAttr.isUnknown())) {
            if (controllingInfo.isInapplicable()) {

                // Maintain existing state information - any attribute with
                // state information already set becomes
                // "maybe inapplicable"
                List<Integer> presentStates = msAttr.getPresentStatesAsList();
                List<String> presentStatesAsStrings = new ArrayList<String>();
                for (int stateNum : presentStates) {
                    presentStatesAsStrings.add(Integer.toString(stateNum));
                }

                // add inapplicable value
                presentStatesAsStrings.add("-");

                // TODO bit of a hack here, as DefaultAttributeData can
                // currently
                // only be set using a String.
                // Will be able to fix this up when we switch to using a
                // SlotFile
                // based dataset.
                try {
                    msAttr.setValueFromString(StringUtils.join(presentStatesAsStrings, "/"));
                } catch (DirectiveException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    // Third pass, unknown values should be variable unless the
    // TREAT UNKNOWN AS INAPPLICABLE directive has been used
    if (!_context.getTreatUnknownAsInapplicable()) {
        for (int i = 0; i < _header.getNumberOfCharacters(); i++) {
            MultiStateCharacter ch = (MultiStateCharacter) _dataset.getCharacter(i + 1);

            MultiStateAttribute msAttr = (MultiStateAttribute) _dataset.getAttribute(item.getItemNumber(),
                    ch.getCharacterId());

            if (msAttr.getPresentStates().isEmpty() && !msAttr.isInapplicable()) {
                // Set attribute as variable - all states are present
                List<String> presentStatesAsStrings = new ArrayList<String>();
                for (int j = 0; j < ch.getNumberOfStates(); j++) {
                    int stateNumber = j + 1;
                    presentStatesAsStrings.add(Integer.toString(stateNumber));
                }

                // TODO bit of a hack here, as DefaultAttributeData can
                // currently
                // only be set using a String.
                // Will be able to fix this up when we switch to using a
                // SlotFile
                // based dataset.
                try {
                    msAttr.setValueFromString(StringUtils.join(presentStatesAsStrings, "/"));
                } catch (DirectiveException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

From source file:com.amalto.core.storage.hibernate.StorageTableResolver.java

private static String __shortString(char[] chars, int threshold) {
    if (chars.length < threshold) {
        return new String(chars).replace('-', '_');
    } else {//from w  ww.  j  a  va 2 s.  com
        String s = new String(ArrayUtils.subarray(chars, 0, threshold / 2))
                + new String(ArrayUtils.subarray(chars, threshold / 2, chars.length)).hashCode();
        return __shortString(s.toCharArray(), threshold);
    }
}

From source file:edu.utdallas.bigsecret.crypter.CrypterMode1.java

/**
 * {@inheritDoc}/*from w  w  w  .j  a va2  s.c  o m*/
 */
public byte[] unwrapRow(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception {
    if (qualifier == null || qualifier.length == 0)
        throw new Exception("Qualifier data null or no data");

    int qualifierIndexSize = getIndexQualifierDataSize();
    byte[] completeData = m_keyCipher.decrypt(qualifier, qualifierIndexSize);

    int rowSize = Bytes.toInt(completeData, 0, 4);

    return ArrayUtils.subarray(completeData, 12, 12 + rowSize);
}

From source file:gda.device.detector.countertimer.TFGTriggeredScaler.java

private double[][] readData(int startFrame, int finalFrame) throws DeviceException {

    // readout everything for those frames
    int numberOfFrames = (finalFrame - startFrame) + 1;
    double[] scalerReadings;
    int numberOfChannelsToRead;
    if (numChannelsToRead == null) {
        numberOfChannelsToRead = scaler.getDimension()[0];
    } else {/*from   ww  w  .  ja  va 2  s  .c o  m*/
        numberOfChannelsToRead = numChannelsToRead;
        // add on the time channel 
        if (isTFGv2) {
            numberOfChannelsToRead++;
        }
    }

    scalerReadings = scaler.read(0, 0, startFrame, numberOfChannelsToRead, 1, numberOfFrames);

    int numberOfValuesPerFrame = this.getExtraNames().length; // assuming the instance is properly setup

    // loop over frames, extract each frame and add log values to the end
    double[][] output = new double[numberOfFrames][];
    for (int i = 0; i < numberOfFrames; i++) {

        // get the slice from the readings array
        int numScalers = numChannelsToRead == null ? scaler.getDimension()[0] : numChannelsToRead;
        int entryNumber = i;
        double[] slice = new double[numScalers];
        for (int scaNum = 0; scaNum < numScalers; scaNum++) {
            slice[scaNum] = scalerReadings[entryNumber];
            entryNumber += numberOfFrames;
        }

        double[] thisFrame = new double[numberOfValuesPerFrame];
        if (isTFGv2 && !timeChannelRequired) {
            // for TFGv2 always get the number of live time clock counts as the first scaler item
            thisFrame = ArrayUtils.subarray(slice, 1, slice.length);
        } else if (isTFGv2 && timeChannelRequired) {
            // convert the live time clock counts into seconds (TFG has a 100MHz clock cycle)
            thisFrame = ArrayUtils.subarray(slice, 0, slice.length);
            thisFrame[0] = thisFrame[0] / 100000000;

            // convert all values to rates
            if (this.returnCountRates && thisFrame[0] > 0.0) {
                for (int scaNum = 1; scaNum < numScalers; scaNum++) {
                    thisFrame[scaNum] /= thisFrame[0];
                }
            }

        } else if (!isTFGv2 && timeChannelRequired) {
            throw new DeviceException("Invalid parameter options for " + getName()
                    + ": cannot add a time channel when using TFGv1! Set timeChannelRequired to false");
        } else {
            thisFrame = slice;
        }
        if (isOutputLogValues())
            thisFrame = appendLogValues(thisFrame);
        output[i] = thisFrame;
    }
    return output;
}

From source file:marytts.tools.voiceimport.HalfPhoneUnitLabelComputer.java

/**
 * Get time of energy peak difference between startTime and endTime, based on energy analysis of the wav file for the current baseName.
 * <p>//from ww  w . ja  va 2s  . co  m
 * The energy analysis (based on the provided parameters {@link #windowSizeInSeconds} and {@link #skipSizeInSeconds}) is saved
 * to a binary file, which is reused if present (and if the parameter values match those encountered in the file header).
 * 
 * @param startTime
 *            of energy analysis
 * @param endTime
 *            of energy analysis
 * @return the time of the greatest increase in energy between startTime and endTime, or {@link Double#NaN} if no such
 *         time can be determined from the signal (this is then handled in {@link #getMidTimes(List, List)})
 * @throws IOException
 *             if the energy analysis file cannot be read or (initially) created
 * @see EnergyContourRms#WriteEnergyFile(EnergyContourRms, String)
 */
private double getEnergyPeak(double startTime, double endTime) throws IOException {
    // determine wav file name and energy analysis file name:
    String wavDir = db.getProperty(DatabaseLayout.WAVDIR);
    String baseName = bnl.getName(basenameIndex);
    String wavExt = db.getProperty(DatabaseLayout.WAVEXT);
    File wavFile = new File(wavDir, baseName + wavExt);
    File energyFile = new File(unitlabelDir, baseName + energyExt);

    // load or create energy analysis file:
    EnergyContourRms energyContourRMS;
    try {
        energyContourRMS = EnergyContourRms.ReadEnergyFile(energyFile.getAbsolutePath());
        if (energyContourRMS.header.windowSizeInSeconds != windowSizeInSeconds
                || energyContourRMS.header.skipSizeInSeconds != skipSizeInSeconds) {
            logger.debug("File header of " + energyFile.getAbsolutePath()
                    + " has unexpected parameter values! Will re-analyze...");
            throw new IOException();
        }
    } catch (IOException e) {
        logger.info("Analyzing " + wavFile.getAbsolutePath() + " and saving result to "
                + energyFile.getAbsolutePath());
        energyContourRMS = new EnergyContourRms(wavFile.getAbsolutePath(), energyFile.getAbsolutePath(),
                windowSizeInSeconds, skipSizeInSeconds);
    }

    // get energy analysis frames between startTime and endTime from energy contour:
    double[] energyContour = energyContourRMS.contour;
    int startFrame = SignalProcUtils.time2frameIndex(startTime, windowSizeInSeconds, skipSizeInSeconds);
    int endFrame = SignalProcUtils.time2frameIndex(endTime, windowSizeInSeconds, skipSizeInSeconds);
    double[] energyLocalContour = ArrayUtils.subarray(energyContour, startFrame, endFrame);

    // get framewise differences:
    double[] energyDiffs = MathUtils.diff(energyLocalContour);
    // we need more than one diff frame:
    if (energyDiffs.length < 2) {
        return Double.NaN;
    }
    // find frame index of peak diff:
    int peakLocalFrame = MathUtils.findGlobalPeakLocation(energyDiffs);
    int peakGlobalFrame = startFrame + peakLocalFrame;
    // convert frame index to time, adding half a window because diffs are between frames:
    double peakTime = SignalProcUtils.frameIndex2Time(peakGlobalFrame, windowSizeInSeconds, skipSizeInSeconds)
            + windowSizeInSeconds / 2;

    // adjust peak diff time to lie inside time range:
    if (peakTime < startTime) {
        peakTime = startTime;
    } else if (peakTime > endTime) {
        peakTime = endTime;
    }
    return peakTime;
}

From source file:com.baidu.terminator.plugin.signer.customized.app.FromAppToDrAPIHttpRequestSigner.java

private String decryptResponse(byte[] content) {
    byte[] body = ArrayUtils.subarray(content, 8, content.length);

    String unGipString = "";
    try {/* w  w  w.j  a  v  a 2 s .  c  om*/
        byte[] gzipBytes = RSAUtil.decryptByPublicKey(body, PUBLIC_KEY);
        unGipString = GZipUtil.unGzipString(gzipBytes);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        logger.error(e);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        logger.error(e);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        logger.error(e);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
        logger.error(e);
    } catch (SignatureException e) {
        e.printStackTrace();
        logger.error(e);
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        logger.error(e);
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
        logger.error(e);
    } catch (BadPaddingException e) {
        e.printStackTrace();
        logger.error(e);
    } catch (ShortBufferException e) {
        e.printStackTrace();
        logger.error(e);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e);
    }
    return unGipString;
}

From source file:net.bible.android.control.page.PageControl.java

/** 
 * Get page title including info about key/verse
 * Return it in 1 or 2 parts allowing it to be split over 2 lines
 * //from w w w .j  av a  2  s .  co  m
 * @return
 */
public String[] getCurrentPageTitleParts() {
    String[] retVal = new String[2];
    try {
        CurrentPage currentPage = CurrentPageManager.getInstance().getCurrentPage();
        if (currentPage != null) {
            if (currentPage.getSingleKey() != null) {
                Key key = currentPage.getSingleKey();
                // verses are special - show book at top and verse below
                if (key instanceof Verse) {
                    Verse verse = (Verse) key;
                    Versification v11n = verse.getVersification();
                    retVal[0] = StringUtils.left(v11n.getShortName(verse.getBook()), 6);

                    StringBuilder verseText = new StringBuilder();
                    verseText.append(verse.getChapter());
                    int verseNo = verse.getVerse();
                    if (verseNo > 0) {
                        verseText.append(":").append(verseNo);
                    }
                    retVal[1] = verseText.toString();
                } else {
                    // handle all non verse keys in a generic way
                    String title = key.getName();
                    // favour correct capitalisation because it looks better and is narrower so more fits in
                    if (ABStringUtils.isAllUpperCaseWherePossible(title)) {
                        // Books like INSTITUTES need corrected capitalisation
                        title = WordUtils.capitalizeFully(title);
                    }
                    String[] parts = titleSplitter.split(title);
                    retVal = ArrayUtils.subarray(parts, 0, 2);
                }
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Error getting page title", e);
    }
    return retVal;
}

From source file:com.ms.commons.standalone.service.StandaloneServiceImpl.java

private String getHeadLogFile(String logFilePath, boolean isTail, int lenth) {
    String content = null;//from  w  w w .ja  va 2  s  . com
    File logFile = new File(logFilePath);
    FileInputStream fiStream = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        fiStream = new FileInputStream(logFile);
        if (isTail && logFile.length() > lenth) {
            fiStream.skip(logFile.length() - lenth);
        }
        byte[] buffer = new byte[lenth];
        long count = 0;
        int n = 0;
        while (-1 != (n = fiStream.read(buffer))) {
            baos.write(buffer, 0, n);
            count += n;
            if (count >= lenth) {
                break;
            }
        }
        byte[] result = ArrayUtils.subarray(baos.toByteArray(), 0, lenth);
        content = new String(result, "utf-8");
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return "" + e.getMessage();
    } finally {
        IOUtils.closeQuietly(fiStream);
        IOUtils.closeQuietly(baos);
    }
    return content;
}

From source file:ips1ap101.lib.core.jsf.JSF.java

public static void upload(Upload upload, String carpeta, EnumOpcionUpload opcion) throws Exception {
    Bitacora.trace(JSF.class, "upload", upload, carpeta, opcion);
    if (upload == null) {
        return;/*from   w  w  w  .  j a  v a 2 s .c  o  m*/
    }
    CampoArchivo campoArchivo = upload instanceof CampoArchivo ? (CampoArchivo) upload : null;
    if (campoArchivo != null) {
        campoArchivo.setClientFileName(null);
        campoArchivo.setServerFileName(null);
    }
    UploadedFile uploadedFile = upload.getUploadedFile();
    if (uploadedFile == null) {
        return;
    }
    /**/
    Bitacora.trace(JSF.class, "upload", "name=" + uploadedFile.getOriginalName());
    Bitacora.trace(JSF.class, "upload", "path=" + uploadedFile.getClientFilePath());
    Bitacora.trace(JSF.class, "upload", "type=" + uploadedFile.getContentType());
    Bitacora.trace(JSF.class, "upload", "size=" + uploadedFile.getSize());
    /**/
    if (uploadedFile.getSize() == 0) {
        return;
    }
    /**/
    String sep = System.getProperties().getProperty("file.separator");
    String validChars = StrUtils.VALID_CHARS;
    String filepath = null;
    if (STP.esIdentificadorArchivoValido(carpeta)) {
        filepath = carpeta.replace(".", sep);
    }
    long id = LongUtils.getNewId();
    //      String filename = STP.getRandomString();
    String filename = id + "";
    String pathname = Utils.getAttachedFilesDir(filepath) + filename;
    String ext = Utils.getExtensionArchivo(uploadedFile.getOriginalName());
    if (StringUtils.isNotBlank(ext)) {
        String str = ext.toLowerCase();
        if (StringUtils.containsOnly(str, validChars)) {
            filename += "." + str;
            pathname += "." + str;
        }
    }
    //      if (!EnumOpcionUpload.FILA.equals(opcion)) {
    //          File file = new File(pathname);
    //          uploadedFile.write(file);
    //      }
    int bytesRead;
    int bufferSize = 8192;
    byte[] bytes = null;
    byte[] buffer = new byte[bufferSize];
    try (InputStream input = uploadedFile.getInputStream();
            OutputStream output = new FileOutputStream(pathname)) {
        while ((bytesRead = input.read(buffer)) != -1) {
            if (!EnumOpcionUpload.FILA.equals(opcion)) {
                output.write(buffer, 0, bytesRead);
            }
            if (!EnumOpcionUpload.ARCHIVO.equals(opcion)) {
                if (bytesRead < bufferSize) {
                    bytes = ArrayUtils.addAll(bytes, ArrayUtils.subarray(buffer, 0, bytesRead));
                } else {
                    bytes = ArrayUtils.addAll(bytes, buffer);
                }
            }
        }
    }
    /**/
    String clientFilePath = uploadedFile.getClientFilePath();
    String originalName = uploadedFile.getOriginalName();
    String clientFileName = clientFilePath == null ? originalName : clientFilePath + originalName;
    String serverFileName = Utils.getWebServerRelativePath(pathname);
    if (!EnumOpcionUpload.ARCHIVO.equals(opcion)) {
        String contentType = uploadedFile.getContentType();
        long size = uploadedFile.getSize();
        //          byte[] bytes = uploadedFile.getBytes();
        insert(id, clientFileName, serverFileName, contentType, size, bytes);
    }
    if (campoArchivo != null) {
        campoArchivo.setClientFileName(clientFileName);
        campoArchivo.setServerFileName(serverFileName);
    }
}