Ejemplo n.º 1
0
  @Override
  public TransformationResult getMoreData(byte opCode, boolean fin, int rsv, ByteBuffer dest)
      throws IOException {
    // Control frames are never compressed and may appear in the middle of
    // a WebSocket method. Pass them straight through.
    if (Util.isControl(opCode)) {
      return next.getMoreData(opCode, fin, rsv, dest);
    }

    if (!Util.isContinuation(opCode)) {
      // First frame in new message
      skipDecompression = (rsv & RSV_BITMASK) == 0;
    }

    // Pass uncompressed frames straight through.
    if (skipDecompression) {
      return next.getMoreData(opCode, fin, rsv, dest);
    }

    int written;
    boolean usedEomBytes = false;

    while (dest.remaining() > 0) {
      // Space available in destination. Try and fill it.
      try {
        written =
            inflater.inflate(dest.array(), dest.arrayOffset() + dest.position(), dest.remaining());
      } catch (DataFormatException e) {
        throw new IOException(sm.getString("perMessageDeflate.deflateFailed"), e);
      }
      dest.position(dest.position() + written);

      if (inflater.needsInput() && !usedEomBytes) {
        if (dest.hasRemaining()) {
          readBuffer.clear();
          TransformationResult nextResult =
              next.getMoreData(opCode, fin, (rsv ^ RSV_BITMASK), readBuffer);
          inflater.setInput(readBuffer.array(), readBuffer.arrayOffset(), readBuffer.position());
          if (TransformationResult.UNDERFLOW.equals(nextResult)) {
            return nextResult;
          } else if (TransformationResult.END_OF_FRAME.equals(nextResult)
              && readBuffer.position() == 0) {
            if (fin) {
              inflater.setInput(EOM_BYTES);
              usedEomBytes = true;
            } else {
              return TransformationResult.END_OF_FRAME;
            }
          }
        }
      } else if (written == 0) {
        if (fin && (isServer && !clientContextTakeover || !isServer && !serverContextTakeover)) {
          inflater.reset();
        }
        return TransformationResult.END_OF_FRAME;
      }
    }

    return TransformationResult.OVERFLOW;
  }
Ejemplo n.º 2
0
 private String transformationStr(Transformation trf) {
   NumberFormat fmt = FloatFormat.getInstance();
   Matrix matrix = trf.matrix();
   Vector vector = trf.vector();
   return "matrix <"
       + fmt.format(matrix.get(Transformation.X, Transformation.X))
       + ","
       + fmt.format(matrix.get(Transformation.Z, Transformation.X))
       + ","
       + fmt.format(matrix.get(Transformation.Y, Transformation.X))
       + ","
       + fmt.format(matrix.get(Transformation.X, Transformation.Z))
       + ","
       + fmt.format(matrix.get(Transformation.Z, Transformation.Z))
       + ","
       + fmt.format(matrix.get(Transformation.Y, Transformation.Z))
       + ","
       + fmt.format(matrix.get(Transformation.X, Transformation.Y))
       + ","
       + fmt.format(matrix.get(Transformation.Z, Transformation.Y))
       + ","
       + fmt.format(matrix.get(Transformation.Y, Transformation.Y))
       + ","
       + fmt.format(vector.getX())
       + ","
       + fmt.format(vector.getZ())
       + ","
       + fmt.format(vector.getY())
       + ">";
 }
Ejemplo n.º 3
0
  private void draw_music_manuscript(Canvas c, Transformation t) {
    float lineSpacingMm = 2.5f;
    float staveHeight = 4 * lineSpacingMm;
    float staffTopMarginMm = 25.0f;
    float staffBottomMarginMm = 15.0f;
    float staffSideMarginMm = 15.0f;
    int staveCount;
    if (aspectRatio.isPortrait()) staveCount = 12;
    else staveCount = 8;
    float staffTotal = staffTopMarginMm + staffBottomMarginMm + staveCount * staveHeight;
    float staffSpacing = staveHeight + (heightMm - staffTotal) / (staveCount - 1);

    float x0, x1, y;

    int shade = 0xaa;
    float threshold = 1500;
    if (t.scale < threshold) shade += (int) ((threshold - t.scale) / threshold * (0xff - shade));
    paint.setARGB(0xff, shade, shade, shade);

    paint.setStrokeWidth(0);

    x0 = t.applyX(staffSideMarginMm / heightMm);
    x1 = t.applyX((widthMm - staffSideMarginMm) / heightMm);

    for (int i = 0; i < staveCount; i++) {
      for (int j = 0; j < 5; j++) {
        y = t.applyY((staffTopMarginMm + i * staffSpacing + j * lineSpacingMm) / heightMm);
        c.drawLine(x0, y, x1, y, paint);
      }
    }
  }
  public static void assertNoIterations(Transformations<Transformation> transformations) {

    for (Transformation transformation : transformations) {

      fail(
          "an empty "
              + Transformations.class.getSimpleName()
              + " should not iterate. Transformation: "
              + transformation.getName());
    }
  }
