@NotNull
 public static char[] adaptiveLoadText(@NotNull Reader reader) throws IOException {
   char[] chars = new char[4096];
   List<char[]> buffers = null;
   int count = 0;
   int total = 0;
   while (true) {
     int n = reader.read(chars, count, chars.length - count);
     if (n <= 0) break;
     count += n;
     if (total > 1024 * 1024 * 10) throw new FileTooBigException("File too big " + reader);
     total += n;
     if (count == chars.length) {
       if (buffers == null) {
         buffers = new ArrayList<char[]>();
       }
       buffers.add(chars);
       int newLength = Math.min(1024 * 1024, chars.length * 2);
       chars = new char[newLength];
       count = 0;
     }
   }
   char[] result = new char[total];
   if (buffers != null) {
     for (char[] buffer : buffers) {
       System.arraycopy(buffer, 0, result, result.length - total, buffer.length);
       total -= buffer.length;
     }
   }
   System.arraycopy(chars, 0, result, result.length - total, total);
   return result;
 }
예제 #2
0
  public void init() {
    gen_begin[0] = 0;
    ply = 0;
    hdp = 0;
    side = LIGHT;
    xside = DARK;
    computerside = DARK;

    int[] clr = {
      0, 0, 0, 0, 0, 0, 0, 0, 0,
      7, 7, 7, 7, 7, 7, 7, 7, 7,
      7, 0, 7, 7, 7, 7, 7, 0, 7,
      0, 7, 0, 7, 0, 7, 0, 7, 0,
      7, 7, 7, 7, 7, 7, 7, 7, 7,
      7, 7, 7, 7, 7, 7, 7, 7, 7,
      1, 7, 1, 7, 1, 7, 1, 7, 1,
      7, 1, 7, 7, 7, 7, 7, 1, 7,
      7, 7, 7, 7, 7, 7, 7, 7, 7,
      1, 1, 1, 1, 1, 1, 1, 1, 1
    };
    int[] pc = {
      5, 3, 2, 1, 6, 1, 2, 3, 5,
      7, 7, 7, 7, 7, 7, 7, 7, 7,
      7, 4, 7, 7, 7, 7, 7, 4, 7,
      0, 7, 0, 7, 0, 7, 0, 7, 0,
      7, 7, 7, 7, 7, 7, 7, 7, 7,
      7, 7, 7, 7, 7, 7, 7, 7, 7,
      0, 7, 0, 7, 0, 7, 0, 7, 0,
      7, 4, 7, 7, 7, 7, 7, 4, 7,
      7, 7, 7, 7, 7, 7, 7, 7, 7,
      5, 3, 2, 1, 6, 1, 2, 3, 5
    };
    System.arraycopy(clr, 0, color, 0, clr.length);
    System.arraycopy(pc, 0, piece, 0, pc.length);
  }
예제 #3
0
  /**
   * Will fill the current buffer from current 'index' position, expanding it and or shuffling it if
   * necessary
   */
  private void fill() {
    if (this.index >= this.buffer.length) {
      if (this.mark == 0) { // expand
        byte[] newBuff = new byte[this.buffer.length + this.initialBufferSize];
        System.arraycopy(this.buffer, 0, newBuff, 0, this.buffer.length);
        this.buffer = newBuff;
      } else { // shuffle
        int length = this.index - this.mark;
        System.arraycopy(this.buffer, this.mark, this.buffer, 0, length);
        this.index = length;
        this.mark = 0;
      }
    }

    try {
      int bytesRead;
      do {
        bytesRead = this.is.read(this.buffer, this.index, this.buffer.length - this.index);
      } while (bytesRead == 0);

      if (bytesRead != -1) {
        this.readAheadLength = this.index + bytesRead;
        if (this.readAheadLength > this.maxDataSize) {
          throw new IllegalStateException(
              "Maximum allowed data size of " + this.maxDataSize + " exceeded.");
        }
      }
    } catch (IOException e) {
      throw new IllegalStateException("Failed while reading InputStream", e);
    }
  }
 @NotNull
 public static byte[] adaptiveLoadBytes(@NotNull InputStream stream) throws IOException {
   byte[] bytes = new byte[4096];
   List<byte[]> buffers = null;
   int count = 0;
   int total = 0;
   while (true) {
     int n = stream.read(bytes, count, bytes.length - count);
     if (n <= 0) break;
     count += n;
     if (total > 1024 * 1024 * 10) throw new FileTooBigException("File too big " + stream);
     total += n;
     if (count == bytes.length) {
       if (buffers == null) {
         buffers = new ArrayList<byte[]>();
       }
       buffers.add(bytes);
       int newLength = Math.min(1024 * 1024, bytes.length * 2);
       bytes = new byte[newLength];
       count = 0;
     }
   }
   byte[] result = new byte[total];
   if (buffers != null) {
     for (byte[] buffer : buffers) {
       System.arraycopy(buffer, 0, result, result.length - total, buffer.length);
       total -= buffer.length;
     }
   }
   System.arraycopy(bytes, 0, result, result.length - total, total);
   return result;
 }
