Example usage for java.util Arrays copyOfRange

List of usage examples for java.util Arrays copyOfRange

Introduction

In this page you can find the example usage for java.util Arrays copyOfRange.

Prototype

public static boolean[] copyOfRange(boolean[] original, int from, int to) 

Source Link

Document

Copies the specified range of the specified array into a new array.

Usage

From source file:net.sfr.tv.mom.mgt.handlers.InvocationHandler.java

@Override
public Object execute(MBeanServerConnection connection, Object[] args) {
    if (this.expression.indexOf("{") != -1) {
        this.expression = renderExpression(new Object[] { "\"".concat(args[0].toString()).concat("\"") });
        args = Arrays.copyOfRange(args, 1, args.length);
    }/*from www.  j a  v  a2  s.c  om*/

    try {
        final Set<ObjectName> oNames = connection.queryNames(new ObjectName(expression), null);
        if (oNames == null || oNames.isEmpty()) {
            LOGGER.severe("No object names returns for expression '" + expression + "'");
            return null;
        } else {
            final Object result = connection.invoke(oNames.iterator().next(), operation.getName(), args,
                    operation.getSignature());
            if (result == null) {
                LOGGER.warning("Result of operation '" + operation.getName() + "'is null");
                return result;
            }
            return formatter.format(result);
        }
        //result = connection.invoke(new ObjectName(expression), operation.getName(), new Object[operation.getSignature().length], operation.getSignature());
    } catch (MBeanException | IllegalArgumentException | InstanceNotFoundException
            | MalformedObjectNameException | ReflectionException | IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:io.alicorn.server.http.LoginEndpoint.java

public static String hash(char[] chars) {
    //Parse chars into bytes for hashing.
    CharBuffer charBuffer = CharBuffer.wrap(chars);
    ByteBuffer byteBuffer = charset.encode(charBuffer);
    byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());

    //Clear temporary arrays of any data.
    Arrays.fill(charBuffer.array(), '\u0000');
    Arrays.fill(byteBuffer.array(), (byte) 0);

    //Generate the SHA-256 hash.
    String hash = hash(bytes);/*from   ww  w. j ava 2s. c  om*/

    //Clear remaining arrays of any data.
    Arrays.fill(bytes, (byte) 0);

    return hash;
}

From source file:bachelorthesis.captchabuilder.builder.NoiseParser.java

/**
 * Parses the string arguments for rendering noise, creates a
 * NoiseProducer and passes it to the CaptchaBuilder
 *
 * @param buildSequenceOptions the string arguments for building noise
 * @param builder              the CaptchaBuilder Object to be modified
 * <p/>// w ww. j a va2s  .  co  m
 * @return a modified CaptchaBuilder object
 * <p/>
 * @throws org.apache.commons.cli.ParseException
 * @see CaptchaBuilder
 */
public static CaptchaBuilder parse(String[] buildSequenceOptions, CaptchaBuilder builder)
        throws ParseException {
    if (buildSequenceOptions.length == 0) {
        //return builder.addNoise();
        builder.addBuildSequence(new NoiseProducerBuilder(NoiseProducerType.CURVEDLINE));
        return builder;
    }

    if (buildSequenceOptions.length > NoiseOptions.values().length) {
        throw new ParseException("Noise takes a max of " + NoiseOptions.values().length + " arguments");
    }

    for (String noiseOption : buildSequenceOptions) {
        if (!noiseOption.isEmpty()) {
            try {
                String[] optionArgs = noiseOption.split(CaptchaConstants.buildSequencelvl3Delim);
                NoiseProducerType bgProdBuilder = NoiseProducerType.valueOf(optionArgs[0]);
                String[] noiseOptions = Arrays.copyOfRange(optionArgs, 1, optionArgs.length);
                return parseNoiseProducer(bgProdBuilder, noiseOptions, builder);
            } catch (IllegalArgumentException e) {
                throw new ParseException(e.getMessage());
            }
        }
    }

    return builder;
}

From source file:CipherProvider.java

/**
 * Create cipher for encrypt or decrypt backup content
 *
 * @param passwd passwd for encryption//from   w  w  w  .  ja  v  a 2s . c  o  m
 * @param mode   encrypt/decrypt mode
 *
 * @return instance of cipher
 */
private static Cipher getCipher(final String passwd, final int mode) {
    /* Derive the key, given password and salt. */
    Cipher cipher = null;
    try {
        SecretKeyFactory factory = null;
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        String salt = "slNadZlato#%^^&(&(5?@#5166?1561?#%^^*^&54431"; // only pseudorandom salt
        KeySpec spec = new PBEKeySpec(passwd.toCharArray(), salt.getBytes(), 65536, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), CIPHER_TYPE);

        // initialization vector
        byte[] iv = Arrays.copyOfRange(DigestUtils.md5(passwd), 0, 16);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);

        // Cipher for encryption
        cipher = Cipher.getInstance(CIPHER_TYPE + "/CBC/PKCS5Padding");
        cipher.init(mode, secret, paramSpec);
    } catch (Exception e) {
        e.printStackTrace(); //Todo implementovat
    }
    return cipher;
}