Ejemplo n.º 5
0
  private boolean processDataBinary() throws IOException {
    // Copy the available data to the buffer
    TransformationResult tr = transformation.getMoreData(opCode, fin, rsv, messageBufferBinary);
    while (!TransformationResult.END_OF_FRAME.equals(tr)) {
      // Frame not complete - what did we run out of?
      if (TransformationResult.UNDERFLOW.equals(tr)) {
        // Ran out of input data - get some more
        return false;
      }

      // Ran out of message buffer - flush it
      if (!usePartial()) {
        CloseReason cr =
            new CloseReason(
                CloseCodes.TOO_BIG,
                sm.getString(
                    "wsFrame.bufferTooSmall",
                    Integer.valueOf(messageBufferBinary.capacity()),
                    Long.valueOf(payloadLength)));
        throw new WsIOException(cr);
      }
      messageBufferBinary.flip();
      ByteBuffer copy = ByteBuffer.allocate(messageBufferBinary.limit());
      copy.put(messageBufferBinary);
      copy.flip();
      sendMessageBinary(copy, false);
      messageBufferBinary.clear();
      // Read more data
      tr = transformation.getMoreData(opCode, fin, rsv, messageBufferBinary);
    }

    // Frame is fully received
    // Send the message if either:
    // - partial messages are supported
    // - the message is complete
    if (usePartial() || !continuationExpected) {
      messageBufferBinary.flip();
      ByteBuffer copy = ByteBuffer.allocate(messageBufferBinary.limit());
      copy.put(messageBufferBinary);
      copy.flip();
      sendMessageBinary(copy, !continuationExpected);
      messageBufferBinary.clear();
    }

    if (continuationExpected) {
      // More data for this message expected, start a new frame
      newFrame();
    } else {
      // Message is complete, start a new message
      newMessage();
    }

    return true;
  }
Ejemplo n.º 6
0
  void applyOrTransformation(final GroupElement parent) throws InvalidPatternException {
    final Transformation transformation = this.orTransformations.get(parent.getType());

    if (transformation == null) {
      throw new RuntimeException(
          "applyOrTransformation could not find transformation for parent '"
              + parent.getType()
              + "' and child 'OR'");
    }
    transformation.transform(parent);
  }
  public static Map<String, Transformation> mockTransformationMap(Collection<String> names) {

    final Map<String, Transformation> transformationMap =
        new HashMap<String, Transformation>(names.size());

    for (Transformation transformation : mockTransformationList(names)) {

      transformationMap.put(transformation.getName(), transformation);
    }

    return transformationMap;
  }
Ejemplo n.º 8
0
  protected void translate(iTranslatable aTranslatable) {
    GVector theVector;
    if (myRotationCenter != null) {
      theVector = new GVector(myRotationCenter.getCamCenterPoint());
    } else {
      theVector = new GVector(aTranslatable.getCamCenterPoint());
    }

    Transformation theTransform = new Transformation();
    theTransform.addTransformation(MatrixOperations.buildTranslationMatrix(theVector.inv()));
    theTransform.addTransformation(MatrixOperations.buildRotationMatrix(myRotation));
    theTransform.addTransformation(MatrixOperations.buildTranslationMatrix(theVector));
    aTranslatable.translate(theTransform);
  }
  public static List<Transformation> mockTransformationList(Collection<String> names) {

    final List<Transformation> transformations = new ArrayList<Transformation>(names.size());

    Transformation transformation;
    for (String name : names) {

      transformation = mock(Transformation.class);
      when(transformation.getName()).thenReturn(name);

      transformations.add(transformation);
    }

    return transformations;
  }
Ejemplo n.º 10
0
 @Override
 public void setNext(Transformation t) {
   if (next == null) {
     this.next = t;
   } else {
     next.setNext(t);
   }
 }
Ejemplo n.º 11
0
  static Bitmap applyCustomTransformations(List<Transformation> transformations, Bitmap result) {
    for (int i = 0, count = transformations.size(); i < count; i++) {
      Transformation transformation = transformations.get(i);
      Bitmap newResult = transformation.transform(result);

      if (newResult == null) {
        StringBuilder builder =
            new StringBuilder() //
                .append("Transformation ")
                .append(transformation.key())
                .append(" returned null after ")
                .append(i)
                .append(" previous transformation(s).\n\nTransformation list:\n");
        for (Transformation t : transformations) {
          builder.append(t.key()).append('\n');
        }
        throw new NullPointerException(builder.toString());
      }

      if (newResult == result && result.isRecycled()) {
        throw new IllegalStateException(
            "Transformation " + transformation.key() + " returned input Bitmap but recycled it.");
      }

      // If the transformation returned a new bitmap ensure they recycled the original.
      if (newResult != result && !result.isRecycled()) {
        throw new IllegalStateException(
            "Transformation "
                + transformation.key()
                + " mutated input Bitmap but failed to recycle the original.");
      }
      result = newResult;
    }
    return result;
  }