예제 #5
0
파일: IdPreMap.java 프로젝트: fpapai/basex
 /**
  * Adds a record to the table and the ID index.
  *
  * @param i index in the table where the record should be inserted
  * @param pre pre value
  * @param fid first ID value
  * @param nid last ID value
  * @param inc increment value
  * @param oid original ID value
  */
 private void add(
     final int i, final int pre, final int fid, final int nid, final int inc, final int oid) {
   if (rows == pres.length) {
     final int s = Array.newSize(rows);
     pres = Arrays.copyOf(pres, s);
     fids = Arrays.copyOf(fids, s);
     nids = Arrays.copyOf(nids, s);
     incs = Arrays.copyOf(incs, s);
     oids = Arrays.copyOf(oids, s);
   }
   if (i < rows) {
     final int destPos = i + 1;
     final int length = rows - i;
     System.arraycopy(pres, i, pres, destPos, length);
     System.arraycopy(fids, i, fids, destPos, length);
     System.arraycopy(nids, i, nids, destPos, length);
     System.arraycopy(incs, i, incs, destPos, length);
     System.arraycopy(oids, i, oids, destPos, length);
   }
   pres[i] = pre;
   fids[i] = fid;
   nids[i] = nid;
   incs[i] = inc;
   oids[i] = oid;
   ++rows;
 }
예제 #6
0
  /**
   * Populate data from this array as if it was in local file data.
   *
   * @param data an array of bytes
   * @param offset the start offset
   * @param length the number of bytes in the array from offset
   * @since 1.1
   * @throws ZipException on error
   */
  public void parseFromLocalFileData(byte[] data, int offset, int length) throws ZipException {

    long givenChecksum = ZipLong.getValue(data, offset);
    byte[] tmp = new byte[length - WORD];
    System.arraycopy(data, offset + WORD, tmp, 0, length - WORD);
    crc.reset();
    crc.update(tmp);
    long realChecksum = crc.getValue();
    if (givenChecksum != realChecksum) {
      throw new ZipException(
          "bad CRC checksum "
              + Long.toHexString(givenChecksum)
              + " instead of "
              + Long.toHexString(realChecksum));
    }

    int newMode = ZipShort.getValue(tmp, 0);
    // CheckStyle:MagicNumber OFF
    byte[] linkArray = new byte[(int) ZipLong.getValue(tmp, 2)];
    uid = ZipShort.getValue(tmp, 6);
    gid = ZipShort.getValue(tmp, 8);

    if (linkArray.length == 0) {
      link = "";
    } else {
      System.arraycopy(tmp, 10, linkArray, 0, linkArray.length);
      link = new String(linkArray);
    }
    // CheckStyle:MagicNumber ON
    setDirectory((newMode & DIR_FLAG) != 0);
    setMode(newMode);
  }
예제 #7
0
 public PropertyDescriptor[] getPropertyDescriptors() {
   PropertyDescriptor[] pds = super.properties;
   PropertyDescriptor[] ps = new PropertyDescriptor[pds.length + properties.length];
   System.arraycopy(pds, 0, ps, 0, pds.length);
   System.arraycopy(properties, 0, ps, pds.length, properties.length);
   return ps;
 }
  private char[] convertReader(Reader reader) {
    ArrayList<char[]> segments = new ArrayList<char[]>();

    // Gather segments.
    int nrOfWholeSegments = -1;
    int bytesRead;
    do {
      char[] segment = new char[STREAM_READ_SEGMENT_SIZE];
      try {
        bytesRead = reader.read(segment, 0, STREAM_READ_SEGMENT_SIZE);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }

      segments.add(segment);
      ++nrOfWholeSegments;
    } while (bytesRead == STREAM_READ_SEGMENT_SIZE);

    // Glue the segments together.
    char[] segment = segments.get(nrOfWholeSegments);
    char[] input;
    if (bytesRead != -1) {
      input = new char[(nrOfWholeSegments * STREAM_READ_SEGMENT_SIZE) + bytesRead];
      System.arraycopy(
          segment, 0, input, (nrOfWholeSegments * STREAM_READ_SEGMENT_SIZE), bytesRead);
    } else {
      input = new char[(nrOfWholeSegments * STREAM_READ_SEGMENT_SIZE)];
    }
    for (int i = nrOfWholeSegments - 1; i >= 0; --i) {
      segment = segments.get(i);
      System.arraycopy(segment, 0, input, (i * STREAM_READ_SEGMENT_SIZE), STREAM_READ_SEGMENT_SIZE);
    }

    return input;
  }
  public int read(byte[] inBuf, int start, int count) throws IOException {

    if (bufPos >= buf.length) {
      int actual = fill(); // read and unwrap next SASL buffer
      while (actual == 0) { // ignore zero length content
        actual = fill();
      }
      if (actual == -1) {
        return -1; // EOF
      }
    }

    int avail = buf.length - bufPos;
    if (count > avail) {
      // Requesting more that we have stored
      // Return all that we have; next invocation of read() will
      // trigger fill()
      System.arraycopy(buf, bufPos, inBuf, start, avail);
      bufPos = buf.length;
      return avail;
    } else {
      // Requesting less than we have stored
      // Return all that was requested
      System.arraycopy(buf, bufPos, inBuf, start, count);
      bufPos += count;
      return count;
    }
  }
