Java Code Examples for java.util.Arrays#copyOf()

The following examples show how to use java.util.Arrays#copyOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AvroUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Handles the conversion of each value of the Collection.
 * Converts the Collection to an Object array
 */
public static Object handleMultiValue(Collection values) {

  if (values.isEmpty()) {
    return null;
  }
  int numValues = values.size();
  Object[] array = new Object[numValues];
  int index = 0;
  for (Object value : values) {
    Object convertedValue = convert(value);
    if (convertedValue != null && !convertedValue.toString().equals("")) {
      array[index++] = convertedValue;
    }
  }
  if (index == numValues) {
    return array;
  } else if (index == 0) {
    return null;
  } else {
    return Arrays.copyOf(array, index);
  }
}
 
Example 2
Source File: ThreadGroup.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
void list(PrintStream out, int indent) {
    int ngroupsSnapshot;
    ThreadGroup[] groupsSnapshot;
    synchronized (this) {
        for (int j = 0 ; j < indent ; j++) {
            out.print(" ");
        }
        out.println(this);
        indent += 4;
        for (int i = 0 ; i < nthreads ; i++) {
            for (int j = 0 ; j < indent ; j++) {
                out.print(" ");
            }
            out.println(threads[i]);
        }
        ngroupsSnapshot = ngroups;
        if (groups != null) {
            groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
        } else {
            groupsSnapshot = null;
        }
    }
    for (int i = 0 ; i < ngroupsSnapshot ; i++) {
        groupsSnapshot[i].list(out, indent);
    }
}
 
Example 3
Source File: CopyOnWriteArrayList.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts the specified element at the specified position in this
 * list. Shifts the element currently at that position (if any) and
 * any subsequent elements to the right (adds one to their indices).
 *
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public void add(int index, E element) {
    synchronized (lock) {
        Object[] es = getArray();
        int len = es.length;
        if (index > len || index < 0)
            throw new IndexOutOfBoundsException(outOfBounds(index, len));
        Object[] newElements;
        int numMoved = len - index;
        if (numMoved == 0)
            newElements = Arrays.copyOf(es, len + 1);
        else {
            newElements = new Object[len + 1];
            System.arraycopy(es, 0, newElements, 0, index);
            System.arraycopy(es, index, newElements, index + 1,
                             numMoved);
        }
        newElements[index] = element;
        setArray(newElements);
    }
}
 
Example 4
Source File: CipherCore.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Continues a multiple-part encryption or decryption operation
 * (depending on how this cipher was initialized), processing another data
 * part.
 *
 * <p>The first <code>inputLen</code> bytes in the <code>input</code>
 * buffer, starting at <code>inputOffset</code>, are processed, and the
 * result is stored in a new buffer.
 *
 * @param input the input buffer
 * @param inputOffset the offset in <code>input</code> where the input
 * starts
 * @param inputLen the input length
 *
 * @return the new buffer with the result
 *
 * @exception IllegalStateException if this cipher is in a wrong state
 * (e.g., has not been initialized)
 */
byte[] update(byte[] input, int inputOffset, int inputLen) {
    checkReinit();

    byte[] output = null;
    try {
        output = new byte[getOutputSizeByOperation(inputLen, false)];
        int len = update(input, inputOffset, inputLen, output,
                         0);
        if (len == output.length) {
            return output;
        } else {
            byte[] copy = Arrays.copyOf(output, len);
            if (decrypting) {
                // Zero out internal buffer which is no longer required
                Arrays.fill(output, (byte) 0x00);
            }
            return copy;
        }
    } catch (ShortBufferException e) {
        // should never happen
        throw new ProviderException("Unexpected exception", e);
    }
}
 
Example 5
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static byte[] getAdditionalAuthenticationData(String headersJson, byte[] aad) {
    byte[] headersAAD = JweHeaders.toCipherAdditionalAuthData(headersJson);
    if (aad != null) {
        // JWE JSON can provide the extra aad
        byte[] newAAD = Arrays.copyOf(headersAAD, headersAAD.length + 1 + aad.length);
        newAAD[headersAAD.length] = '.';
        System.arraycopy(aad, 0, newAAD, headersAAD.length + 1, aad.length);
        return newAAD;
    }
    return headersAAD;
}
 
Example 6
Source File: HARAMNetwork.java    From meka with GNU General Public License v3.0 5 votes vote down vote up
private void ARAMm_Add_New_Category() {

		weightsA = Arrays.copyOf(weightsA, numCategories + 1);
		weightsB = Arrays.copyOf(weightsB, numCategories + 1);
		weightsA[numCategories] = new double[numFeatures];
		weightsB[numCategories] = new double[numClasses];
		Arrays.fill(weightsA[numCategories], 1.0);
		Arrays.fill(weightsB[numCategories], 0.0);
		numCategories += 1;

	}
 