Ejemplo n.º 12
0
  @Override
  public String toString() {
    final StringBuilder builder = new StringBuilder("Request{");
    if (resourceId > 0) {
      builder.append(resourceId);
    } else {
      builder.append(uri);
    }
    if (transformations != null && !transformations.isEmpty()) {
      for (Transformation transformation : transformations) {
        builder.append(' ').append(transformation.key());
      }
    }
    if (stableKey != null) {
      builder.append(" stableKey(").append(stableKey).append(')');
    }
    if (targetWidth > 0) {
      builder.append(" resize(").append(targetWidth).append(',').append(targetHeight).append(')');
    }
    if (centerCrop) {
      builder.append(" centerCrop");
    }
    if (centerInside) {
      builder.append(" centerInside");
    }
    if (rotationDegrees != 0) {
      builder.append(" rotation(").append(rotationDegrees);
      if (hasRotationPivot) {
        builder.append(" @ ").append(rotationPivotX).append(',').append(rotationPivotY);
      }
      builder.append(')');
    }
    if (purgeable) {
      builder.append(" purgeable");
    }
    if (config != null) {
      builder.append(' ').append(config);
    }
    builder.append('}');

    return builder.toString();
  }
Ejemplo n.º 13
0
 @Override
 public boolean validateRsvBits(int i) {
   if ((i & RSV_BITMASK) > 0) {
     return false;
   }
   if (next == null) {
     return true;
   } else {
     return next.validateRsvBits(i | RSV_BITMASK);
   }
 }
Ejemplo n.º 14
0
  public static void transform(SrcImg src, DstImg dst, Transformation trans) {
    int w = dst.getWidth();
    int h = dst.getHeight();

    for (int y = 0; y < h; y++)
      for (int x = 0; x < w; x++) {
        long srcX = trans.getSrcX(x, y);
        long srcY = trans.getSrcY(x, y);

        int pixel00 = src.getRGB((int) (srcX >>> 32), (int) (srcY >>> 32));
        int pixel01 = src.getRGB((int) (srcX >>> 32), (int) (srcY >>> 32) + 1);
        int pixel10 = src.getRGB((int) (srcX >>> 32) + 1, (int) (srcY >>> 32));
        int pixel11 = src.getRGB((int) (srcX >>> 32) + 1, (int) (srcY >>> 32) + 1);

        int pixel =
            merge(pixel00, pixel01, pixel10, pixel11, ((int) srcX) >>> 24, ((int) srcY) >>> 24);

        dst.setRGB(x, y, pixel);
      }
  }
Ejemplo n.º 15
0
  private void draw_ruled(Canvas c, Transformation t, float lineSpacing, float margin) {

    float spacingMm = lineSpacing;
    float vertLineMm = margin;

    int shade = 0xaa;
    float threshold = 1500;
    if (t.scale < threshold) shade += (int) ((threshold - t.scale) / threshold * (0xff - shade));
    paint.setARGB(0xff, shade, shade, shade);

    paint.setStrokeWidth(0);
    int n = (int) Math.floor((heightMm - 2 * marginMm) / spacingMm) - 2;
    float x0 = t.applyX(marginMm / heightMm);
    float x1 = t.applyX((widthMm - marginMm) / heightMm);
    for (int i = 1; i <= n; i++) {
      float y = t.applyY(((heightMm - n * spacingMm) / 2 + i * spacingMm) / heightMm);
      c.drawLine(x0, y, x1, y, paint);
    }

    // Paint margin
    if (margin > 0.0f) {
      paint.setARGB(0xff, 0xff, shade, shade);
      paint.setStrokeWidth(0);
      float y0 = t.applyY(marginMm / heightMm);
      float y1 = t.applyY((heightMm - marginMm) / heightMm);
      float x = t.applyX(vertLineMm / widthMm);
      c.drawLine(x, y0, x, y1, paint);
    }
  }