예제 #10
0
 /** 将byte[] b数组,拼接到byte[] a数组后面,返回拼接后的byte[]数组 */
 public static byte[] mergArray(byte[] a, byte[] b) {
   byte[] c = null;
   c = new byte[a.length + b.length];
   System.arraycopy(a, 0, c, 0, a.length);
   System.arraycopy(b, 0, c, a.length, b.length);
   return c;
 }
예제 #11
0
 /**
  * Remove the occurrence of a given value in a copied slice of array defined by the array part
  * from [begin, begin+length).
  *
  * @param values the input array
  * @param begin start index of the array to include
  * @param length number of elements to include from begin
  * @param removedValue the value to be removed from the sliced array
  * @return the copy of the sliced array after removing the removedValue
  */
 private static double[] removeAndSlice(
     final double[] values, final int begin, final int length, final double removedValue) {
   MathArrays.verifyValues(values, begin, length);
   final double[] temp;
   // BitSet(length) to indicate where the removedValue is located
   final BitSet bits = new BitSet(length);
   for (int i = begin; i < begin + length; i++) {
     if (Precision.equalsIncludingNaN(removedValue, values[i])) {
       bits.set(i - begin);
     }
   }
   // Check if empty then create a new copy
   if (bits.isEmpty()) {
     temp = copyOf(values, begin, length); // Nothing removed, just copy
   } else if (bits.cardinality() == length) {
     temp = new double[0]; // All removed, just empty
   } else { // Some removable, so new
     temp = new double[length - bits.cardinality()];
     int start = begin; // start index from source array (i.e values)
     int dest = 0; // dest index in destination array(i.e temp)
     int nextOne = -1; // nextOne is the index of bit set of next one
     int bitSetPtr = 0; // bitSetPtr is start index pointer of bitset
     while ((nextOne = bits.nextSetBit(bitSetPtr)) != -1) {
       final int lengthToCopy = nextOne - bitSetPtr;
       System.arraycopy(values, start, temp, dest, lengthToCopy);
       dest += lengthToCopy;
       start = begin + (bitSetPtr = bits.nextClearBit(nextOne));
     }
     // Copy any residue past start index till begin+length
     if (start < begin + length) {
       System.arraycopy(values, start, temp, dest, begin + length - start);
     }
   }
   return temp;
 }
