Esempio n. 1
0
  private double interpolate_value(
      final UnstructuredVolumeObject volume, final int index0, final int index1)
      throws KVSException {
    Buffer buf = volume.values();
    float[] coords = volume.coords();

    final float value0 = this.substitute_plane_equation(new Vector3f(coords, 3 * index0));
    final float value1 = this.substitute_plane_equation(new Vector3f(coords, 3 * index1));
    final float ratio = kvs.core.util.Math.abs(value0 / (value1 - value0));

    if (buf instanceof ByteBuffer) {
      ByteBuffer values = (ByteBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof ShortBuffer) {
      ShortBuffer values = (ShortBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof IntBuffer) {
      IntBuffer values = (IntBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof LongBuffer) {
      LongBuffer values = (LongBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof FloatBuffer) {
      FloatBuffer values = (FloatBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof DoubleBuffer) {
      DoubleBuffer values = (DoubleBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof CharBuffer) {
      CharBuffer values = (CharBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else {
      throw new KVSException("Unsupported data type");
    }
  }
Esempio n. 2
0
 protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) {
   int mark = src.position();
   if (!doneBOM && src.hasRemaining()) {
     if (dst.remaining() < 4) return CoderResult.OVERFLOW;
     put(BOM_BIG, dst);
     doneBOM = true;
   }
   try {
     while (src.hasRemaining()) {
       char c = src.get();
       if (!Character.isSurrogate(c)) {
         if (dst.remaining() < 4) return CoderResult.OVERFLOW;
         mark++;
         put(c, dst);
       } else if (Character.isHighSurrogate(c)) {
         if (!src.hasRemaining()) return CoderResult.UNDERFLOW;
         char low = src.get();
         if (Character.isLowSurrogate(low)) {
           if (dst.remaining() < 4) return CoderResult.OVERFLOW;
           mark += 2;
           put(Character.toCodePoint(c, low), dst);
         } else {
           return CoderResult.malformedForLength(1);
         }
       } else {
         // assert Character.isLowSurrogate(c);
         return CoderResult.malformedForLength(1);
       }
     }
     return CoderResult.UNDERFLOW;
   } finally {
     src.position(mark);
   }
 }
Esempio n. 3
0
 private static Type getType(CharBuffer desc) {
   switch (desc.get()) {
     case 'Z':
       return I8;
     case 'B':
       return I8;
     case 'S':
       return I16;
     case 'C':
       return I16;
     case 'I':
       return I32;
     case 'J':
       return I64;
     case 'F':
       return FLOAT;
     case 'D':
       return DOUBLE;
     case 'V':
       return VOID;
     case 'L':
       while (desc.get() != ';') ;
       return OBJECT_PTR;
     case '[':
       getType(desc);
       return OBJECT_PTR;
   }
   throw new IllegalArgumentException();
 }
Esempio n. 4
0
 private static List<String> getParameterDescriptors(CharBuffer cb) {
   List<String> result = new ArrayList<String>();
   cb.get(); // Skip the initial '('
   while (cb.hasRemaining() && cb.get(cb.position()) != ')') {
     StringBuilder sb = new StringBuilder();
     nextDescriptor(cb, sb);
     result.add(sb.toString());
   }
   return result;
 }
  public void byte2char(byte[] src, int index_src, char[] dst, int index_dst, int len) {

    if (len > (BUFFER_SIZE / 2)) {
      CharBuffer buffer = ByteBuffer.wrap(src, index_src, len * 2).order(order).asCharBuffer();
      buffer.get(dst, index_dst, len);
    } else {
      byteBuffer.clear();
      byteBuffer.put(src, index_src, len * 2);

      charBuffer.position(0).limit(len);
      charBuffer.get(dst, index_dst, len);
    }
  }
Esempio n. 6
0
 private static void nextDescriptor(CharBuffer cb, StringBuilder sb) {
   char c = cb.get();
   sb.append(c);
   if (c == 'L') {
     do {
       c = cb.get();
       sb.append(c);
     } while (c != ';');
   } else if (c == '[') {
     nextDescriptor(cb, sb);
   } else {
     // Must be a primitive
   }
 }
Esempio n. 7
0
  /**
   * Write a string to the network. The length header of the string is written automatically and its
   * encoded to the correct CharSet automatically.
   *
   * @param value the string that shall be send to the server
   */
  @Override
  public void writeString(@Nonnull String value) throws CharacterCodingException {
    int startIndex = buffer.position();
    buffer.putShort((short) 0);

    encodingBuffer.clear();
    encodingBuffer.put(value, 0, Math.min(encodingBuffer.capacity(), value.length()));
    encodingBuffer.flip();

    do {
      CoderResult encodingResult = encoder.encode(encodingBuffer, buffer, true);
      if (!encodingResult.isError()) {
        break;
      }
      if (encodingResult.isUnmappable()) {
        log.warn(
            "Found a character that failed to encode for the transfer to the server: {} - SKIP",
            encodingBuffer.get());
      } else {
        encodingResult.throwException();
      }
    } while (encodingBuffer.hasRemaining());

    int lastIndex = buffer.position();
    buffer.position(startIndex);
    writeUShort(lastIndex - startIndex - 2);
    buffer.position(lastIndex);
  }
 /**
  * Receive as many items as possible from the given byte buffer to this buffer.
  *
  * <p>The <TT>receiveItems()</TT> method must not block the calling thread; if it does, all
  * message I/O in MP will be blocked.
  *
  * @param i Index of first item to receive, in the range 0 .. <TT>length</TT>-1.
  * @param num Maximum number of items to receive.
  * @param buffer Byte buffer.
  * @return Number of items received.
  */
 protected int receiveItems(int i, int num, ByteBuffer buffer) {
   CharBuffer charbuffer = buffer.asCharBuffer();
   int n = 0;
   int r = i / myColCount;
   int row = r + myLowerRow;
   int c = i % myColCount;
   int col = c + myLowerCol;
   int ncols = Math.min(myColCount - c, charbuffer.remaining());
   while (r < myRowCount && ncols > 0) {
     char[] myMatrix_row = myMatrix[row];
     while (c < ncols) {
       myMatrix_row[col] = myOp.op(myMatrix_row[col], charbuffer.get());
       ++c;
       ++col;
     }
     n += ncols;
     ++r;
     ++row;
     c = 0;
     col = myLowerCol;
     ncols = Math.min(myColCount, charbuffer.remaining());
   }
   buffer.position(buffer.position() + 2 * n);
   return n;
 }
Esempio n. 9
0
  protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) {
    int mark = src.position();

    if (needsMark) {
      if (dst.remaining() < 2) return CoderResult.OVERFLOW;
      put(BYTE_ORDER_MARK, dst);
      needsMark = false;
    }

    try {
      while (src.hasRemaining()) {
        char c = src.get();
        if (!Surrogate.is(c)) {
          if (dst.remaining() < 2) return CoderResult.OVERFLOW;
          mark++;
          put(c, dst);
          continue;
        }
        int d = sgp.parse(c, src);
        if (d < 0) return sgp.error();
        if (dst.remaining() < 4) return CoderResult.OVERFLOW;
        mark += 2;
        put(Surrogate.high(d), dst);
        put(Surrogate.low(d), dst);
      }
      return CoderResult.UNDERFLOW;
    } finally {
      src.position(mark);
    }
  }
Esempio n. 10
0
    private CoderResult encodeBufferLoop(CharBuffer src, ByteBuffer dst) {
      int mark = src.position();
      try {
        while (src.hasRemaining()) {
          char c = src.get();

          // AQUI HACE EL CAMBIO DE ALGUNOS CARACTERES
          if (c >= 0x0FF) {
            Character ch = s_codesTable.get((int) c);
            if (ch == null) {
              System.err.println(
                  "Character without encoding in 'MyCharSet.properties' (" + (int) c + "): " + c);
            } else {
              c = ch;
            }
          }

          if (c < 0x0FF) {
            if (!dst.hasRemaining()) return CoderResult.OVERFLOW;
            dst.put((byte) c);
            mark++;
            continue;
          }

          if (sgp.parse(c, src) < 0) return sgp.error();
          return sgp.unmappableResult();
        }
        return CoderResult.UNDERFLOW;
      } finally {
        src.position(mark);
      }
    }
Esempio n. 11
0
 public static void main(String[] arguments) {
   try {
     // read byte data into a byte buffer
     String data = "friends.dat";
     FileInputStream inData = new FileInputStream(data);
     FileChannel inChannel = inData.getChannel();
     long inSize = inChannel.size();
     ByteBuffer source = ByteBuffer.allocate((int) inSize);
     inChannel.read(source, 0);
     source.position(0);
     System.out.println("Original byte data:");
     for (int i = 0; source.remaining() > 0; i++) {
       System.out.print(source.get() + " ");
     }
     // convert byte data into character data
     source.position(0);
     Charset ascii = Charset.forName("US-ASCII");
     CharsetDecoder toAscii = ascii.newDecoder();
     CharBuffer destination = toAscii.decode(source);
     destination.position(0);
     System.out.println("\n\nNew character data:");
     for (int i = 0; destination.remaining() > 0; i++) {
       System.out.print(destination.get());
     }
     System.out.println();
   } catch (FileNotFoundException fne) {
     System.out.println(fne.getMessage());
   } catch (IOException ioe) {
     System.out.println(ioe.getMessage());
   }
 }
Esempio n. 12
0
 public static void main(String[] args) {
   ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 'a'});
   bb.rewind();
   printnb("Byte Buffer ");
   while (bb.hasRemaining()) printnb(bb.position() + " -> " + bb.get() + ", ");
   print();
   CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer();
   printnb("Char Buffer ");
   while (cb.hasRemaining()) printnb(cb.position() + " -> " + cb.get() + ", ");
   print();
   FloatBuffer fb = ((ByteBuffer) bb.rewind()).asFloatBuffer();
   printnb("Float Buffer ");
   while (fb.hasRemaining()) printnb(fb.position() + " -> " + fb.get() + ", ");
   print();
   IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer();
   printnb("Int Buffer ");
   while (ib.hasRemaining()) printnb(ib.position() + " -> " + ib.get() + ", ");
   print();
   LongBuffer lb = ((ByteBuffer) bb.rewind()).asLongBuffer();
   printnb("Long Buffer ");
   while (lb.hasRemaining()) printnb(lb.position() + " -> " + lb.get() + ", ");
   print();
   ShortBuffer sb = ((ByteBuffer) bb.rewind()).asShortBuffer();
   printnb("Short Buffer ");
   while (sb.hasRemaining()) printnb(sb.position() + " -> " + sb.get() + ", ");
   print();
   DoubleBuffer db = ((ByteBuffer) bb.rewind()).asDoubleBuffer();
   printnb("Double Buffer ");
   while (db.hasRemaining()) printnb(db.position() + " -> " + db.get() + ", ");
 }
Esempio n. 13
0
 private byte[] encodeImpl(CharBuffer in) {
   Charset cs = charset();
   if (!(cs instanceof IOSCharset)) {
     throw new UnsupportedCharsetException(cs.name());
   }
   char[] chars;
   int i;
   if (inBuffer != null) {
     i = inBuffer.length;
     chars = new char[i + in.remaining()];
     System.arraycopy(inBuffer, 0, chars, 0, inBuffer.length);
     inBuffer = null;
   } else {
     if (((IOSCharset) cs).nsEncoding() == /* NSUnicodeStringEncoding */ 10L) {
       // Prepend required BOM for Java's big-endian encoding default.
       chars = new char[in.remaining() + 1];
       chars[0] = (char) 0xFEFF;
       i = 1;
     } else {
       i = 0;
       chars = new char[in.remaining()];
     }
   }
   in.get(chars, i, chars.length - i);
   byte[] bytes = encode(chars, ((IOSCharset) cs).nsEncoding());
   if (bytes.length == 0) {
     inBuffer = chars;
   } else {
     inBuffer = null;
   }
   return bytes;
 }
Esempio n. 14
0
 /**
  * Sets the contents of this string to the contents of the given <tt>CharBuffer</tt>. The
  * characters between the buffer's current position (inclusive) and the buffer's limit (exclusive)
  * will be stored in this string.
  *
  * @param buffer The character buffer to read the characters from.
  */
 public void setValue(CharBuffer buffer) {
   checkNotNull(buffer);
   final int len = buffer.length();
   ensureSize(len);
   buffer.get(this.value, 0, len);
   this.len = len;
   this.hashCode = 0;
 }
Esempio n. 15
0
 public static void setDelimiter(String delimiter) {
   List<String> l = new ArrayList<String>();
   CharBuffer buf = CharBuffer.wrap(delimiter);
   while (buf.hasRemaining()) {
     l.add(String.valueOf(buf.get()));
   }
   delimiters = l.toArray(new String[l.size()]);
 }
Esempio n. 16
0
 /** @param s */
 @Override
 public void print(PrintStream s) {
   // s.write(buffer.array());
   buffer.rewind();
   for (int x = 0; x < size; x++) {
     s.write(buffer.get());
   }
 }
Esempio n. 17
0
 private static FunctionType getFunctionType(String methodDesc, boolean ztatic, boolean nativ) {
   List<Type> paramTypes = new ArrayList<Type>();
   paramTypes.add(ENV_PTR);
   if (!ztatic) {
     paramTypes.add(OBJECT_PTR);
   } else if (nativ) {
     paramTypes.add(OBJECT_PTR);
   }
   CharBuffer buffer = CharBuffer.wrap(methodDesc);
   buffer.get(); // Skip initial (
   while (buffer.get(buffer.position()) != ')') {
     paramTypes.add(getType(buffer));
   }
   buffer.get(); // Skip ending )
   Type returnType = getType(buffer);
   return new FunctionType(returnType, paramTypes.toArray(new Type[paramTypes.size()]));
 }
Esempio n. 18
0
  public void mergeNormals() {
    FloatBuffer normalAccumulationBuffer = FloatBuffer.allocate(mVertices.capacity());
    for (int i = 0; i < mIndices.capacity(); i++) {
      int indice = mIndices.get(i);
      int offset_indice = indice * D3DMesh.nbFloatPerVertex;

      for (int j = 0; j < mIndices.capacity(); j++) {
        char indice2 = mIndices.get(j);
        int offset_indice2 = indice2 * D3DMesh.nbFloatPerVertex;
        float x = mVertices.get(indice * D3DMesh.nbFloatPerVertex);
        float y = mVertices.get(indice * D3DMesh.nbFloatPerVertex + 1);
        float z = mVertices.get(indice * D3DMesh.nbFloatPerVertex + 2);

        float x2 = mVertices.get(indice2 * D3DMesh.nbFloatPerVertex);
        float y2 = mVertices.get(indice2 * D3DMesh.nbFloatPerVertex + 1);
        float z2 = mVertices.get(indice2 * D3DMesh.nbFloatPerVertex + 2);

        if ((x == x2) && (y == y2) && (z == z2)) {

          normalAccumulationBuffer.put(
              offset_indice2 + 3,
              normalAccumulationBuffer.get(offset_indice2 + 3) + mVertices.get(offset_indice + 3));
          normalAccumulationBuffer.put(
              offset_indice2 + 4,
              normalAccumulationBuffer.get(offset_indice2 + 4) + mVertices.get(offset_indice + 4));
          normalAccumulationBuffer.put(
              offset_indice2 + 5,
              normalAccumulationBuffer.get(offset_indice2 + 5) + mVertices.get(offset_indice + 5));
        }
      }
    }

    D3DVector normal = new D3DVector();
    for (int i = 0; i < mIndices.capacity(); i++) {
      int indice = mIndices.get(i);
      int offset_indice = indice * D3DMesh.nbFloatPerVertex;
      normal.set(0, normalAccumulationBuffer.get(offset_indice + 3));
      normal.set(1, normalAccumulationBuffer.get(offset_indice + 4));
      normal.set(2, normalAccumulationBuffer.get(offset_indice + 5));
      normal.normalize();
      mVertices.put(offset_indice + 3, normal.get(0));
      mVertices.put(offset_indice + 4, normal.get(1));
      mVertices.put(offset_indice + 5, normal.get(2));
    }
  }
 public T get(CharBuffer buffer, int offset) {
   char ch = buffer.get(offset);
   try {
     return list.get(ch);
   } catch (IndexOutOfBoundsException e) {
     throw new IllegalStateException(
         "Object id " + (int) ch + " is not valid, must be less than " + list.size(), e);
   }
 }
Esempio n. 20
0
  private double interpolate_value(
      final StructuredVolumeObject volume, final Vector3f vertex0, final Vector3f vertex1)
      throws KVSException {
    Buffer buf = volume.values();

    final int line_size = volume.nnodesPerLine();
    final int slice_size = volume.nnodesPerSlice();

    final float value0 = this.substitute_plane_equation(vertex0);
    final float value1 = this.substitute_plane_equation(vertex1);
    final float ratio = kvs.core.util.Math.abs(value0 / (value1 - value0));

    final int index0 =
        (int) (vertex0.getX() + vertex0.getY() * line_size + vertex0.getZ() * slice_size);
    final int index1 =
        (int) (vertex1.getX() + vertex1.getY() * line_size + vertex1.getZ() * slice_size);

    if (buf instanceof ByteBuffer) {
      ByteBuffer values = (ByteBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof ShortBuffer) {
      ShortBuffer values = (ShortBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof IntBuffer) {
      IntBuffer values = (IntBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof LongBuffer) {
      LongBuffer values = (LongBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof FloatBuffer) {
      FloatBuffer values = (FloatBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof DoubleBuffer) {
      DoubleBuffer values = (DoubleBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else if (buf instanceof CharBuffer) {
      CharBuffer values = (CharBuffer) buf;
      return (values.get(index0) + ratio * (values.get(index1) - values.get(index0)));
    } else {
      throw new KVSException("Unsupported data type");
    }
  }
Esempio n. 21
0
 static {
   Charset charset = Charset.forName("ASCII");
   byte[] bytes = new byte[256];
   for (int i = 0; i <= 255; i++) {
     asc[i] = '.';
     bytes[i] = (byte) (0xff & i);
   }
   CharBuffer buffer = charset.decode(ByteBuffer.wrap(bytes));
   for (int i = 0x20; i <= 0x7E; i++) {
     asc[i] = buffer.get(i);
   }
 }
Esempio n. 22
0
 private int getNextCharacter() throws IOException {
   CharBuffer buf = readerBuffer;
   if (buf.remaining() == 0) {
     buf.clear();
     int read = reader.read(buf);
     buf.flip();
     assert read != 0;
     if (read < 0) {
       return EOF;
     }
   }
   return buf.get();
 }
Esempio n. 23
0
 private boolean trimWhitespaces() {
   boolean trim = false;
   for (int i = lineBuffer.position(), n = lineBuffer.limit(); i < n; i++) {
     char c = lineBuffer.get(i);
     if (Character.isWhitespace(c)) {
       trim = true;
       lineBuffer.position(i + 1);
     } else {
       break;
     }
   }
   for (int i = lineBuffer.limit() - 1, n = lineBuffer.position(); i >= n; i--) {
     char c = lineBuffer.get(i);
     if (Character.isWhitespace(c)) {
       trim = true;
       lineBuffer.limit(i);
     } else {
       break;
     }
   }
   return trim;
 }
Esempio n. 24
0
 /** {@inheritDoc} */
 @Override
 public void decode(final CharBuffer input, final ByteBuffer output) {
   // Ignore leading 0x characters if present
   if (input.get(0) == '0' && input.get(1) == 'x') {
     input.position(input.position() + 2);
   }
   byte hi = 0;
   byte lo;
   char current;
   while (input.hasRemaining()) {
     current = input.get();
     if (current == ':' || Character.isWhitespace(current)) {
       continue;
     }
     if ((count++ & 0x01) == 0) {
       hi = lookup(current);
     } else {
       lo = lookup(current);
       output.put((byte) ((hi << 4) | lo));
     }
   }
 }
Esempio n. 25
0
  public int mergeVertexIndices() {
    int countmerge = 0;
    for (int i = 0; i < mIndices.capacity(); i++) {
      int indice = mIndices.get(i);
      for (int j = 0; j < i; j++) {
        char indice2 = mIndices.get(j);

        float x = mVertices.get(indice * D3DMesh.nbFloatPerVertex);
        float y = mVertices.get(indice * D3DMesh.nbFloatPerVertex + 1);
        float z = mVertices.get(indice * D3DMesh.nbFloatPerVertex + 2);

        float x2 = mVertices.get(indice2 * D3DMesh.nbFloatPerVertex);
        float y2 = mVertices.get(indice2 * D3DMesh.nbFloatPerVertex + 1);
        float z2 = mVertices.get(indice2 * D3DMesh.nbFloatPerVertex + 2);

        if ((x == x2) && (y == y2) && (z == z2)) {
          mIndices.put(i, indice2);
          countmerge++;
        }
      }
    }
    return countmerge;
  }
Esempio n. 26
0
 /*     */ protected CoderResult encodeLoop(
     CharBuffer paramCharBuffer, ByteBuffer paramByteBuffer) {
   /* 146 */ int i = paramCharBuffer.position();
   /* 147 */ if ((!this.doneBOM) && (paramCharBuffer.hasRemaining())) {
     /* 148 */ if (paramByteBuffer.remaining() < 4) /* 149 */ return CoderResult.OVERFLOW;
     /* 150 */ put(65279, paramByteBuffer);
     /* 151 */ this.doneBOM = true;
     /*     */ }
   /*     */ try {
     /* 154 */ while (paramCharBuffer.hasRemaining()) {
       /* 155 */ char c1 = paramCharBuffer.get();
       /*     */ CoderResult localCoderResult2;
       /* 156 */ if (!Character.isSurrogate(c1)) {
         /* 157 */ if (paramByteBuffer.remaining() < 4) /* 158 */ return CoderResult.OVERFLOW;
         /* 159 */ i++;
         /* 160 */ put(c1, paramByteBuffer);
         /* 161 */ } else if (Character.isHighSurrogate(c1)) {
         /* 162 */ if (!paramCharBuffer.hasRemaining()) /* 163 */ return CoderResult.UNDERFLOW;
         /* 164 */ char c2 = paramCharBuffer.get();
         /*     */ CoderResult localCoderResult4;
         /* 165 */ if (Character.isLowSurrogate(c2)) {
           /* 166 */ if (paramByteBuffer.remaining() < 4) /* 167 */ return CoderResult.OVERFLOW;
           /* 168 */ i += 2;
           /* 169 */ put(Character.toCodePoint(c1, c2), paramByteBuffer);
           /*     */ } else {
           /* 171 */ return CoderResult.malformedForLength(1);
           /*     */ }
         /*     */ }
       /*     */ else {
         /* 175 */ return CoderResult.malformedForLength(1);
         /*     */ }
       /*     */ }
     /* 178 */ return CoderResult.UNDERFLOW;
     /*     */ } finally {
     /* 180 */ paramCharBuffer.position(i);
     /*     */ }
   /*     */ }
Esempio n. 27
0
 @Override
 public void add() {
   boolean done = false;
   int pos = size - 1;
   while (pos >= 0 && !done) {
     char c = buffer.get(pos);
     if (c == '9') {
       buffer.put(pos, '0');
       pos--;
     } else {
       c++;
       buffer.put(pos, c);
       done = true;
     }
   }
 }
Esempio n. 28
0
  private int readInRequest(
      QueueSession session, HttpServletRequest request, HttpServletResponse response) {
    try {

      BufferedReader reader = request.getReader();
      if (!reader.ready()) return 0;
      StringAppender sb = new StringAppender(request.getContentLength());
      CharBuffer buffer = CharBuffer.allocate(10);
      int read;
      while ((read = reader.read(buffer)) > 0) {
        buffer.rewind();
        for (; read > 0; read--) {
          sb.append(buffer.get());
        }
        buffer.rewind();
      }

      Message msg =
          createCommandMessage(
              sessionProvider.getSession(
                  request.getSession(), request.getHeader(ClientMessageBus.REMOTE_QUEUE_ID_HEADER)),
              request,
              sb.toString());
      if (msg != null) {
        try {
          service.store(msg);
        } catch (Exception e) {
          if (!e.getMessage().contains("expired")) {
            writeExceptionToOutputStream(response, e);
            return 0;
          }
        }

        return 1;
      } else {
        return 0;
      }
    } catch (IOException e) {
      MessageQueue queue = service.getBus().getQueue(session);
      if (queue != null) {
        queue.stopQueue();
      }
      e.printStackTrace();
      return -1;
    }
  }
Esempio n. 29
0
  /**
   * Gets a Reader for a text flavor, decoded, if necessary, for the expected charset (encoding).
   * The supported representation classes are <code>java.io.Reader</code>, <code>java.lang.String
   * </code>, <code>java.nio.CharBuffer</code>, <code>[C</code>, <code>java.io.InputStream</code>,
   * <code>java.nio.ByteBuffer</code>, and <code>[B</code>.
   *
   * <p>Because text flavors which do not support the charset parameter are encoded in a
   * non-standard format, this method should not be called for such flavors. However, in order to
   * maintain backward-compatibility, if this method is called for such a flavor, this method will
   * treat the flavor as though it supports the charset parameter and attempt to decode it
   * accordingly. See <code>selectBestTextFlavor</code> for a list of text flavors which do not
   * support the charset parameter.
   *
   * @param transferable the <code>Transferable</code> whose data will be requested in this flavor
   * @return a <code>Reader</code> to read the <code>Transferable</code>'s data
   * @exception IllegalArgumentException if the representation class is not one of the seven listed
   *     above
   * @exception IllegalArgumentException if the <code>Transferable</code> has <code>null</code> data
   * @exception NullPointerException if the <code>Transferable</code> is <code>null</code>
   * @exception UnsupportedEncodingException if this flavor's representation is <code>
   *     java.io.InputStream</code>, <code>java.nio.ByteBuffer</code>, or <code>[B</code> and this
   *     flavor's encoding is not supported by this implementation of the Java platform
   * @exception UnsupportedFlavorException if the <code>Transferable</code> does not support this
   *     flavor
   * @exception IOException if the data cannot be read because of an I/O error
   * @see #selectBestTextFlavor
   * @since 1.3
   */
  public Reader getReaderForText(Transferable transferable)
      throws UnsupportedFlavorException, IOException {
    Object transferObject = transferable.getTransferData(this);
    if (transferObject == null) {
      throw new IllegalArgumentException("getTransferData() returned null");
    }

    if (transferObject instanceof Reader) {
      return (Reader) transferObject;
    } else if (transferObject instanceof String) {
      return new StringReader((String) transferObject);
    } else if (transferObject instanceof CharBuffer) {
      CharBuffer buffer = (CharBuffer) transferObject;
      int size = buffer.remaining();
      char[] chars = new char[size];
      buffer.get(chars, 0, size);
      return new CharArrayReader(chars);
    } else if (transferObject instanceof char[]) {
      return new CharArrayReader((char[]) transferObject);
    }

    InputStream stream = null;

    if (transferObject instanceof InputStream) {
      stream = (InputStream) transferObject;
    } else if (transferObject instanceof ByteBuffer) {
      ByteBuffer buffer = (ByteBuffer) transferObject;
      int size = buffer.remaining();
      byte[] bytes = new byte[size];
      buffer.get(bytes, 0, size);
      stream = new ByteArrayInputStream(bytes);
    } else if (transferObject instanceof byte[]) {
      stream = new ByteArrayInputStream((byte[]) transferObject);
    }

    if (stream == null) {
      throw new IllegalArgumentException(
          "transfer data is not Reader, String, CharBuffer, char array, InputStream, ByteBuffer, or byte array");
    }

    String encoding = getParameter("charset");
    return (encoding == null)
        ? new InputStreamReader(stream)
        : new InputStreamReader(stream, encoding);
  }
Esempio n. 30
0
  /**
   * Converts camelcase and underscores to a string with spaces with some intelligence.
   *
   * @param column
   * @return
   */
  public static String camelCaseToSentence(String in) {
    CharBuffer buffer = CharBuffer.allocate(in.length() + 100);

    boolean last = false; // was last a capital?
    boolean lastu = false; // was last a capital?

    char ch;
    char next = in.charAt(0);

    for (int i = 1; i < in.length(); ++i) {

      ch = next;
      next = in.charAt(i);

      if ((Character.isUpperCase(ch) && last == false)
          || (Character.isUpperCase(ch)
              && last == true
              && Character.isUpperCase(next) == false
              && next != '_')) {

        buffer.append(" ");
      }

      if (ch == '_') {
        buffer.append(" ");
      } else if (lastu) {
        buffer.append(Character.toUpperCase(ch));
      } else {
        buffer.append(ch);
      }

      last = Character.isUpperCase(ch) ? true : false;
      lastu = ch == '_' ? true : false;
    }

    buffer.append(next);

    buffer.put(0, Character.toUpperCase(buffer.get(0)));
    buffer.flip();

    return buffer.toString();
  }