Ejemplo n.º 16
0
  private void draw_quad(Canvas c, Transformation t) {
    float spacingMm = 5f;
    int nx, ny;
    float x, x0, x1, y, y0, y1;

    int shade = 0xaa;
    float threshold = 1500;
    if (t.scale < threshold) shade += (int) ((threshold - t.scale) / threshold * (0xff - shade));
    paint.setARGB(0xff, shade, shade, shade);

    paint.setStrokeWidth(0);
    ny = (int) Math.floor((heightMm - 2 * marginMm) / spacingMm);
    nx = (int) Math.floor((widthMm - 2 * marginMm) / spacingMm);
    float marginXMm = (widthMm - nx * spacingMm) / 2;
    float marginYMm = (heightMm - ny * spacingMm) / 2;
    x0 = t.applyX(marginXMm / heightMm);
    x1 = t.applyX((widthMm - marginXMm) / heightMm);
    y0 = t.applyY(marginYMm / heightMm);
    y1 = t.applyY((heightMm - marginYMm) / heightMm);
    for (int i = 0; i <= ny; i++) {
      y = t.applyY((marginYMm + i * spacingMm) / heightMm);
      c.drawLine(x0, y, x1, y, paint);
    }
    for (int i = 0; i <= nx; i++) {
      x = t.applyX((marginXMm + i * spacingMm) / heightMm);
      c.drawLine(x, y0, x, y1, paint);
    }
  }
Ejemplo n.º 17
0
 /**
  * Add a custom transformation to be applied to the image.
  *
  * <p>Custom transformations will always be run after the built-in transformations.
  */
 public Builder transform(@NonNull Transformation transformation) {
   if (transformation == null) {
     throw new IllegalArgumentException("Transformation must not be null.");
   }
   if (transformation.key() == null) {
     throw new IllegalArgumentException("Transformation key must not be null.");
   }
   if (transformations == null) {
     transformations = new ArrayList<Transformation>(2);
   }
   transformations.add(transformation);
   return this;
 }
Ejemplo n.º 18
0
  private void draw_cornellnotes(Canvas c, Transformation t) {

    float x0, x1, y0, y1;
    final float MARGIN = 1.25f;

    int shade = 0xaa;
    float threshold = 1500;
    if (t.scale < threshold) shade += (int) ((threshold - t.scale) / threshold * (0xff - shade));
    paint.setARGB(0xff, shade, shade, shade);
    paint.setStrokeWidth(0);

    // Cue Column
    x0 = t.applyX((MARGIN * INCH_in_MM) / widthMm);
    x1 = x0;
    y0 = t.applyY(0);
    y1 = t.applyY((heightMm - (MARGIN * INCH_in_MM)) / heightMm);

    c.drawLine(x0, y0, x1, y1, paint);

    // Summary area at base of page
    x0 = t.applyX(0);
    x1 = t.applyX(widthMm / heightMm);
    y0 = t.applyY((heightMm - (MARGIN * INCH_in_MM)) / heightMm);
    y1 = y0;

    c.drawLine(x0, y0, x1, y1, paint);

    // Details
    float spacingMm = COLLEGERULED_SPACING;
    int n = (int) Math.floor((heightMm - (MARGIN * INCH_in_MM) - 2 * marginMm) / spacingMm);

    x0 = t.applyX((MARGIN * INCH_in_MM) / widthMm + marginMm / heightMm);
    x1 = t.applyX((widthMm - marginMm) / heightMm);

    for (int i = 1; i <= n; i++) {
      float y =
          t.applyY(
              ((heightMm - n * spacingMm - MARGIN * INCH_in_MM) / 2 + i * spacingMm) / heightMm);
      c.drawLine(x0, y, x1, y, paint);
    }
  }
Ejemplo n.º 19
0
 @Override
 public boolean validateRsv(int rsv, byte opCode) {
   if (Util.isControl(opCode)) {
     if ((rsv & RSV_BITMASK) > 0) {
       return false;
     } else {
       if (next == null) {
         return true;
       } else {
         return next.validateRsv(rsv, opCode);
       }
     }
   } else {
     int rsvNext = rsv;
     if ((rsv & RSV_BITMASK) > 0) {
       rsvNext = rsv ^ RSV_BITMASK;
     }
     if (next == null) {
       return true;
     } else {
       return next.validateRsv(rsvNext, opCode);
     }
   }
 }
Ejemplo n.º 20
0
 public WsFrameBase(WsSession wsSession, Transformation transformation) {
   inputBuffer = new byte[Constants.DEFAULT_BUFFER_SIZE];
   messageBufferBinary = ByteBuffer.allocate(wsSession.getMaxBinaryMessageBufferSize());
   messageBufferText = CharBuffer.allocate(wsSession.getMaxTextMessageBufferSize());
   this.wsSession = wsSession;
   Transformation finalTransformation;
   if (isMasked()) {
     finalTransformation = new UnmaskTransformation();
   } else {
     finalTransformation = new NoopTransformation();
   }
   if (transformation == null) {
     this.transformation = finalTransformation;
   } else {
     transformation.setNext(finalTransformation);
     this.transformation = transformation;
   }
 }