예제 #12
0
  public byte[] decryptSAMFileRowWithComm(
      String filenamePrefix, byte bytesRow[], byte cryptKey[], byte IVec[]) {
    try {
      if (fileNamePrefix.contains(filenamePrefix)) {
        List<byte[]> outBytesList = new ArrayList<byte[]>();

        int nStartIndex = 0, nEndIndex = 0;
        int totalColumnSize = Integer.parseInt(mapColumnSize.get(filenamePrefix + ".0"));
        for (int i = 1; i <= totalColumnSize; i++) {
          int nColumnSize = Integer.parseInt(mapColumnSize.get(filenamePrefix + "." + i));
          String encryptMode = mapEncryptMode.get(filenamePrefix + "." + i);

          if (FIELD_CRYPT_ALOG_SHA256.equalsIgnoreCase(encryptMode)) {
            nColumnSize = 44;
          }

          nEndIndex = nStartIndex + nColumnSize;

          byte inputBytes[] = new byte[nColumnSize];
          System.arraycopy(bytesRow, nStartIndex, inputBytes, 0, nColumnSize);

          nStartIndex = nEndIndex + 1; // with comma

          if (FIELD_CRYPT_ALOG_PLAINTEXT.equalsIgnoreCase(encryptMode)) {
            outBytesList.add(inputBytes);
          } else if (FIELD_CRYPT_ALOG_SHA256.equalsIgnoreCase(encryptMode)) {
            outBytesList.add(inputBytes);
          } else if (FIELD_CRYPT_ALOG_SEED_CBC.equalsIgnoreCase(encryptMode)) {
            outBytesList.add(decryptWithSEED128CBC(inputBytes, cryptKey, IVec));
          } else if (FIELD_CRYPT_ALOG_ARIA128.equalsIgnoreCase(encryptMode)) {
            outBytesList.add(decryptWithARIA128CBC(inputBytes, cryptKey, mARIA128IVec));
          } else if (FIELD_CRYPT_ALOG_ARIA256.equalsIgnoreCase(encryptMode)) {
            outBytesList.add(decryptWithARIA256CBC(inputBytes, cryptKey, mARIA256IVec));
          }
        }

        int nBytesIndex = 0, totalBytesLength = 0;
        for (int i = 0; i < outBytesList.size(); i++) {
          if (i > 0) totalBytesLength++; // with comma
          totalBytesLength += outBytesList.get(i).length;
        }

        byte outBytes[] = new byte[totalBytesLength];

        for (int i = 0; i < outBytesList.size(); i++) {
          if (i > 0) outBytes[nBytesIndex++] = bCOMMA;
          System.arraycopy(
              outBytesList.get(i), 0, outBytes, nBytesIndex, outBytesList.get(i).length);
          nBytesIndex += outBytesList.get(i).length;
        }

        return outBytes;
      } else {
        return null;
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }
예제 #13
0
  /**
   * Merges the view states contained in the given list into a single view. <br>
   * The view is the concatenation of the different views, according to the order provided by the
   * list itself. The version is the smallest all the versions.
   *
   * @param l A list conatining the view states to merge
   * @return the merged view state.
   * @throws AppiaGroupException See {@linkplain ViewState#ViewState(String, Group, ViewID,
   *     ViewID[], Endpt[], InetWithPort[])}
   * @throws NullPointerException See {@linkplain ViewState#ViewState(String, Group, ViewID,
   *     ViewID[], Endpt[], InetWithPort[])}
   */
  public static ViewState merge(List l) throws NullPointerException, AppiaGroupException {
    ListIterator iter = l.listIterator(l.size());
    int viewsize = 0;
    int prevsize = 0;
    while (iter.hasPrevious()) {
      ViewState aux = (ViewState) iter.previous();
      viewsize += aux.view.length;
      prevsize += aux.previous.length;
    }

    String v = null;
    Group g = null;
    ViewID vid = null;
    ViewID[] prevs = new ViewID[prevsize];
    Endpt[] endpts = new Endpt[viewsize];
    InetSocketAddress[] addrs = new InetSocketAddress[viewsize];
    int iprevs = 0, iendpts = 0, iaddrs = 0;

    while (iter.hasNext()) {
      ViewState aux = (ViewState) iter.next();
      if ((v == null) || (aux.version.compareTo(v) < 0)) v = aux.version;
      if (g == null) g = aux.group;
      if (vid == null) vid = aux.id;
      else if (aux.id.ltime > vid.ltime) vid.ltime = aux.id.ltime;
      System.arraycopy(aux.previous, 0, prevs, iprevs, aux.previous.length);
      iprevs += aux.previous.length;
      System.arraycopy(aux.view, 0, endpts, iendpts, aux.view.length);
      iendpts += aux.view.length;
      System.arraycopy(aux.addresses, 0, addrs, iaddrs, aux.addresses.length);
      iaddrs += aux.addresses.length;
    }

    return new ViewState(v, g, vid, prevs, endpts, addrs);
  }
예제 #14
0
 /**
  * Convert to a human readable (BASE58) address with network and type prefixes.
  *
  * @param address
  * @return human readable representation of the address
  * @throws ValidationException
  */
 public static String toSatoshiStyle(Address address) throws ValidationException {
   byte[] keyDigest = address.toByteArray();
   int addressFlag;
   if (address.getNetwork() == Network.PRODUCTION) {
     if (address.getType() == Address.Type.COMMON) {
       addressFlag = 0x0;
     } else if (address.getType() == Address.Type.P2SH) {
       addressFlag = 0x5;
     } else {
       throw new ValidationException("unknown address type");
     }
   } else if (address.getNetwork() == Network.TEST) {
     if (address.getType() == Address.Type.COMMON) {
       addressFlag = 0x6f;
     } else if (address.getType() == Address.Type.P2SH) {
       addressFlag = 196;
     } else {
       throw new ValidationException("unknown address type");
     }
   } else {
     throw new ValidationException("unknown network");
   }
   byte[] addressBytes = new byte[1 + keyDigest.length + 4];
   addressBytes[0] = (byte) (addressFlag & 0xff);
   System.arraycopy(keyDigest, 0, addressBytes, 1, keyDigest.length);
   byte[] check = Hash.hash(addressBytes, 0, keyDigest.length + 1);
   System.arraycopy(check, 0, addressBytes, keyDigest.length + 1, 4);
   return ByteUtils.toBase58(addressBytes);
 }
예제 #15
0
  // Method to read 8 bit BMP image data
  private Image read8Bit(int paletteEntries) throws IOException, BadElementException {
    byte bdata[] = new byte[width * height];
    // Padding bytes at the end of each scanline
    int padding = 0;

    // width * bitsPerPixel should be divisible by 32
    int bitsPerScanline = width * 8;
    if (bitsPerScanline % 32 != 0) {
      padding = (bitsPerScanline / 32 + 1) * 32 - bitsPerScanline;
      padding = (int) Math.ceil(padding / 8.0);
    }

    int imSize = (width + padding) * height;

    // Read till we have the whole image
    byte values[] = new byte[imSize];
    int bytesRead = 0;
    while (bytesRead < imSize) {
      bytesRead += inputStream.read(values, bytesRead, imSize - bytesRead);
    }

    if (isBottomUp) {

      // Convert the bottom up image to a top down format by copying
      // one scanline from the bottom to the top at a time.
      for (int i = 0; i < height; i++) {
        System.arraycopy(values, imSize - (i + 1) * (width + padding), bdata, i * width, width);
      }
    } else {
      for (int i = 0; i < height; i++) {
        System.arraycopy(values, i * (width + padding), bdata, i * width, width);
      }
    }
    return indexedModel(bdata, 8, paletteEntries);
  }
예제 #16
0
  /**
   * Copies outer join data from a source MultiJoinRel to a new set of arrays. Also adjusts the
   * conditions to reflect the new position of an input if that input ends up being shifted to the
   * right.
   *
   * @param multiJoinRel the source MultiJoinRel
   * @param destConds the array where the join conditions will be copied
   * @param destJoinTypes the array where the join types will be copied
   * @param destPos starting position in the array where the copying starts
   * @param adjustmentAmount if > 0, the amount the RexInputRefs in the join conditions need to be
   *     adjusted by
   * @param srcFields the source fields that the original join conditions are referencing
   * @param destFields the destination fields that the new join conditions will be referencing
   */
  private void copyOuterJoinInfo(
      MultiJoinRel multiJoinRel,
      RexNode[] destConds,
      JoinRelType[] destJoinTypes,
      int destPos,
      int adjustmentAmount,
      RelDataTypeField[] srcFields,
      RelDataTypeField[] destFields) {
    RexNode[] srcConds = multiJoinRel.getOuterJoinConditions();
    JoinRelType[] srcJoinTypes = multiJoinRel.getJoinTypes();
    RexBuilder rexBuilder = multiJoinRel.getCluster().getRexBuilder();

    int len = srcConds.length;
    System.arraycopy(srcJoinTypes, 0, destJoinTypes, destPos, len);

    if (adjustmentAmount == 0) {
      System.arraycopy(srcConds, 0, destConds, 0, len);
    } else {
      int nFields = srcFields.length;
      int[] adjustments = new int[nFields];
      for (int idx = 0; idx < nFields; idx++) {
        adjustments[idx] = adjustmentAmount;
      }
      for (int i = 0; i < len; i++) {
        if (srcConds[i] != null) {
          destConds[i + destPos] =
              srcConds[i].accept(
                  new RelOptUtil.RexInputConverter(rexBuilder, srcFields, destFields, adjustments));
        }
      }
    }
  }
  @Override
  public ArrayData fastSplice(final int start, final int removed, final int added)
      throws UnsupportedOperationException {
    final long oldLength = length();
    final long newLength = oldLength - removed + added;
    if (newLength > SparseArrayData.MAX_DENSE_LENGTH && newLength > array.length) {
      throw new UnsupportedOperationException();
    }
    final ArrayData returnValue =
        removed == 0
            ? EMPTY_ARRAY
            : new NumberArrayData(Arrays.copyOfRange(array, start, start + removed), removed);

    if (newLength != oldLength) {
      final double[] newArray;

      if (newLength > array.length) {
        newArray = new double[ArrayData.nextSize((int) newLength)];
        System.arraycopy(array, 0, newArray, 0, start);
      } else {
        newArray = array;
      }

      System.arraycopy(
          array, start + removed, newArray, start + added, (int) (oldLength - start - removed));
      array = newArray;
      setLength(newLength);
    }

    return returnValue;
  }
예제 #18
0
    /**
     * Copy the state from the next one into this instance (the previous state placeholder). Used to
     * save the previous state when we are advancing the seeker to the next key/value.
     */
    protected void copyFromNext(SeekerState nextState) {
      if (keyBuffer.length != nextState.keyBuffer.length) {
        keyBuffer = nextState.keyBuffer.clone();
      } else if (!isValid()) {
        // Note: we can only call isValid before we override our state, so this
        // comes before all the assignments at the end of this method.
        System.arraycopy(nextState.keyBuffer, 0, keyBuffer, 0, nextState.keyLength);
      } else {
        // don't copy the common prefix between this key and the previous one
        System.arraycopy(
            nextState.keyBuffer,
            nextState.lastCommonPrefix,
            keyBuffer,
            nextState.lastCommonPrefix,
            nextState.keyLength - nextState.lastCommonPrefix);
      }
      currentKey = nextState.currentKey;

      valueOffset = nextState.valueOffset;
      keyLength = nextState.keyLength;
      valueLength = nextState.valueLength;
      lastCommonPrefix = nextState.lastCommonPrefix;
      nextKvOffset = nextState.nextKvOffset;
      memstoreTS = nextState.memstoreTS;
      currentBuffer = nextState.currentBuffer;
      tagsOffset = nextState.tagsOffset;
      tagsLength = nextState.tagsLength;
      if (nextState.tagCompressionContext != null) {
        tagCompressionContext = nextState.tagCompressionContext;
      }
    }
예제 #19
0
 /**
  * @param colors A color buffer
  * @param i The index in this buffer where to put the 12 components of this quad
  */
 public void updateColors(float[] colors, int i) {
   float[] baseColor = getColorForOrder(groupIdx, 6);
   System.arraycopy(baseColor, 0, colors, i, 3);
   System.arraycopy(baseColor, 0, colors, i + 3, 3);
   System.arraycopy(baseColor, 0, colors, i + 6, 3);
   System.arraycopy(baseColor, 0, colors, i + 9, 3);
 }
예제 #20
0
  /**
   * Remove <i>listener</i> from <i>bag</i> of listeners. The function does not modify <i>bag</i>
   * and return a new collection containing all listeners from <i>bag</i> except <i>listener</i>. If
   * <i>bag</i> does not contain <i>listener</i>, the function returns <i>bag</i>.
   *
   * <p>For usage example, see {@link #addListener(Object bag, Object listener)}.
   *
   * @param listener Listener to remove from <i>bag</i>
   * @param bag Current collection of listeners.
   * @return A new bag containing all listeners from <i>bag</i> except <i>listener</i>.
   * @see #addListener(Object bag, Object listener)
   * @see #getListener(Object bag, int index)
   */
  public static Object removeListener(Object bag, Object listener) {
    if (listener == null) throw new IllegalArgumentException();
    if (listener instanceof Object[]) throw new IllegalArgumentException();

    if (bag == listener) {
      bag = null;
    } else if (bag instanceof Object[]) {
      Object[] array = (Object[]) bag;
      int L = array.length;
      // bag has at least 2 elements if it is array
      if (L < 2) throw new IllegalArgumentException();
      if (L == 2) {
        if (array[1] == listener) {
          bag = array[0];
        } else if (array[0] == listener) {
          bag = array[1];
        }
      } else {
        int i = L;
        do {
          --i;
          if (array[i] == listener) {
            Object[] tmp = new Object[L - 1];
            System.arraycopy(array, 0, tmp, 0, i);
            System.arraycopy(array, i + 1, tmp, i, L - (i + 1));
            bag = tmp;
            break;
          }
        } while (i != 0);
      }
    }

    return bag;
  }
예제 #21
0
  /** Appends a value to the declaration. */
  public void append(Value v, int idx, boolean prio) {
    if (values.length == count) {
      Value[] newval = new Value[count * 2];
      int[] newidx = new int[count * 2];
      boolean[] newprio = new boolean[count * 2];

      System.arraycopy(values, 0, newval, 0, count);
      System.arraycopy(indexes, 0, newidx, 0, count);
      System.arraycopy(priorities, 0, newprio, 0, count);

      values = newval;
      indexes = newidx;
      priorities = newprio;
    }
    for (int i = 0; i < count; i++) {
      if (indexes[i] == idx) {
        // Replace existing property values,
        // unless they are important!
        if (prio || (priorities[i] == prio)) {
          values[i] = v;
          priorities[i] = prio;
        }
        return;
      }
    }
    values[count] = v;
    indexes[count] = idx;
    priorities[count] = prio;
    count++;
  }
예제 #22
0
 public static byte[] readStream(InputStream is, int initialBufferCapacity) throws IOException {
   if (initialBufferCapacity <= 0) {
     throw new IllegalArgumentException("Bad initialBufferCapacity: " + initialBufferCapacity);
   }
   byte[] buffer = new byte[initialBufferCapacity];
   int cursor = 0;
   for (; ; ) {
     int n = is.read(buffer, cursor, buffer.length - cursor);
     if (n < 0) {
       break;
     }
     cursor += n;
     if (cursor == buffer.length) {
       byte[] tmp = new byte[buffer.length * 2];
       System.arraycopy(buffer, 0, tmp, 0, cursor);
       buffer = tmp;
     }
   }
   if (cursor != buffer.length) {
     byte[] tmp = new byte[cursor];
     System.arraycopy(buffer, 0, tmp, 0, cursor);
     buffer = tmp;
   }
   return buffer;
 }
예제 #23
0
  public void writeSession(HttpServletRequest request, HttpServletResponse response)
      throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
          BadPaddingException, IllegalBlockSizeException {
    SparkHttpRequestWrapper sparkRequest = (SparkHttpRequestWrapper) request;
    if (!sparkRequest.sessionAccessed()) return;
    CookieSession session = (CookieSession) request.getSession();

    // serialize session
    byte[] sessionBytes = conf.asByteArray(session);

    // encrypt content
    final Cipher symmetricalCipher = Cipher.getInstance(symmetricEncryptionAlgorithm);
    symmetricalCipher.init(Cipher.ENCRYPT_MODE, this.symmetricEncryptionKey);
    byte[] encryptedBytes = symmetricalCipher.doFinal(sessionBytes);

    // sign content
    byte[] signature = sign(encryptedBytes);
    byte[] cookieContent = new byte[encryptedBytes.length + signature.length];

    System.arraycopy(encryptedBytes, 0, cookieContent, 0, encryptedBytes.length);
    System.arraycopy(
        signature, 0, cookieContent, cookieContent.length - signature.length, signature.length);

    String base64CookieContent = Base64.getEncoder().encodeToString(cookieContent);
    addCookie(base64CookieContent, response);
  }
예제 #24
0
  private MessageDigest setSHA1(AuthSecrets macParms) {
    try {
      mySHA1 = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
      Trace.comm.errorm(" Unable to build SHA", e);
      Trace.comm.notifyFatal();
    }
    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      Trace.comm.errorm("Unable to build MD5", e);
      Trace.comm.notifyFatal();
    }
    // Calculate the MAC key
    byte[] macKey = new byte[64];
    System.arraycopy(md5Hash(0x11, macParms.myDHSecret, md5), 0, macKey, 0, 16);
    System.arraycopy(md5Hash(0x22, macParms.myDHSecret, md5), 0, macKey, 16, 16);
    System.arraycopy(md5Hash(0x33, macParms.myDHSecret, md5), 0, macKey, 32, 16);
    System.arraycopy(md5Hash(0x44, macParms.myDHSecret, md5), 0, macKey, 48, 16);
    myMACKey = macParms.myMacKey = macKey;

    // Set up to do the MAC calculation
    myIsDoingMac = true;
    myMAC = new byte[20];
    return md5;
  }
 private GearmanPacket getPacketFromJob(GearmanJob job) {
   int destPos = 0;
   GearmanPacketMagic magic = GearmanPacketMagic.REQ;
   GearmanPacketType type = null;
   byte[] packetdata = null;
   byte[] fnname = ByteUtils.toAsciiBytes(job.getFunctionName());
   byte[] uid = job.getID();
   byte[] data = job.getData();
   if (job.getPriority().equals(GearmanJob.JobPriority.HIGH)) {
     type =
         job.isBackgroundJob()
             ? GearmanPacketType.SUBMIT_JOB_HIGH_BG
             : GearmanPacketType.SUBMIT_JOB_HIGH;
   }
   if (job.getPriority().equals(GearmanJob.JobPriority.LOW)) {
     type =
         job.isBackgroundJob()
             ? GearmanPacketType.SUBMIT_JOB_LOW_BG
             : GearmanPacketType.SUBMIT_JOB_LOW;
   }
   if (job.getPriority().equals(GearmanJob.JobPriority.NORMAL)) {
     type = job.isBackgroundJob() ? GearmanPacketType.SUBMIT_JOB_BG : GearmanPacketType.SUBMIT_JOB;
   }
   packetdata = new byte[fnname.length + uid.length + data.length + 2];
   System.arraycopy(fnname, 0, packetdata, destPos, fnname.length);
   destPos += fnname.length;
   packetdata[destPos++] = ByteUtils.NULL;
   System.arraycopy(uid, 0, packetdata, destPos, uid.length);
   destPos += uid.length;
   packetdata[destPos++] = ByteUtils.NULL;
   System.arraycopy(data, 0, packetdata, destPos, data.length);
   return new GearmanPacketImpl(magic, type, packetdata);
 }
  /**
   * Loads an input stream into an array of strings representing each line of the input stream
   *
   * @param input the input stream to load
   * @return the array of strings representing the inputStream
   */
  public static String[] loadStrings(InputStream input) {
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));

      String lines[] = new String[100];
      int lineCount = 0;
      String line = null;
      while ((line = reader.readLine()) != null) {
        if (lineCount == lines.length) {
          String temp[] = new String[lineCount << 1];
          System.arraycopy(lines, 0, temp, 0, lineCount);
          lines = temp;
        }
        lines[lineCount++] = line;
      }
      reader.close();

      if (lineCount == lines.length) {
        return lines;
      }

      // resize array to appropriate amount for these lines
      String output[] = new String[lineCount];
      System.arraycopy(lines, 0, output, 0, lineCount);
      return output;

    } catch (IOException e) {
      IStatus status =
          new Status(IStatus.WARNING, ArduinoConst.CORE_PLUGIN_ID, "Failed to read stream ", e);
      Common.log(status);
    }
    return null;
  }
