Example usage for java.util Arrays fill

List of usage examples for java.util Arrays fill

Introduction

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

Prototype

public static void fill(Object[] a, Object val) 

Source Link

Document

Assigns the specified Object reference to each element of the specified array of Objects.

Usage

From source file:Main.java

/**
 * Build a String with count chars using fillChar
 * //from  w ww .j a  v a2s . c om
 * @param fillChar
 * @param count
 * @return the String of length count filled with fillChar
 */
public final static String fillString(char fillChar, int count) {
    char[] chars = new char[count];
    Arrays.fill(chars, fillChar);
    return new String(chars);
}

From source file:Main.java

public static byte[] decipherAes256(byte[] encrypedPwdBytes, String password) throws NullPointerException {

    if (password == null || password.length() == 0) {
        throw new NullPointerException("Please give Password");
    }/*from w  ww.j a v a2  s  . c  o  m*/

    if (encrypedPwdBytes == null || encrypedPwdBytes.length <= 0) {
        throw new NullPointerException("Please give encrypedPwdBytes");
    }

    try {
        SecretKey key = getKey(password);

        // IMPORTANT TO GET SAME RESULTS ON iOS and ANDROID
        final byte[] iv = new byte[16];
        Arrays.fill(iv, (byte) 0x00);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        // cipher is not thread safe
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
        byte[] decryptedValueBytes = (cipher.doFinal(encrypedPwdBytes));

        return decryptedValueBytes;

    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static void writeWString(OutputStream out, String s, int fixedLen) throws IOException {
    byte[] bytes = s.getBytes();
    writeShort(out, bytes.length);//w w w  . j av a 2  s .c  o  m
    fixedLen -= 2;

    if (fixedLen <= 0)
        return;

    if (fixedLen <= bytes.length) {
        out.write(bytes, 0, fixedLen);
    } else {
        out.write(bytes);
        byte[] fillBytes = new byte[fixedLen - bytes.length];
        Arrays.fill(fillBytes, (byte) 0);
        out.write(fillBytes);
    }

    out.flush();
}

From source file:co.rewen.statex.AsyncLocalStorageUtil.java

/**
 * Build the String required for an SQL select statement:
 *  WHERE key IN (?, ?, ..., ?)/*ww  w  .java2s . com*/
 * without 'WHERE' and with selectionCount '?'
 */
/* package */
static String buildKeySelection(int selectionCount) {
    String[] list = new String[selectionCount];
    Arrays.fill(list, "?");
    return KEY_COLUMN + " IN (" + TextUtils.join(", ", list) + ")";
}

From source file:Main.java

private static String getString(char c, int length) {
    char[] line = new char[length];
    Arrays.fill(line, c);
    String string = new String(line);
    return string;
}

From source file:Main.java

/**
 * Indent the supplied XML string by the number of spaces specified in the
 * 'indent' param.//from ww w  .  j a  v  a  2s.  com
 * <p/>
 * The indents are only inserted after newlines, where the first non-whitespace character
 * is '<'.
 *
 * @param xml The XML to indent.
 * @param indent The number of spaces to insert as the indent.
 * @return The indented XML string.
 */
public static String indent(String xml, int indent) {
    StringBuffer indentedXml = new StringBuffer();
    int xmlLen = xml.length();
    char[] indentChars = new char[indent];

    Arrays.fill(indentChars, ' ');

    int i = 0;
    while (i < xmlLen) {
        if (isStartOf(xml, i, COMMENT_START)) {
            int commentEnd = xml.indexOf(COMMENT_END, i);
            indentedXml.append(xml, i, commentEnd);
            i = commentEnd;
        } else if (isStartOf(xml, i, CDATA_START)) {
            int cdataEnd = xml.indexOf(CDATA_END, i);
            indentedXml.append(xml, i, cdataEnd);
            i = cdataEnd;
        } else {
            char nextChar = xml.charAt(i);

            indentedXml.append(nextChar);

            if (nextChar == '\n') {
                // We're at the start of a new line.  Need to determine
                // if the next sequence of non-whitespace characters are the start/end of
                // an XML element.  If it is... add an indent before....
                while (i < xmlLen) {
                    i++;

                    char preXmlChar = xml.charAt(i);
                    if (!Character.isWhitespace(preXmlChar)) {
                        if (preXmlChar == '<') {
                            if (!isStartOf(xml, i, COMMENT_START) && !isStartOf(xml, i, CDATA_START)) {
                                indentedXml.append(indentChars);
                            }
                        }
                        break;
                    } else {
                        indentedXml.append(preXmlChar);
                    }
                }
            } else {
                i++;
            }
        }
    }

    return indentedXml.toString();
}

From source file:Main.java

/**
 * Splits the given array into blocks of given size and adds padding to the
 * last one, if necessary.// w  w w  . j a v  a  2 s  .  co  m
 * 
 * @param byteArray
 *            the array.
 * @param blocksize
 *            the block size.
 * @return a list of blocks of given size.
 */
public static List<byte[]> splitAndPad(byte[] byteArray, int blocksize) {
    List<byte[]> blocks = new ArrayList<byte[]>();
    int numBlocks = (int) Math.ceil(byteArray.length / (double) blocksize);

    for (int i = 0; i < numBlocks; i++) {

        byte[] block = new byte[blocksize];
        Arrays.fill(block, (byte) 0x00);
        if (i + 1 == numBlocks) {
            // the last block
            int remainingBytes = byteArray.length - (i * blocksize);
            System.arraycopy(byteArray, i * blocksize, block, 0, remainingBytes);
        } else {
            System.arraycopy(byteArray, i * blocksize, block, 0, blocksize);
        }
        blocks.add(block);
    }

    return blocks;
}

From source file:Main.java

private static String digest(final String value) {
    byte[] digested;
    try {//from ww w.  j  a  v a  2  s.  c o m
        digested = MessageDigest.getInstance(HASH_ALGORITHM).digest(value.getBytes(CHARSET));
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (UnsupportedEncodingException e) {
        return null;
    }

    String hashed = new BigInteger(1, digested).toString(16);
    int padding = HASH_LENGTH - hashed.length();
    if (padding == 0)
        return hashed;

    char[] zeros = new char[padding];
    Arrays.fill(zeros, '0');
    return new StringBuilder(HASH_LENGTH).append(zeros).append(hashed).toString();
}

From source file:Main.java

/**
 * Adds a padding to the given array, such that a new array with the given
 * length is generated./*from  w  w w  .  j a v  a 2 s. co m*/
 * 
 * @param array
 *            the array to be padded.
 * @param value
 *            the padding value.
 * @param newLength
 *            the new length of the padded array.
 * @return the array padded with the given value.
 */
public static byte[] padArray(byte[] array, byte value, int newLength) {
    int length = array.length;
    int paddingLength = newLength - length;

    if (paddingLength < 1) {
        return array;
    } else {
        byte[] padding = new byte[paddingLength];
        Arrays.fill(padding, value);

        return concatenate(array, padding);
    }

}

From source file:de.burlov.amazon.s3.dirsync.CLI.java

/**
 * @param args/* w  ww  . ja  v  a 2  s .  c om*/
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Logger.getLogger("").setLevel(Level.OFF);
    Logger deLogger = Logger.getLogger("de");
    deLogger.setLevel(Level.INFO);
    Handler handler = new ConsoleHandler();
    handler.setFormatter(new VerySimpleFormatter());
    deLogger.addHandler(handler);
    deLogger.setUseParentHandlers(false);
    //      if (true)
    //      {
    //         LogFactory.getLog(CLI.class).error("test msg", new Exception("test extception"));
    //         return;
    //      }
    Options opts = new Options();
    OptionGroup gr = new OptionGroup();

    /*
     * Befehlsgruppe initialisieren
     */
    gr = new OptionGroup();
    gr.setRequired(true);
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download changed or new files").create(CMD_UPDATE));
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download directory snapshot").create(CMD_SNAPSHOT));
    gr.addOption(OptionBuilder.withDescription("Delete remote folder").create(CMD_DELETE_DIR));
    gr.addOption(OptionBuilder.withDescription("Delete a bucket").create(CMD_DELETE_BUCKET));
    gr.addOption(OptionBuilder.create(CMD_HELP));
    gr.addOption(OptionBuilder.create(CMD_VERSION));
    gr.addOption(OptionBuilder.withDescription("Prints summary for stored data").create(CMD_SUMMARY));
    gr.addOption(OptionBuilder.withDescription("Clean up orphaned objekts").create(CMD_CLEANUP));
    gr.addOption(OptionBuilder.withDescription("Changes encryption password").withArgName("new password")
            .hasArg().create(CMD_CHANGE_PASSWORD));
    gr.addOption(OptionBuilder.withDescription("Lists all buckets").create(CMD_LIST_BUCKETS));
    gr.addOption(OptionBuilder.withDescription("Lists raw objects in a bucket").create(CMD_LIST_BUCKET));
    gr.addOption(OptionBuilder.withDescription("Lists files in remote folder").create(CMD_LIST_DIR));
    opts.addOptionGroup(gr);
    /*
     * Parametergruppe initialisieren
     */
    opts.addOption(OptionBuilder.withArgName("key").isRequired(false).hasArg().withDescription("S3 access key")
            .create(OPT_S3S_KEY));
    opts.addOption(OptionBuilder.withArgName("secret").isRequired(false).hasArg()
            .withDescription("Secret key for S3 account").create(OPT_S3S_SECRET));
    opts.addOption(OptionBuilder.withArgName("bucket").isRequired(false).hasArg().withDescription(
            "Optional bucket name for storage. If not specified then an unique bucket name will be generated")
            .create(OPT_BUCKET));
    // opts.addOption(OptionBuilder.withArgName("US|EU").hasArg().
    // withDescription(
    // "Where the new bucket should be created. Default US").create(
    // OPT_LOCATION));
    opts.addOption(OptionBuilder.withArgName("path").isRequired(false).hasArg()
            .withDescription("Local directory path").create(OPT_LOCAL_DIR));
    opts.addOption(OptionBuilder.withArgName("name").isRequired(false).hasArg()
            .withDescription("Remote directory name").create(OPT_REMOTE_DIR));
    opts.addOption(OptionBuilder.withArgName("password").isRequired(false).hasArg()
            .withDescription("Encryption password").create(OPT_ENC_PASSWORD));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs()
            .withDescription("Comma separated exclude file patterns like '*.tmp,*/dir/*.tmp'")
            .create(OPT_EXCLUDE_PATTERNS));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs().withDescription(
            "Comma separated include patterns like '*.java'. If not specified, then all files in specified local directory will be included")
            .create(OPT_INCLUDE_PATTERNS));

    if (args.length == 0) {
        printUsage(opts);
        return;
    }

    CommandLine cmd = null;
    try {
        cmd = new GnuParser().parse(opts, args);
        if (cmd.hasOption(CMD_HELP)) {
            printUsage(opts);
            return;
        }
        if (cmd.hasOption(CMD_VERSION)) {
            System.out.println("s3dirsync version " + Version.CURRENT_VERSION);
            return;
        }
        String awsKey = cmd.getOptionValue(OPT_S3S_KEY);
        String awsSecret = cmd.getOptionValue(OPT_S3S_SECRET);
        String bucket = cmd.getOptionValue(OPT_BUCKET);
        String bucketLocation = cmd.getOptionValue(OPT_LOCATION);
        String localDir = cmd.getOptionValue(OPT_LOCAL_DIR);
        String remoteDir = cmd.getOptionValue(OPT_REMOTE_DIR);
        String password = cmd.getOptionValue(OPT_ENC_PASSWORD);
        String exclude = cmd.getOptionValue(OPT_EXCLUDE_PATTERNS);
        String include = cmd.getOptionValue(OPT_INCLUDE_PATTERNS);

        if (StringUtils.isBlank(awsKey) || StringUtils.isBlank(awsSecret)) {
            System.out.println("S3 account data required");
            return;
        }

        if (StringUtils.isBlank(bucket)) {
            bucket = awsKey + ".dirsync";
        }

        if (cmd.hasOption(CMD_DELETE_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            int deleted = S3Utils.deleteBucket(awsKey, awsSecret, bucket);
            System.out.println("Deleted objects: " + deleted);
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKETS)) {
            for (String str : S3Utils.listBuckets(awsKey, awsSecret)) {
                System.out.println(str);
            }
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            for (String str : S3Utils.listObjects(awsKey, awsSecret, bucket)) {
                System.out.println(str);
            }
            return;
        }
        if (StringUtils.isBlank(password)) {
            System.out.println("Encryption password required");
            return;
        }
        char[] psw = password.toCharArray();
        DirSync ds = new DirSync(awsKey, awsSecret, bucket, bucketLocation, psw);
        ds.setExcludePatterns(parseSubargumenths(exclude));
        ds.setIncludePatterns(parseSubargumenths(include));
        if (cmd.hasOption(CMD_SUMMARY)) {
            ds.printStorageSummary();
            return;
        }
        if (StringUtils.isBlank(remoteDir)) {
            System.out.println("Remote directory name required");
            return;
        }
        if (cmd.hasOption(CMD_DELETE_DIR)) {
            ds.deleteFolder(remoteDir);
            return;
        }
        if (cmd.hasOption(CMD_LIST_DIR)) {
            Folder folder = ds.getFolder(remoteDir);
            if (folder == null) {
                System.out.println("No such folder found: " + remoteDir);
                return;
            }
            for (Map.Entry<String, FileInfo> entry : folder.getIndexData().entrySet()) {
                System.out.println(entry.getKey() + " ("
                        + FileUtils.byteCountToDisplaySize(entry.getValue().getLength()) + ")");
            }
            return;
        }
        if (cmd.hasOption(CMD_CLEANUP)) {
            ds.cleanUp();
            return;
        }
        if (cmd.hasOption(CMD_CHANGE_PASSWORD)) {
            String newPassword = cmd.getOptionValue(CMD_CHANGE_PASSWORD);
            if (StringUtils.isBlank(newPassword)) {
                System.out.println("new password required");
                return;
            }
            char[] chars = newPassword.toCharArray();
            ds.changePassword(chars);
            newPassword = null;
            Arrays.fill(chars, ' ');
            return;
        }
        if (StringUtils.isBlank(localDir)) {
            System.out.println(OPT_LOCAL_DIR + " argument required");
            return;
        }
        String direction = "";
        boolean up = false;
        boolean snapshot = false;
        if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_UPDATE))) {
            direction = cmd.getOptionValue(CMD_UPDATE);
        } else if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_SNAPSHOT))) {
            direction = cmd.getOptionValue(CMD_SNAPSHOT);
            snapshot = true;
        }
        if (StringUtils.isBlank(direction)) {
            System.out.println("Operation direction required");
            return;
        }
        up = StringUtils.equalsIgnoreCase(OPT_UP, direction);
        File baseDir = new File(localDir);
        if (!baseDir.exists() && !baseDir.mkdirs()) {
            System.out.println("Invalid local directory: " + baseDir.getAbsolutePath());
            return;
        }
        ds.syncFolder(baseDir, remoteDir, up, snapshot);

    } catch (DirSyncException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(opts);

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}