From source file:com.jameslandrum.bluetoothsmart.actions.LargeSetCharacteristic.java

@Override
public ActionError execute(SmartDevice smartDevice) {
    mError = super.execute(smartDevice);
    if (mError != null)
        return mError;
    int index = 0;

    BluetoothGattCharacteristic characteristic = mCharacteristic.getCharacteristic();
    characteristic.setValue(mData);// ww  w  .  j  ava 2 s. c om

    smartDevice.addGattListener(this);
    try {
        while (index < mData.length) {
            if (!mDevice.isConnected()) {
                mError = new CharacteristicWriteError();
                return mError;
            }
            int end = Math.min(index + mSize, mData.length);
            characteristic.setValue(Arrays.copyOfRange(mData, index, end));
            mGatt.writeCharacteristic(characteristic);
            synchronized (mHolder) {
                mHolder.wait(300);
            }
            index += mSize;
        }
    } catch (Exception e) {
        mError = new CharacteristicWriteError();
    }
    smartDevice.removeGattListener(this);

    if (mCompleteListener != null)
        mCompleteListener.onActionCompleted(this, mError == null);

    return mError;
}

From source file:dev.maisentito.suca.commands.AdminCommandHandler.java

@Override
public void handleCommand(MessageEvent event, String[] args) throws Throwable {
    if ((!Main.config.verifyOwner || event.getUser().isVerified())
            && event.getUser().getNick().equals(getStringGlobal(Main.GLOBAL_OWNER, ""))) {
        if (args.length < 2) {
            if (args.length == 1) {
                if (getGlobals().has(args[0], Object.class)) {
                    event.respond(/*from   w w  w  .  ja va  2  s .  co  m*/
                            String.format("!admin: %s = %s", args[0], getGlobals().get(args[0]).toString()));
                } else {
                    event.respond(String.format("!admin: %s = null", args[0]));
                }
                return;
            } else {
                event.respond("!admin: not enough arguments");
                return;
            }
        } else if (args[1].length() < 3) {
            event.respond("!admin: invalid value");
            return;
        }

        String key = args[0];
        String full = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), ' ');
        Object value;

        switch (args[1].charAt(0)) {
        case 'c':
            value = args[1].charAt(2);
            break;
        case 'b':
            value = Byte.parseByte(args[1].substring(2));
            break;
        case 's':
            value = Short.parseShort(args[1].substring(2));
            break;
        case 'i':
            value = Integer.parseInt(args[1].substring(2));
            break;
        case 'l':
            value = Long.parseLong(args[1].substring(2));
            break;
        case 'f':
            value = Float.parseFloat(args[1].substring(2));
            break;
        case 'd':
            value = Double.parseDouble(args[1].substring(2));
            break;
        case 'z':
            value = Boolean.parseBoolean(args[1].substring(2));
            break;
        case 'a':
            value = full.substring(2);
            break;
        default:
            event.respond("!admin: invalid type");
            return;
        }

        getGlobals().put(key, value);
        event.respond("success");

    } else {
        event.respond("nope");
    }
}

From source file:bachelorthesis.captchabuilder.builder.GimpyParser.java

/**
 * Parses the string arguments for rendering transformations, creates a
 * GimpyRenderer and passes it to the CaptchaBuilder
 *
 * @param buildSequenceOptions the string arguments for building
 *                             transformations
 * @param builder              the CaptchaBuilder Object to be modified
 * <p/>/*from  w w  w . ja v  a2  s . com*/
 * @return a modified CaptchaBuilder object
 * <p/>
 * @throws org.apache.commons.cli.ParseException
 * @see CaptchaBuilder
 */