Ejemplo n.º 21
0
  private void drawLine(Graphics g, Vector p, Vector q) {
    // FIXME: maybe eliminate class instantiations
    // from this method for performance reasons:
    // use static point arrays for transformations

    Vector u = rotation.apply(p.sub(origin));
    Vector v = rotation.apply(q.sub(origin));

    Point2D.Double from = new Point2D.Double(u.getX(), u.getZ());
    Point2D.Double to = new Point2D.Double(v.getX(), v.getZ());

    Point ifrom = new Point();
    Point ito = new Point();

    transform.transform(from, ifrom);
    transform.transform(to, ito);

    //		g.drawLine(xInt(u.getX()),yInt(u.getZ()),
    //				xInt(v.getX()),yInt(v.getZ()));

    g.drawLine(ifrom.x, ifrom.y, ito.x, ito.y);
  }
Ejemplo n.º 22
0
  public void performTransformation(
      final PhaseResult phaseResult, final Collection<M> currentMatches) throws Exception {
    final TimeMetric lhs = new TimeMetric("LHS");
    final TimeMetric rhs = new TimeMetric("RHS");
    final ScalarMetric modified = new ScalarMetric("Modified");
    nObjectsToModify = Util.calcModify(bc, currentMatches.size());
    modified.setValue(nObjectsToModify);

    lhs.startMeasure();
    driver.beginTransaction();
    lhs(currentMatches);
    lhs.stopMeasure();

    // we do not measure this in the benchmark results
    final List<O> candidatesList = copyAndSort();
    objectsToModify = pickRandom(nObjectsToModify, candidatesList);

    rhs.startMeasure();
    transformation.rhs(objectsToModify);
    driver.finishTransaction();
    rhs.stopMeasure();

    phaseResult.addMetrics(lhs, rhs, modified);
  }
Ejemplo n.º 23
0
  @Override
  public List<MessagePart> sendMessagePart(List<MessagePart> uncompressedParts) {
    List<MessagePart> allCompressedParts = new ArrayList<MessagePart>();

    for (MessagePart uncompressedPart : uncompressedParts) {
      byte opCode = uncompressedPart.getOpCode();
      if (Util.isControl(opCode)) {
        // Control messages can appear in the middle of other messages
        // and must not be compressed. Pass it straight through
        allCompressedParts.add(uncompressedPart);
      } else {
        List<MessagePart> compressedParts = new ArrayList<MessagePart>();
        ByteBuffer uncompressedPayload = uncompressedPart.getPayload();
        SendHandler uncompressedIntermediateHandler = uncompressedPart.getIntermediateHandler();

        deflater.setInput(
            uncompressedPayload.array(),
            uncompressedPayload.arrayOffset() + uncompressedPayload.position(),
            uncompressedPayload.remaining());

        int flush = (uncompressedPart.isFin() ? Deflater.SYNC_FLUSH : Deflater.NO_FLUSH);
        boolean deflateRequired = true;

        while (deflateRequired) {
          ByteBuffer compressedPayload = writeBuffer;

          int written =
              deflater.deflate(
                  compressedPayload.array(),
                  compressedPayload.arrayOffset() + compressedPayload.position(),
                  compressedPayload.remaining(),
                  flush);
          compressedPayload.position(compressedPayload.position() + written);

          if (!uncompressedPart.isFin()
              && compressedPayload.hasRemaining()
              && deflater.needsInput()) {
            // This message part has been fully processed by the
            // deflater. Fire the send handler for this message part
            // and move on to the next message part.
            break;
          }

          // If this point is reached, a new compressed message part
          // will be created...
          MessagePart compressedPart;

          // .. and a new writeBuffer will be required.
          writeBuffer = ByteBuffer.allocate(Constants.DEFAULT_BUFFER_SIZE);

          // Flip the compressed payload ready for writing
          compressedPayload.flip();

          boolean fin = uncompressedPart.isFin();
          boolean full = compressedPayload.limit() == compressedPayload.capacity();
          boolean needsInput = deflater.needsInput();

          if (fin && !full && needsInput) {
            // End of compressed message. Drop EOM bytes and output.
            compressedPayload.limit(compressedPayload.limit() - EOM_BYTES.length);
            compressedPart =
                new MessagePart(
                    true,
                    getRsv(uncompressedPart),
                    opCode,
                    compressedPayload,
                    uncompressedIntermediateHandler,
                    uncompressedIntermediateHandler);
            deflateRequired = false;
            startNewMessage();
          } else if (full && !needsInput) {
            // Write buffer full and input message not fully read.
            // Output and start new compressed part.
            compressedPart =
                new MessagePart(
                    false,
                    getRsv(uncompressedPart),
                    opCode,
                    compressedPayload,
                    uncompressedIntermediateHandler,
                    uncompressedIntermediateHandler);
          } else if (!fin && full && needsInput) {
            // Write buffer full and input message not fully read.
            // Output and get more data.
            compressedPart =
                new MessagePart(
                    false,
                    getRsv(uncompressedPart),
                    opCode,
                    compressedPayload,
                    uncompressedIntermediateHandler,
                    uncompressedIntermediateHandler);
            deflateRequired = false;
          } else if (fin && full && needsInput) {
            // Write buffer full. Input fully read. Deflater may be
            // in one of four states:
            // - output complete (just happened to align with end of
            //   buffer
            // - in middle of EOM bytes
            // - about to write EOM bytes
            // - more data to write
            int eomBufferWritten =
                deflater.deflate(EOM_BUFFER, 0, EOM_BUFFER.length, Deflater.SYNC_FLUSH);
            if (eomBufferWritten < EOM_BUFFER.length) {
              // EOM has just been completed
              compressedPayload.limit(
                  compressedPayload.limit() - EOM_BYTES.length + eomBufferWritten);
              compressedPart =
                  new MessagePart(
                      true,
                      getRsv(uncompressedPart),
                      opCode,
                      compressedPayload,
                      uncompressedIntermediateHandler,
                      uncompressedIntermediateHandler);
              deflateRequired = false;
              startNewMessage();
            } else {
              // More data to write
              // Copy bytes to new write buffer
              writeBuffer.put(EOM_BUFFER, 0, eomBufferWritten);
              compressedPart =
                  new MessagePart(
                      false,
                      getRsv(uncompressedPart),
                      opCode,
                      compressedPayload,
                      uncompressedIntermediateHandler,
                      uncompressedIntermediateHandler);
            }
          } else {
            throw new IllegalStateException("Should never happen");
          }

          // Add the newly created compressed part to the set of parts
          // to pass on to the next transformation.
          compressedParts.add(compressedPart);
        }

        SendHandler uncompressedEndHandler = uncompressedPart.getEndHandler();
        int size = compressedParts.size();
        if (size > 0) {
          compressedParts.get(size - 1).setEndHandler(uncompressedEndHandler);
        }

        allCompressedParts.addAll(compressedParts);
      }
    }

    if (next == null) {
      return allCompressedParts;
    } else {
      return next.sendMessagePart(allCompressedParts);
    }
  }