Example 7
Source File: BasicHistoryUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testAutoResolveConflicts() throws Exception {

    final PatchingTestBuilder builder = createDefaultBuilder();

    // Create a file
    final File existing = builder.getFile(FILE_EXISTING);
    touch(existing);
    dump(existing, randomString());
    final byte[] existingHash = hashFile(existing);
    final byte[] initialHash = Arrays.copyOf(existingHash, existingHash.length);

    final byte[] moduleHash = new byte[20];

    final PatchingTestStepBuilder oo1 = builder.createStepBuilder();
    oo1.setPatchId("one-off-one")
            .oneOffPatchIdentity(PRODUCT_VERSION)
            .updateFileWithRandomContent(initialHash, existingHash, FILE_EXISTING)
            .oneOffPatchElement("base-one-off", "base", false)
            .addModuleWithRandomContent("test.module", moduleHash)
    ;
    // Apply OO1
    apply(oo1);

    final PatchingTestStepBuilder cp1 = builder.createStepBuilder();
    cp1.setPatchId("CP1")
            .upgradeIdentity(PRODUCT_VERSION, PRODUCT_VERSION)
            .updateFileWithRandomContent(initialHash, existingHash, FILE_EXISTING)
            .upgradeElement("base-cp1", "base", false)
            .addModuleWithRandomContent("test.module", moduleHash)
    ;
    // Apply CP1
    apply(cp1);
    rollback(cp1);
    rollback(oo1);
}
 
Example 8
Source File: MultiTaskListener.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void add(TaskListener listener) {
    for (TaskListener l: listeners) {
        if (ccw.unwrap(l) == listener)
            throw new IllegalStateException();
    }
    listeners = Arrays.copyOf(listeners, listeners.length + 1);
    listeners[listeners.length - 1] = ccw.wrap(listener);
}
 
Example 9
Source File: PriorityBlockingQueue.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a {@code PriorityBlockingQueue} containing the elements
 * in the specified collection.  If the specified collection is a
 * {@link SortedSet} or a {@link PriorityQueue}, this
 * priority queue will be ordered according to the same ordering.
 * Otherwise, this priority queue will be ordered according to the
 * {@linkplain Comparable natural ordering} of its elements.
 *
 * @param  c the collection whose elements are to be placed
 *         into this priority queue
 * @throws ClassCastException if elements of the specified collection
 *         cannot be compared to one another according to the priority
 *         queue's ordering
 * @throws NullPointerException if the specified collection or any
 *         of its elements are null
 */
public PriorityBlockingQueue(Collection<? extends E> c) {
    this.lock = new ReentrantLock();
    this.notEmpty = lock.newCondition();
    boolean heapify = true; // true if not known to be in heap order
    boolean screen = true;  // true if must screen for nulls
    if (c instanceof SortedSet<?>) {
        SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
        this.comparator = (Comparator<? super E>) ss.comparator();
        heapify = false;
    }
    else if (c instanceof PriorityBlockingQueue<?>) {
        PriorityBlockingQueue<? extends E> pq =
            (PriorityBlockingQueue<? extends E>) c;
        this.comparator = (Comparator<? super E>) pq.comparator();
        screen = false;
        if (pq.getClass() == PriorityBlockingQueue.class) // exact match
            heapify = false;
    }
    Object[] a = c.toArray();
    int n = a.length;
    // If c.toArray incorrectly doesn't return Object[], copy it.
    if (a.getClass() != Object[].class)
        a = Arrays.copyOf(a, n, Object[].class);
    if (screen && (n == 1 || this.comparator != null)) {
        for (int i = 0; i < n; ++i)
            if (a[i] == null)
                throw new NullPointerException();
    }
    this.queue = a;
    this.size = n;
    if (heapify)
        heapify();
}
 
Example 10
Source File: AbstractHeapPriorityQueue.java    From flink with Apache License 2.0 5 votes vote down vote up
protected void resizeQueueArray(int desiredSize, int minRequiredSize) {
	if (isValidArraySize(desiredSize)) {
		queue = Arrays.copyOf(queue, desiredSize);
	} else if (isValidArraySize(minRequiredSize)) {
		queue = Arrays.copyOf(queue, MAX_ARRAY_SIZE);
	} else {
		throw new OutOfMemoryError("Required minimum heap size " + minRequiredSize +
			" exceeds maximum size of " + MAX_ARRAY_SIZE + ".");
	}
}
 