public static CaptchaBuilder parse(String[] buildSequenceOptions, CaptchaBuilder builder)
        throws ParseException {
    if (buildSequenceOptions.length == 0) {
        //return builder.gimp();
        builder.addBuildSequence(new GimpyRendererBuilder(GimpyRendererType.RIPPLE));
        return builder;
    }

    if (buildSequenceOptions.length > GimpyRendererOptions.values().length) {
        throw new ParseException("Gimp takes a max of " + GimpyRendererOptions.values().length + " arguments");
    }

    for (String gimpyOption : buildSequenceOptions) {
        if (!gimpyOption.isEmpty()) {
            try {
                String[] optionArgs = gimpyOption.split(CaptchaConstants.buildSequencelvl3Delim);
                GimpyRendererType gimpyRenenderType = GimpyRendererType.valueOf(optionArgs[0]);
                String[] gimpyOptions = Arrays.copyOfRange(optionArgs, 1, optionArgs.length);
                return parseGimpyRenderer(gimpyRenenderType, gimpyOptions, builder);
            } catch (IllegalArgumentException e) {
                throw new ParseException(e.getMessage());
            }
        }
    }

    return builder;
}

From source file:com.bitbreeds.webrtc.stun.StunMessage.java

/**
 * @param data bytes that make up StunMessage
 * @return parsed StunMessage/*ww w . j av a 2  s  .c o m*/
 */
public static StunMessage fromBytes(byte[] data) {
    StunHeader header = StunHeader.fromBytes(Arrays.copyOfRange(data, 0, HEADER_LENGTH_BYTES));

    Map<StunAttributeTypeEnum, StunAttribute> attributeMap = new HashMap<>();
    int start = HEADER_LENGTH_BYTES;

    while (start - HEADER_LENGTH_BYTES < header.getMessageLength() && (start) < data.length) {
        byte[] tp = Arrays.copyOfRange(data, start, start + 2);
        StunAttributeTypeEnum type = StunAttributeTypeEnum.fromBytes(tp);
        start += 2;

        int lgt = SignalUtil.intFromTwoBytes(Arrays.copyOfRange(data, start, start + 2));
        start += 2;

        byte[] bt = Arrays.copyOfRange(data, start, start + lgt);
        String s = new String(bt);
        start += lgt;

        attributeMap.put(type, new StunAttribute(type, bt));

        start = SignalUtil.multipleOfFour(start);
    }

    return new StunMessage(header, attributeMap, true, true, null, null);
}

From source file:bachelorthesis.captchabuilder.builder.BackgroundParser.java

/**
 * Parses the string arguments for rendering a background, creates a
 * BackgroundProducer and passes it to the CaptchaBuilder
 *
 * @param buildSequenceOptions the string arguments for building a
 *                             background
 * @param builder              the CaptchaBuilder Object to be modified
 * <p/>/*from  w w w .j  av a  2 s  . c om*/
 * @return a modified CaptchaBuilder object
 * <p/>
 * @throws org.apache.commons.cli.ParseException
 * @see CaptchaBuilder
 */
public static CaptchaBuilder parse(String[] buildSequenceOptions, CaptchaBuilder builder)
        throws ParseException {
    if (buildSequenceOptions.length == 0) {
        //return builder.addBackground();
        builder.addBuildSequence(new BackgroundProducerBuilder(BackgroundProducerType.TRANSPARENT));
        return builder;
    }

    if (buildSequenceOptions.length > 1) {
        throw new ParseException("Background takes a max of 1 arguments");
    }

    for (String backgroundOption : buildSequenceOptions) {
        if (!backgroundOption.isEmpty()) {
            try {
                String[] optionArgs = backgroundOption.split(CaptchaConstants.buildSequencelvl3Delim);
                BackgroundProducerType backgroundProducerType = BackgroundProducerType.valueOf(optionArgs[0]);
                String[] backgroundOptionArgs = Arrays.copyOfRange(optionArgs, 1, optionArgs.length);
                return parseBackgroundProducer(backgroundProducerType, backgroundOptionArgs, builder);
            } catch (IllegalArgumentException e) {
                throw new ParseException(e.getMessage());
            }
        }
    }

    return builder;
}

From source file:com.dsh105.nexus.util.StringUtil.java

/**
 * Builds a sentence list from an array of strings.
 * Example: {"one", "two", "three"} returns "one, two and three".
 *
 * @param words The string array to build into a list,
 * @return String representing the list.
 *///ww w .  j a  v a2s.  c  o m
public static String buildSentenceList(String[] words) {
    Validate.notEmpty(words);
    if (words.length == 1) {
        return words[0];
    } else if (words.length == 2) {
        return combineSplit(0, words, " and ");
    } else {
        // This is where the fun starts!
        String[] initial = Arrays.copyOfRange(words, 0, words.length - 1);
        String list = combineSplit(0, initial, ", ");
        list += " and " + words[words.length - 1];
        return list;
    }
}