예제 #27
0
  /**
   * Refills the input buffer.
   *
   * @return <code>false</code>, iff there was new input.
   * @exception java.io.IOException if any I/O-Error occurs
   */
  private boolean zzRefill() throws java.io.IOException {

    /* first: make room (if you can) */
    if (zzStartRead > 0) {
      System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead - zzStartRead);

      /* translate stored positions */
      zzEndRead -= zzStartRead;
      zzCurrentPos -= zzStartRead;
      zzMarkedPos -= zzStartRead;
      zzPushbackPos -= zzStartRead;
      zzStartRead = 0;
    }

    /* is the buffer big enough? */
    if (zzCurrentPos >= zzBuffer.length) {
      /* if not: blow it up */
      char newBuffer[] = new char[zzCurrentPos * 2];
      System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
      zzBuffer = newBuffer;
    }

    /* finally: fill the buffer with new input */
    int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length - zzEndRead);

    if (numRead < 0) {
      return true;
    } else {
      zzEndRead += numRead;
      return false;
    }
  }
예제 #28
0
  /**
   * Draws a rectangle using the given vertices. There must be 4 vertices, each made up of 5
   * elements in this order: x, y, color, u, v.
   */
  public void draw(Texture texture, float[] spriteVertices, int offset, int length) {
    if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw.");

    if (texture != lastTexture) {
      switchTexture(texture);
    }

    int remainingVertices = vertices.length - idx;
    if (remainingVertices == 0) {
      renderMesh();
      remainingVertices = vertices.length;
    }
    int vertexCount = Math.min(remainingVertices, length - offset);
    System.arraycopy(spriteVertices, offset, vertices, idx, vertexCount);
    offset += vertexCount;
    idx += vertexCount;

    while (offset < length) {
      renderMesh();
      vertexCount = Math.min(vertices.length, length - offset);
      System.arraycopy(spriteVertices, offset, vertices, 0, vertexCount);
      offset += vertexCount;
      idx += vertexCount;
    }
  }