Example 11
Source File: Window.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static Window[] getWindows(AppContext appContext) {
    synchronized (Window.class) {
        Window realCopy[];
        @SuppressWarnings("unchecked")
        Vector<WeakReference<Window>> windowList =
            (Vector<WeakReference<Window>>)appContext.get(Window.class);
        if (windowList != null) {
            int fullSize = windowList.size();
            int realSize = 0;
            Window fullCopy[] = new Window[fullSize];
            for (int i = 0; i < fullSize; i++) {
                Window w = windowList.get(i).get();
                if (w != null) {
                    fullCopy[realSize++] = w;
                }
            }
            if (fullSize != realSize) {
                realCopy = Arrays.copyOf(fullCopy, realSize);
            } else {
                realCopy = fullCopy;
            }
        } else {
            realCopy = new Window[0];
        }
        return realCopy;
    }
}
 
Example 12
Source File: SpinedBuffer.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String toString() {
    int[] array = asPrimitiveArray();
    if (array.length < 200) {
        return String.format("%s[length=%d, chunks=%d]%s",
                             getClass().getSimpleName(), array.length,
                             spineIndex, Arrays.toString(array));
    }
    else {
        int[] array2 = Arrays.copyOf(array, 200);
        return String.format("%s[length=%d, chunks=%d]%s...",
                             getClass().getSimpleName(), array.length,
                             spineIndex, Arrays.toString(array2));
    }
}
 
Example 13
Source File: ZToolAddress64.java    From zigbee4java with Apache License 2.0 4 votes vote down vote up
public ZToolAddress64(byte[] address) {
    this.address = Arrays.copyOf(address, address.length);
}
 
Example 14
Source File: MediaSource.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * @return application capabilities
 */
public String[] getCapabilities() {
    return mCapabilities == null ? null : Arrays.copyOf(mCapabilities, mCapabilities.length);
}
 
Example 15
Source File: StringAttributeDescription.java    From constellation with Apache License 2.0 4 votes vote down vote up
@Override
public Object saveData() {
    return Arrays.copyOf(data, data.length);
}
 
Example 16
Source File: ZipFile.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private int getEntryPos(byte[] name, boolean addSlash) {
    if (total == 0) {
        return -1;
    }
    int hsh = hashN(name, 0, name.length);
    int idx = table[(hsh & 0x7fffffff) % tablelen];
    /*
     * This while loop is an optimization where a double lookup
     * for name and name+/ is being performed. The name char
     * array has enough room at the end to try again with a
     * slash appended if the first table lookup does not succeed.
     */
    while(true) {
        /*
         * Search down the target hash chain for a entry whose
         * 32 bit hash matches the hashed name.
         */
        while (idx != ZIP_ENDCHAIN) {
            if (getEntryHash(idx) == hsh) {
                // The CEN name must match the specfied one
                int pos = getEntryPos(idx);
                if (name.length == CENNAM(cen, pos)) {
                    boolean matched = true;
                    int nameoff = pos + CENHDR;
                    for (int i = 0; i < name.length; i++) {
                        if (name[i] != cen[nameoff++]) {
                            matched = false;
                            break;
                        }
                    }
                    if (matched) {
                        return pos;
                    }
                 }
            }
            idx = getEntryNext(idx);
        }
        /* If not addSlash, or slash is already there, we are done */
        if (!addSlash  || name.length == 0 || name[name.length - 1] == '/') {
             return -1;
        }
        /* Add slash and try once more */
        name = Arrays.copyOf(name, name.length + 1);
        name[name.length - 1] = '/';
        hsh = hash_append(hsh, (byte)'/');
        //idx = table[hsh % tablelen];
        idx = table[(hsh & 0x7fffffff) % tablelen];
        addSlash = false;
    }
}
 
Example 17
Source File: TInstanceGenerator.java    From sql-layer with GNU Affero General Public License v3.0 4 votes vote down vote up
public TInstanceGenerator(TClass tclass, int... attrs) {
    this.tclass = tclass;
    this.attrs = Arrays.copyOf(attrs, attrs.length);
}
 
Example 18
Source File: DefaultCallQuery.java    From terracotta-platform with Apache License 2.0 4 votes vote down vote up
@Override
public Parameter[] getParameters() {
  return Arrays.copyOf(parameters, parameters.length);
}
 
Example 19
Source File: NTLM.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
byte[] ntlm2NTLM(byte[] ntlmHash, byte[] nonce, byte[] challenge) {
    byte[] b = Arrays.copyOf(challenge, 16);
    System.arraycopy(nonce, 0, b, 8, 8);
    byte[] sesshash = Arrays.copyOf(md5.digest(b), 8);
    return calcResponse(ntlmHash, sesshash);
}
 
Example 20
Source File: LLDPOrganizationalTLV.java    From floodlight_with_topoguard with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the value of the OUI.
 * @return The value of the OUI .
 */
public byte[] getOUI() {
    return Arrays.copyOf(oui, oui.length);
}