Ejemplo n.º 24
0
 public void reset() {
   super.reset();
   button.setSelected(false);
 }
Ejemplo n.º 25
0
 public void setRotation(double zangle) {
   initRotation();
   rotation = rotation.rotz(zangle);
   repaint();
 }
Ejemplo n.º 26
0
 protected void initRotation() {
   rotation = new Transformation();
   if (perspective == PERSPECTIVE_TOP) rotation = rotation.rotx(90);
 }
Ejemplo n.º 27
0
  /**
   * @return <code>true</code> if sufficient data was present to process all of the initial header
   */
  private boolean processInitialHeader() throws IOException {
    // Need at least two bytes of data to do this
    if (writePos - readPos < 2) {
      return false;
    }
    int b = inputBuffer[readPos++];
    fin = (b & 0x80) > 0;
    rsv = (b & 0x70) >>> 4;
    opCode = (byte) (b & 0x0F);
    if (!transformation.validateRsv(rsv, opCode)) {
      throw new WsIOException(
          new CloseReason(
              CloseCodes.PROTOCOL_ERROR,
              sm.getString("wsFrame.wrongRsv", Integer.valueOf(rsv), Integer.valueOf(opCode))));
    }

    if (Util.isControl(opCode)) {
      if (!fin) {
        throw new WsIOException(
            new CloseReason(CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.controlFragmented")));
      }
      if (opCode != Constants.OPCODE_PING
          && opCode != Constants.OPCODE_PONG
          && opCode != Constants.OPCODE_CLOSE) {
        throw new WsIOException(
            new CloseReason(
                CloseCodes.PROTOCOL_ERROR,
                sm.getString("wsFrame.invalidOpCode", Integer.valueOf(opCode))));
      }
    } else {
      if (continuationExpected) {
        if (!Util.isContinuation(opCode)) {
          throw new WsIOException(
              new CloseReason(CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.noContinuation")));
        }
      } else {
        try {
          if (opCode == Constants.OPCODE_BINARY) {
            // New binary message
            textMessage = false;
            int size = wsSession.getMaxBinaryMessageBufferSize();
            if (size != messageBufferBinary.capacity()) {
              messageBufferBinary = ByteBuffer.allocate(size);
            }
            binaryMsgHandler = wsSession.getBinaryMessageHandler();
            textMsgHandler = null;
          } else if (opCode == Constants.OPCODE_TEXT) {
            // New text message
            textMessage = true;
            int size = wsSession.getMaxTextMessageBufferSize();
            if (size != messageBufferText.capacity()) {
              messageBufferText = CharBuffer.allocate(size);
            }
            binaryMsgHandler = null;
            textMsgHandler = wsSession.getTextMessageHandler();
          } else {
            throw new WsIOException(
                new CloseReason(
                    CloseCodes.PROTOCOL_ERROR,
                    sm.getString("wsFrame.invalidOpCode", Integer.valueOf(opCode))));
          }
        } catch (IllegalStateException ise) {
          // Thrown if the session is already closed
          throw new WsIOException(
              new CloseReason(CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.sessionClosed")));
        }
      }
      continuationExpected = !fin;
    }
    b = inputBuffer[readPos++];
    // Client data must be masked
    if ((b & 0x80) == 0 && isMasked()) {
      throw new WsIOException(
          new CloseReason(CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.notMasked")));
    }
    payloadLength = b & 0x7F;
    state = State.PARTIAL_HEADER;
    return true;
  }
Ejemplo n.º 28
0
  private boolean processDataControl() throws IOException {
    TransformationResult tr = transformation.getMoreData(opCode, fin, rsv, controlBufferBinary);
    if (TransformationResult.UNDERFLOW.equals(tr)) {
      return false;
    }
    // Control messages have fixed message size so
    // TransformationResult.OVERFLOW is not possible here

    controlBufferBinary.flip();
    if (opCode == Constants.OPCODE_CLOSE) {
      open = false;
      String reason = null;
      int code = CloseCodes.NORMAL_CLOSURE.getCode();
      if (controlBufferBinary.remaining() == 1) {
        controlBufferBinary.clear();
        // Payload must be zero or greater than 2
        throw new WsIOException(
            new CloseReason(CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.oneByteCloseCode")));
      }
      if (controlBufferBinary.remaining() > 1) {
        code = controlBufferBinary.getShort();
        if (controlBufferBinary.remaining() > 0) {
          CoderResult cr = utf8DecoderControl.decode(controlBufferBinary, controlBufferText, true);
          if (cr.isError()) {
            controlBufferBinary.clear();
            controlBufferText.clear();
            throw new WsIOException(
                new CloseReason(
                    CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.invalidUtf8Close")));
          }
          // There will be no overflow as the output buffer is big
          // enough. There will be no underflow as all the data is
          // passed to the decoder in a single call.
          controlBufferText.flip();
          reason = controlBufferText.toString();
        }
      }
      wsSession.onClose(new CloseReason(Util.getCloseCode(code), reason));
    } else if (opCode == Constants.OPCODE_PING) {
      if (wsSession.isOpen()) {
        wsSession.getBasicRemote().sendPong(controlBufferBinary);
      }
    } else if (opCode == Constants.OPCODE_PONG) {
      MessageHandler.Whole<PongMessage> mhPong = wsSession.getPongMessageHandler();
      if (mhPong != null) {
        try {
          mhPong.onMessage(new WsPongMessage(controlBufferBinary));
        } catch (Throwable t) {
          handleThrowableOnSend(t);
        } finally {
          controlBufferBinary.clear();
        }
      }
    } else {
      // Should have caught this earlier but just in case...
      controlBufferBinary.clear();
      throw new WsIOException(
          new CloseReason(
              CloseCodes.PROTOCOL_ERROR,
              sm.getString("wsFrame.invalidOpCode", Integer.valueOf(opCode))));
    }
    controlBufferBinary.clear();
    newFrame();
    return true;
  }
Ejemplo n.º 29
0
  private boolean processDataText() throws IOException {
    // Copy the available data to the buffer
    TransformationResult tr = transformation.getMoreData(opCode, fin, rsv, messageBufferBinary);
    while (!TransformationResult.END_OF_FRAME.equals(tr)) {
      // Frame not complete - we ran out of something
      // Convert bytes to UTF-8
      messageBufferBinary.flip();
      while (true) {
        CoderResult cr = utf8DecoderMessage.decode(messageBufferBinary, messageBufferText, false);
        if (cr.isError()) {
          throw new WsIOException(
              new CloseReason(CloseCodes.NOT_CONSISTENT, sm.getString("wsFrame.invalidUtf8")));
        } else if (cr.isOverflow()) {
          // Ran out of space in text buffer - flush it
          if (usePartial()) {
            messageBufferText.flip();
            sendMessageText(false);
            messageBufferText.clear();
          } else {
            throw new WsIOException(
                new CloseReason(CloseCodes.TOO_BIG, sm.getString("wsFrame.textMessageTooBig")));
          }
        } else if (cr.isUnderflow()) {
          // Compact what we have to create as much space as possible
          messageBufferBinary.compact();

          // Need more input
          // What did we run out of?
          if (TransformationResult.OVERFLOW.equals(tr)) {
            // Ran out of message buffer - exit inner loop and
            // refill
            break;
          } else {
            // TransformationResult.UNDERFLOW
            // Ran out of input data - get some more
            return false;
          }
        }
      }
      // Read more input data
      tr = transformation.getMoreData(opCode, fin, rsv, messageBufferBinary);
    }

    messageBufferBinary.flip();
    boolean last = false;
    // Frame is fully received
    // Convert bytes to UTF-8
    while (true) {
      CoderResult cr = utf8DecoderMessage.decode(messageBufferBinary, messageBufferText, last);
      if (cr.isError()) {
        throw new WsIOException(
            new CloseReason(CloseCodes.NOT_CONSISTENT, sm.getString("wsFrame.invalidUtf8")));
      } else if (cr.isOverflow()) {
        // Ran out of space in text buffer - flush it
        if (usePartial()) {
          messageBufferText.flip();
          sendMessageText(false);
          messageBufferText.clear();
        } else {
          throw new WsIOException(
              new CloseReason(CloseCodes.TOO_BIG, sm.getString("wsFrame.textMessageTooBig")));
        }
      } else if (cr.isUnderflow() & !last) {
        // End of frame and possible message as well.

        if (continuationExpected) {
          // If partial messages are supported, send what we have
          // managed to decode
          if (usePartial()) {
            messageBufferText.flip();
            sendMessageText(false);
            messageBufferText.clear();
          }
          messageBufferBinary.compact();
          newFrame();
          // Process next frame
          return true;
        } else {
          // Make sure coder has flushed all output
          last = true;
        }
      } else {
        // End of message
        messageBufferText.flip();
        sendMessageText(true);

        newMessage();
        return true;
      }
    }
  }
Ejemplo n.º 30
0
  private void draw_dayplanner(Canvas c, Transformation t, Calendar calendar) {
    float x0, x1, y, y0, y1;
    float textHeight;
    int shade = 0xaa;
    float threshold = 1500;
    if (t.scale < threshold) shade += (int) ((threshold - t.scale) / threshold * (0xff - shade));
    // paint.setARGB(0xff, shade, shade, shade);
    paint.setStrokeWidth(0);
    paint.setColor(Color.DKGRAY);

    Typeface font = Typeface.create(Typeface.SERIF, Typeface.BOLD);
    paint.setTypeface(font);
    paint.setAntiAlias(true);

    // Header
    float headerHeightMm = 30f;
    x0 = t.applyX(marginMm / heightMm);
    x1 = t.applyX((widthMm - marginMm) / heightMm);
    y = t.applyY(headerHeightMm / heightMm);
    c.drawLine(x0, y, x1, y, paint);

    textHeight = t.scaleText(24f);
    paint.setTextSize(textHeight);
    y = t.applyY(marginMm / heightMm) + textHeight;
    c.drawText(
        calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()), x0, y, paint);

    // I'm leaving this out for now; Should there be a gui to pick the day of the year? Or just let
    // the user write the date?
    //		y0 = t.applyY((widthMm-marginMm)/widthMm);
    //		c.drawText(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)), x0, y0, paint);
    //
    //		paint.setTextSize(t.scaleText(12f));
    //
    //		c.drawText(calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG,
    // Locale.getDefault()), x0 + t.applyX(2*marginMm/heightMm), y0 + t.applyY(marginMm/heightMm),
    // paint);
    //
    //		paint.setTextSize(t.scaleText(10f));
    //		font = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
    //		paint.setTextAlign(Align.RIGHT);
    //		c.drawText("Week " +
    // calendar.get(Calendar.WEEK_OF_YEAR),t.applyX((widthMm-marginMm)/heightMm), t.applyY((float)
    // (marginMm*1.75/widthMm)), paint);

    // Details
    paint.setTextAlign(Align.LEFT);
    paint.setARGB(0xff, shade, shade, shade);
    float spacingMm = COLLEGERULED_SPACING;
    int n = (int) Math.floor((heightMm - headerHeightMm - marginMm) / spacingMm);

    x0 = t.applyX(marginMm / heightMm);
    x1 = t.applyX((widthMm - marginMm) / heightMm);

    int hourMarker = 7;
    textHeight = t.scaleText(10f);
    paint.setTextSize(textHeight);

    for (int i = 1; i <= n; i++) {
      y = t.applyY((headerHeightMm + i * spacingMm) / heightMm);
      c.drawLine(x0, y, x1, y, paint);

      if (i % 2 == 1) {
        y = t.applyY((headerHeightMm + (i - 0.5f) * spacingMm) / heightMm) + textHeight / 2;
        c.drawText(hourMarker + ":", x0, y, paint);

        hourMarker++;
        if (hourMarker == 13) hourMarker = 1;
      }
    }
  }