예제 #29
0
  /** @return an array of buildlets that together build a CIMTool project */
  public Buildlet[] createBuildlets() {
    Buildlet[] defaultBuildlets =
        new Buildlet[] {
          new SchemaBuildlet(),
          new ProfileChecker(),
          new XSDBuildlet(),
          new TransformBuildlet(null, "xml"),
          new TransformBuildlet("html", "html"),
          new TextBuildlet("sql", "sql"),
          new TextBuildlet("jpa", "java"),
          new TextBuildlet("scala", "scala"),
          new SimpleOWLBuildlet("RDF/XML", "simple-flat-owl", false),
          new SimpleOWLBuildlet("RDF/XML-ABBREV", "simple-owl", false),
          new LegacyRDFSBuildlet("RDF/XML", "legacy-rdfs", false),
          new SimpleOWLBuildlet("RDF/XML", "simple-flat-owl-augmented", true),
          new SimpleOWLBuildlet("RDF/XML-ABBREV", "simple-owl-augmented", true),
          new LegacyRDFSBuildlet("RDF/XML", "legacy-rdfs-augmented", true),
          new CopyBuildlet("TURTLE", "ttl"),
          new ValidationBuildlet(),
          new SplitValidationBuildlet(),
          new IncrementalValidationBuildlet(),
        };

    ProfileBuildlet[] registered = ProfileBuildletRegistry.INSTANCE.getBuildlets();
    if (registered.length > 0) {
      Buildlet[] combined = new Buildlet[defaultBuildlets.length + registered.length];
      System.arraycopy(defaultBuildlets, 0, combined, 0, defaultBuildlets.length);
      System.arraycopy(registered, 0, combined, defaultBuildlets.length, registered.length);
      return combined;
    } else return defaultBuildlets;
  }
예제 #30
0
 private void sortTail() {
   // size > limit here
   T[] d = data;
   int l = limit, s = size;
   Comparator<? super T> cmp = comparator;
   Arrays.sort(d, l, s, cmp);
   if (cmp.compare(d[s - 1], d[0]) < 0) {
     // Common case: descending sequence
     // Assume size - limit <= limit here
     System.arraycopy(d, 0, d, s - l, 2 * l - s);
     System.arraycopy(d, l, d, 0, s - l);
   } else {
     // Merge presorted 0..limit-1 and limit..size-1
     @SuppressWarnings("unchecked")
     T[] buf = (T[]) new Object[l];
     int i = 0, j = l, k = 0;
     // d[l-1] is guaranteed to be the worst element, thus no need to
     // check it
     while (i < l - 1 && k < l && j < s) {
       if (cmp.compare(d[i], d[j]) <= 0) {
         buf[k++] = d[i++];
       } else {
         buf[k++] = d[j++];
       }
     }
     if (k < l) {
       System.arraycopy(d, i < l - 1 ? i : j, d, k, l - k);
     }
     System.arraycopy(buf, 0, d, 0, k);
   }
   size = l;
 }