private InputStream generateExcel(List<Map<String, Object>> detailList) throws IOException {
    Workbook wb = new HSSFWorkbook();
    Sheet sheet1 = wb.createSheet("sheet1");
    CellStyle headerStyle = getHeaderStyle(wb);
    CellStyle firstCellStyle = getFirsetCellStyle(wb);
    CellStyle commonCellStyle = getCommonCellStyle(wb);
    CellStyle amtCellStyle = getAmtCellStyle(wb);

    for (int i = 0; i < LENGTH_9; i++) {
      sheet1.setColumnWidth(i, STR_15 * STR_256);
    }

    // 表头
    Row row = sheet1.createRow(0);
    row.setHeightInPoints(STR_20);

    Cell cell = headInfo(headerStyle, row);

    if (detailList.size() == 0) {
      row = sheet1.createRow(1);
      cell = row.createCell(0);
      cell.setCellValue(NO_RECORD);
    } else {
      fillData(detailList, sheet1, firstCellStyle, commonCellStyle, amtCellStyle);
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    wb.write(outputStream);
    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    outputStream.close();
    return inputStream;
  }
Example #2
0
  public ByteBuffer toBytes() {
    byte[] keyBytes = Bytes.toBytes(key);
    byte[] keyLengthBytes = Bytes.toBytes(keyBytes.length);
    byte[] valueLengthBytes = Bytes.toBytes(value.length);
    byte[] oldVersionBytes = Bytes.toBytes(oldVersion);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
      outputStream.write(keyLengthBytes);
      outputStream.write(keyBytes);
      outputStream.write(valueLengthBytes);
      outputStream.write(value);
      outputStream.write(oldVersionBytes);
    } catch (IOException e) {
      log.error("Unexpected error while serializing an option", e);
    }

    byte[] concatenated = outputStream.toByteArray();
    ByteBuffer serialized = ByteBuffer.wrap(concatenated);
    try {
      outputStream.close();
    } catch (IOException ignored) {
    }
    return serialized;
  }
  @Override
  public void decompress() {
    if (compressed) {
      Inflater decompressor = new Inflater();
      decompressor.setInput(data);

      ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);

      byte[] buf = new byte[1024];
      while (!decompressor.finished()) {
        try {
          int count = decompressor.inflate(buf);
          bos.write(buf, 0, count);
        } catch (DataFormatException e) {

        }
      }
      try {
        bos.close();
      } catch (IOException e) {

      }

      data = bos.toByteArray();
    }
  }
Example #4
0
 private void createData() throws IOException {
   // apache commons' implementation required
   ByteArrayOutputStream bstream = new ByteArrayOutputStream();
   for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) bstream.write(b);
   bstream.write(Byte.MAX_VALUE);
   data = bstream.toByteArray();
   bstream.close(); // doesn't really do anything
 }
Example #5
0
  /** Perform the transformation to always return a String object */
  protected Object doTransform(Object src, String encoding) throws TransformerException {
    try {
      HttpResponse response = (HttpResponse) src;
      ByteArrayOutputStream bos = new ByteArrayOutputStream(8192);
      OutputStream outstream = bos;
      ResponseWriter writer = new ResponseWriter(outstream, encoding);
      writer.println(response.getStatusLine());
      Iterator item = response.getHeaderIterator();
      while (item.hasNext()) {
        Header header = (Header) item.next();
        writer.print(header.toExternalForm());
      }
      writer.println();
      writer.flush();

      InputStream content = response.getBody();
      if (content != null) {
        Header transferenc = response.getFirstHeader(HttpConstants.HEADER_TRANSFER_ENCODING);
        if (transferenc != null) {
          response.removeHeaders(HttpConstants.HEADER_CONTENT_LENGTH);
          if (transferenc.getValue().indexOf(HttpConstants.TRANSFER_ENCODING_CHUNKED) != -1) {
            outstream = new ChunkedOutputStream(outstream);
          }
        }

        IOUtils.copy(content, outstream);

        if (outstream instanceof ChunkedOutputStream) {
          ((ChunkedOutputStream) outstream).finish();
        }
      }

      outstream.flush();
      bos.flush();
      byte[] result = bos.toByteArray();
      outstream.close();
      writer.close();
      bos.close();

      String output = null;
      try {
        output = new String(result, encoding);
      } catch (UnsupportedEncodingException uee) {
        // I believe this is never reached since a TransformerExcpetion
        // is thrown before at new ResponseWriter(outstream, encoding) if
        // encoding is not supported
        output = new String(result);
      }

      return output;
    } catch (IOException e) {
      throw new TransformerException(this, e);
    }
  }
Example #6
0
 protected String read(InputStream resource) throws IOException {
   int i;
   byte[] buffer = new byte[65565];
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   while ((i = resource.read(buffer, 0, buffer.length)) != -1) {
     out.write(buffer, 0, i);
   }
   out.flush();
   out.close();
   return new String(out.toByteArray(), "UTF-8");
 }
Example #7
0
  public static byte[] decrypt(InputStream fromInputStream, String password) throws IOException {
    CipherSession cipherSession = new CipherSession(password);
    MultiCipherInputStream cipherInputStream =
        new MultiCipherInputStream(fromInputStream, cipherSession);
    ByteArrayOutputStream plaintextOutputStream = new ByteArrayOutputStream();

    FileUtil.appendToOutputStream(cipherInputStream, plaintextOutputStream);

    cipherInputStream.close();
    plaintextOutputStream.close();

    return plaintextOutputStream.toByteArray();
  }
 @Override
 public void close() throws IOException {
   if (tempMemoryBuffer != null) {
     tempMemoryBuffer.close();
   } else {
     bufOut.close();
     fout.close();
   }
   closed = true;
   if (runnable != null) {
     runnable.run();
   }
 }
Example #9
0
  /**
   * Used for uncompressing a byte array into a uncompressed byte array using GZIP
   *
   * @param bytes An array of bytes to uncompress
   * @return an uncompressed byte array
   * @throws java.io.IOException if it fails to read from a GZIPInputStream
   * @see java.util.zip.GZIPInputStream
   */
  public byte[] uncompressByteArray(byte[] bytes) throws IOException {
    // TODO add strict behaviour as option
    if (!isCompressed(bytes)) {
      /*
       * if (strict) { // throw a specific exception here to allow users of
       * this method to // diffientiate between general IOExceptions and an
       * invalid format logger.warn("Data is not of type GZIP compressed." + "
       * The data may not have been compressed in the first place."); throw new
       * CompressionException("Not in GZIP format"); }
       */

      // nothing to uncompress
      if (logger.isDebugEnabled()) {
        logger.debug("Data already uncompressed; doing nothing");
      }
      return bytes;
    }

    if (logger.isDebugEnabled()) {
      logger.debug("Uncompressing message of size: " + bytes.length);
    }

    ByteArrayInputStream bais = null;
    GZIPInputStream gzis = null;
    ByteArrayOutputStream baos = null;

    try {
      bais = new ByteArrayInputStream(bytes);
      gzis = new GZIPInputStream(bais);
      baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);

      IOUtils.copy(gzis, baos);
      gzis.close();
      bais.close();

      byte[] uncompressedByteArray = baos.toByteArray();
      baos.close();

      if (logger.isDebugEnabled()) {
        logger.debug("Uncompressed message to size: " + uncompressedByteArray.length);
      }

      return uncompressedByteArray;
    } catch (IOException ioex) {
      throw ioex;
    } finally {
      IOUtils.closeQuietly(gzis);
      IOUtils.closeQuietly(bais);
      IOUtils.closeQuietly(baos);
    }
  }
Example #10
0
  @Test
  public void verifyBytesWritten() throws IOException, WriteFileInContainerException {
    cont.storeFile(
        file, new BufferedInputStream(new ByteArrayInputStream(data)), FileInContainer.NO_TAIL_ID);

    // apache commons' implementation required
    ByteArrayOutputStream bstream = new ByteArrayOutputStream();
    bstream.write(containerHeader);
    bstream.write(fileHeader);
    bstream.write(data);
    bstream.write(checksum);
    byte[] expected = bstream.toByteArray();
    bstream.close();
    byte[] actual = FileUtils.readFileToByteArray(new java.io.File(cont.getFileName()));
    assertArrayEquals(expected, actual);
  }
  private InputStream generatePdf(List<Map<String, Object>> detailList)
      throws IOException, DocumentException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    Rectangle rectPageSize = new Rectangle(PageSize.A4);
    Document document = new Document(rectPageSize, STR_20, STR_20, STR_20, STR_20);
    PdfWriter.getInstance(document, output);
    document.open();

    BaseFont bfChinese =
        BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); // 设置中文字体
    com.itextpdf.text.Font headFont =
        new com.itextpdf.text.Font(bfChinese, STR_10, com.itextpdf.text.Font.BOLD);
    com.itextpdf.text.Font commonFont =
        new com.itextpdf.text.Font(bfChinese, STR_10, com.itextpdf.text.Font.NORMAL); // 设置字体大小
    com.itextpdf.text.Font amtFont =
        new com.itextpdf.text.Font(bfChinese, STR_10, com.itextpdf.text.Font.BOLD); // 设置字体大小
    amtFont.setColor(STR_39, STR_157, STR_94);

    float[] widths = {
      STR_0_1F, STR_0_15F, STR_0_15F, STR_0_15F, STR_0_15F, STR_0_15F, STR_0_15F, STR_0_15F
    };
    PdfPTable table = new PdfPTable(widths);
    table.getDefaultCell().setBorder(1);

    PdfPCell cell;
    headStyle(headFont, table);
    if (detailList.size() == 0) {
      cell = new PdfPCell(new Paragraph(NO_RECORD, commonFont));
      cell.setHorizontalAlignment(Element.ALIGN_LEFT);
      cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cell.setColspan(STR_9);
      table.addCell(cell);
    } else {
      fillData(detailList, commonFont, amtFont, table);
    }

    document.add(table);
    document.close();
    InputStream inputStream = new ByteArrayInputStream(output.toByteArray());
    output.close();
    return inputStream;
  }
Example #12
0
 // TODO move to separate thread?
 public void compress() {
   if (!compressed) {
     Deflater deflater = new Deflater();
     deflater.setInput(fileData);
     deflater.setLevel(Deflater.BEST_COMPRESSION);
     deflater.finish();
     ByteArrayOutputStream bos = new ByteArrayOutputStream(fileData.length);
     byte[] buffer = new byte[1024];
     while (!deflater.finished()) {
       int bytesCompressed = deflater.deflate(buffer);
       bos.write(buffer, 0, bytesCompressed);
     }
     try {
       bos.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
     fileData = bos.toByteArray();
     compressed = true;
   }
 }
Example #13
0
  /**
   * Used for compressing a byte array into a new byte array using GZIP
   *
   * @param bytes An array of bytes to compress
   * @return a compressed byte array
   * @throws java.io.IOException if it fails to write to a GZIPOutputStream
   * @see java.util.zip.GZIPOutputStream
   */
  public byte[] compressByteArray(byte[] bytes) throws IOException {
    // TODO add strict behaviour as option
    if (bytes == null || isCompressed(bytes)) {
      // nothing to compress
      if (logger.isDebugEnabled()) {
        logger.debug("Data already compressed; doing nothing");
      }
      return bytes;
    }

    if (logger.isDebugEnabled()) {
      logger.debug("Compressing message of size: " + bytes.length);
    }

    ByteArrayOutputStream baos = null;
    GZIPOutputStream gzos = null;

    try {
      baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
      gzos = new GZIPOutputStream(baos);

      gzos.write(bytes, 0, bytes.length);
      gzos.finish();
      gzos.close();

      byte[] compressedByteArray = baos.toByteArray();
      baos.close();

      if (logger.isDebugEnabled()) {
        logger.debug("Compressed message to size: " + compressedByteArray.length);
      }

      return compressedByteArray;
    } catch (IOException ioex) {
      throw ioex;
    } finally {
      IOUtils.closeQuietly(gzos);
      IOUtils.closeQuietly(baos);
    }
  }
Example #14
0
  /**
   * Decompresses a compressed byte array.
   *
   * @param input The byte array to be decompressed.
   * @return The byte array in its decompressed, readable form.
   */
  public static byte[] decompress(byte[] input) {
    try {
      final Inflater inflater = new Inflater();
      final ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(input.length);
      final byte[] buffer = new byte[1024];
      inflater.setInput(input);

      while (!inflater.finished()) {
        final int count = inflater.inflate(buffer);
        byteOutput.write(buffer, 0, count);
      }

      byteOutput.close();
      return byteOutput.toByteArray();
    } catch (final DataFormatException e) {
      RadixCore.getInstance().quitWithException("Error decompressing byte array.", e);
      return null;
    } catch (final IOException e) {
      RadixCore.getInstance().quitWithException("Error decompressing byte array.", e);
      return null;
    }
  }
Example #15
0
  /**
   * Compresses the data in a byte array.
   *
   * @param input The byte array to be compressed.
   * @return The byte array in its compressed form.
   */
  public static byte[] compress(byte[] input) {
    try {
      final Deflater deflater = new Deflater();
      deflater.setLevel(Deflater.BEST_COMPRESSION);
      deflater.setInput(input);

      final ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(input.length);
      deflater.finish();

      final byte[] buffer = new byte[1024];

      while (!deflater.finished()) {
        final int count = deflater.deflate(buffer);
        byteOutput.write(buffer, 0, count);
      }

      byteOutput.close();
      return byteOutput.toByteArray();
    } catch (final IOException e) {
      RadixCore.getInstance().quitWithException("Error compressing byte array.", e);
      return null;
    }
  }
  public static ForensicReportBase64 getBase64(String urlHash, String mongoHostIP)
      throws UnknownHostException {
    System.out.println("Create base64 for hash " + urlHash);
    MongoClient mongoclient = new MongoClient(mongoHostIP, 27017);
    Morphia morphia = new Morphia();
    morphia.map(ForensicReport.class).map(dqReport.class);
    Datastore ds = new Morphia().createDatastore(mongoclient, "ForensicDatabase");
    ds.ensureCaps();
    ForensicReportBase64 reportBase64 = new ForensicReportBase64();
    ForensicReport report = ds.get(ForensicReport.class, urlHash);

    if (report != null) {
      if (report.displayImage != null) {
        byte[] displayImageInByte;
        BufferedImage displayImage;
        try {
          displayImage = ImageIO.read(new File(report.displayImage));
          ByteArrayOutputStream displayImagebuffer = new ByteArrayOutputStream();
          ImageIO.write(displayImage, "png", displayImagebuffer);
          displayImagebuffer.flush();
          displayImageInByte = displayImagebuffer.toByteArray();
          displayImagebuffer.close();
          ScalingReport dataScale = new ScalingReport();
          try {
            dataScale = scale(displayImageInByte, 500, 500);
            String displayImageBase64String =
                Base64.getEncoder().encodeToString(dataScale.scaledByte);
            reportBase64.displayImageBase64 = "data:image/jpeg;base64," + displayImageBase64String;
            reportBase64.widthdisplayImage = dataScale.width;
          } catch (ApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Scalling exception");
            String displayImageBase64String =
                Base64.getEncoder().encodeToString(displayImageInByte);
            reportBase64.displayImageBase64 = "data:image/jpeg;base64," + displayImageBase64String;
            reportBase64.widthdisplayImage = displayImage.getWidth();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          System.out.println("Display image exception");
        }
      }
      if (report.thumbnailReport.numberOfThumbnails > 0) {
        for (int ThumbInd = 0; ThumbInd < report.thumbnailReport.thumbnailList.size(); ThumbInd++) {
          try {
            byte[] thumbInByte;
            BufferedImage thumbImage;
            thumbImage = ImageIO.read(new File(report.thumbnailReport.thumbnailList.get(ThumbInd)));
            ByteArrayOutputStream thumbbuffer = new ByteArrayOutputStream();
            ImageIO.write(thumbImage, "png", thumbbuffer);
            thumbbuffer.flush();
            thumbInByte = thumbbuffer.toByteArray();
            thumbbuffer.close();
            ScalingReport thumbScale = new ScalingReport();
            try {
              thumbScale = scale(thumbInByte, 500, 500);
              String thumbBase64String = Base64.getEncoder().encodeToString(thumbScale.scaledByte);
              reportBase64.thumbBase64.add("data:image/jpeg;base64," + thumbBase64String);
              reportBase64.widththumb.add(thumbScale.width);
            } catch (ApplicationException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
              System.out.println("Scalling exception");
              String thumbBase64String = Base64.getEncoder().encodeToString(thumbInByte);
              reportBase64.thumbBase64.add("data:image/jpeg;base64," + thumbBase64String);
              reportBase64.widththumb.add(thumbImage.getWidth());
            }
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }
      if (report.dqReport.completed) {
        byte[] dqInByte;
        BufferedImage dqImage;
        try {
          dqImage = ImageIO.read(new File(report.dqReport.map));
          ByteArrayOutputStream dqbuffer = new ByteArrayOutputStream();
          ImageIO.write(dqImage, "png", dqbuffer);
          dqbuffer.flush();
          dqInByte = dqbuffer.toByteArray();
          dqbuffer.close();
          ScalingReport dqScale = new ScalingReport();
          try {
            dqScale = scale(dqInByte, 130, 130);
            String dqBase64String = Base64.getEncoder().encodeToString(dqScale.scaledByte);
            reportBase64.dqBase64 = "data:image/jpeg;base64," + dqBase64String;
            reportBase64.widthdq = dqScale.width;
          } catch (ApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Scalling exception");
            String dqBase64String = Base64.getEncoder().encodeToString(dqInByte);
            reportBase64.dqBase64 = "data:image/jpeg;base64," + dqBase64String;
            reportBase64.widthdq = dqImage.getWidth();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

      if (report.dwNoiseReport.completed) {
        byte[] dwNoiseInByte;
        BufferedImage dwNoiseImage;
        try {
          dwNoiseImage = ImageIO.read(new File(report.dwNoiseReport.map));
          ByteArrayOutputStream dwNoisebuffer = new ByteArrayOutputStream();
          ImageIO.write(dwNoiseImage, "png", dwNoisebuffer);
          dwNoisebuffer.flush();
          dwNoiseInByte = dwNoisebuffer.toByteArray();
          dwNoisebuffer.close();
          ScalingReport dwNoiseScale = new ScalingReport();
          try {
            dwNoiseScale = scale(dwNoiseInByte, 130, 130);
            String dwNoiseBase64String =
                Base64.getEncoder().encodeToString(dwNoiseScale.scaledByte);
            reportBase64.dwNoiseBase64 = "data:image/jpeg;base64," + dwNoiseBase64String;
            reportBase64.widthdwNoise = dwNoiseScale.width;
          } catch (ApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Scalling exception");
            String dwNoiseBase64String = Base64.getEncoder().encodeToString(dwNoiseInByte);
            reportBase64.dwNoiseBase64 = "data:image/jpeg;base64," + dwNoiseBase64String;
            reportBase64.widthdwNoise = dwNoiseImage.getWidth();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if (report.elaReport.completed) {
        byte[] elaInByte;
        BufferedImage elaImage;
        try {
          elaImage = ImageIO.read(new File(report.elaReport.map));
          ByteArrayOutputStream elabuffer = new ByteArrayOutputStream();
          ImageIO.write(elaImage, "png", elabuffer);
          elabuffer.flush();
          elaInByte = elabuffer.toByteArray();
          elabuffer.close();
          ScalingReport elaScale = new ScalingReport();
          try {
            elaScale = scale(elaInByte, 130, 130);
            String elaBase64String = Base64.getEncoder().encodeToString(elaScale.scaledByte);
            reportBase64.elaBase64 = "data:image/jpeg;base64," + elaBase64String;
            reportBase64.widthela = elaScale.width;
          } catch (ApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Scalling exception");
            String elaBase64String = Base64.getEncoder().encodeToString(elaInByte);
            reportBase64.elaBase64 = "data:image/jpeg;base64," + elaBase64String;
            reportBase64.widthela = elaImage.getWidth();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if (report.blockingReport.completed) {
        byte[] blockingInByte;
        BufferedImage blockingImage;
        try {
          blockingImage = ImageIO.read(new File(report.blockingReport.map));
          ByteArrayOutputStream blockingbuffer = new ByteArrayOutputStream();
          ImageIO.write(blockingImage, "png", blockingbuffer);
          blockingbuffer.flush();
          blockingInByte = blockingbuffer.toByteArray();
          blockingbuffer.close();
          ScalingReport blockingScale = new ScalingReport();
          try {
            blockingScale = scale(blockingInByte, 130, 130);
            String blockingBase64String =
                Base64.getEncoder().encodeToString(blockingScale.scaledByte);
            reportBase64.blockingBase64 = "data:image/jpeg;base64," + blockingBase64String;
            reportBase64.widthblocking = blockingScale.width;
          } catch (ApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Scalling exception");
            String blockingBase64String = Base64.getEncoder().encodeToString(blockingInByte);
            reportBase64.blockingBase64 = "data:image/jpeg;base64," + blockingBase64String;
            reportBase64.widthblocking = blockingImage.getWidth();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if (report.medianNoiseReport.completed) {
        byte[] medianNoiseInByte;
        BufferedImage medianNoiseImage;
        try {
          medianNoiseImage = ImageIO.read(new File(report.medianNoiseReport.map));
          ByteArrayOutputStream medianNoisebuffer = new ByteArrayOutputStream();
          ImageIO.write(medianNoiseImage, "png", medianNoisebuffer);
          medianNoisebuffer.flush();
          medianNoiseInByte = medianNoisebuffer.toByteArray();
          medianNoisebuffer.close();
          ScalingReport medianNoiseScale = new ScalingReport();
          try {
            medianNoiseScale = scale(medianNoiseInByte, 130, 130);
            String medianNoiseBase64String =
                Base64.getEncoder().encodeToString(medianNoiseScale.scaledByte);
            reportBase64.medianNoiseBase64 = "data:image/jpeg;base64," + medianNoiseBase64String;
            reportBase64.widthmedianNoise = medianNoiseScale.width;
          } catch (ApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Scalling exception");
            String medianNoiseBase64String = Base64.getEncoder().encodeToString(medianNoiseInByte);
            reportBase64.medianNoiseBase64 = "data:image/jpeg;base64," + medianNoiseBase64String;
            reportBase64.widthmedianNoise = medianNoiseImage.getWidth();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if (report.ghostReport.completed) {

        try {
          for (int GhostInd = 0; GhostInd < report.ghostReport.maps.size(); GhostInd++) {
            byte[] ghostInByte;
            BufferedImage ghostImage;
            ghostImage = ImageIO.read(new File(report.ghostReport.maps.get(GhostInd)));
            ByteArrayOutputStream ghostbuffer = new ByteArrayOutputStream();
            ImageIO.write(ghostImage, "png", ghostbuffer);
            ghostbuffer.flush();
            ghostInByte = ghostbuffer.toByteArray();
            ghostbuffer.close();
            ScalingReport ghostScale = new ScalingReport();
            try {
              ghostScale = scale(ghostInByte, 130, 130);
              String ghostBase64String = Base64.getEncoder().encodeToString(ghostScale.scaledByte);
              reportBase64.ghostBase64.add("data:image/jpeg;base64," + ghostBase64String);
              reportBase64.widthghost.add(ghostScale.width);
            } catch (ApplicationException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
              System.out.println("Scalling exception");
              String ghostBase64String = Base64.getEncoder().encodeToString(ghostInByte);
              reportBase64.ghostBase64.add("data:image/jpeg;base64," + ghostBase64String);
              reportBase64.widthghost.add(ghostImage.getWidth());
            }
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

      if (report.gridsReport.completed) {
        byte[] gridsInByte, gridsInvInByte;
        BufferedImage gridsImage, gridsInvImage;
        String gridsBase64String, gridsInvBase64String;
        try {
          // GRIDS
          gridsImage = ImageIO.read(new File(report.gridsReport.map));
          ByteArrayOutputStream gridsbuffer = new ByteArrayOutputStream();
          ImageIO.write(gridsImage, "png", gridsbuffer);
          gridsbuffer.flush();
          gridsInByte = gridsbuffer.toByteArray();
          gridsbuffer.close();
          ScalingReport gridsScale = new ScalingReport();
          try {
            gridsScale = scale(gridsInByte, 130, 130);
            gridsBase64String = Base64.getEncoder().encodeToString(gridsScale.scaledByte);
            reportBase64.gridsBase64 = "data:image/jpeg;base64," + gridsBase64String;
            reportBase64.widthgrids = gridsScale.width;
          } catch (ApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Scalling exception");
            gridsBase64String = Base64.getEncoder().encodeToString(gridsInByte);
            reportBase64.gridsBase64 = "data:image/jpeg;base64," + gridsBase64String;
            reportBase64.widthgrids = gridsImage.getWidth();
          }

          // GRIDS INVERSED
          gridsInvImage = ImageIO.read(new File(report.gridsInversedReport.map));
          ByteArrayOutputStream gridsInvbuffer = new ByteArrayOutputStream();
          ImageIO.write(gridsInvImage, "png", gridsInvbuffer);
          gridsInvbuffer.flush();
          gridsInvInByte = gridsInvbuffer.toByteArray();
          gridsInvbuffer.close();
          ScalingReport gridsInvScale = new ScalingReport();
          try {
            gridsInvScale = scale(gridsInvInByte, 130, 130);
            gridsInvBase64String = Base64.getEncoder().encodeToString(gridsInvScale.scaledByte);
            reportBase64.gridsInversedBase64 = "data:image/jpeg;base64," + gridsInvBase64String;
            reportBase64.widthgridsInversed = gridsInvScale.width;
          } catch (ApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Scalling exception");
            gridsInvBase64String = Base64.getEncoder().encodeToString(gridsInvInByte);
            reportBase64.gridsInversedBase64 = "data:image/jpeg;base64," + gridsInvBase64String;
            reportBase64.widthgridsInversed = gridsInvImage.getWidth();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

    } else {
      System.out.println("report is empty");
    }
    mongoclient.close();
    return reportBase64;
  }
  public void process(SlingHttpServletResponse response, ProxyResponse proxyResponse)
      throws IOException {
    Map<String, String[]> headers = proxyResponse.getResponseHeaders();

    // Check if the content-length is smaller than the maximum (if any).
    String[] contentLengthHeader = headers.get("Content-Length");
    if (contentLengthHeader != null) {
      int length = Integer.parseInt(contentLengthHeader[0]);
      if (length > MAX_RSS_LENGTH) {
        response.sendError(
            HttpServletResponse.SC_FORBIDDEN,
            "This RSS feed is too big. The maximum for a feed is: " + MAX_RSS_LENGTH);
        return;
      }
    }

    // Check if the Content-Type we get is valid (if any).
    String[] contentTypeHeader = headers.get("Content-Type");
    if (contentTypeHeader != null) {
      String contentType = contentTypeHeader[0];
      if (contentType.contains(";")) {
        contentType = contentType.substring(0, contentType.indexOf(';'));
      }
      if (!contentTypes.contains(contentType)) {
        response.sendError(
            HttpServletResponse.SC_FORBIDDEN, "This URL doesn't send a proper Content-Type back");
        return;
      }
    }

    boolean isValid = false;
    InputStream in = proxyResponse.getResponseBodyAsInputStream();
    InputStreamReader reader = new InputStreamReader(in);

    // XMLStreamWriter writer = null;
    XMLEventWriter writer = null;
    ByteArrayOutputStream out = null;

    int i = 0;
    try {
      XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(reader);
      // Create a temporary outputstream where we can write to.
      out = new ByteArrayOutputStream();

      Map<String, Boolean> checkedElements = new HashMap<String, Boolean>();
      checkedElements.put("rss", false);
      checkedElements.put("channel", false);
      checkedElements.put("title", false);
      checkedElements.put("link", false);
      checkedElements.put("item", false);
      checkedElements.put("title", false);
      checkedElements.put("link", false);

      XMLOutputFactory outputFactory = new WstxOutputFactory();
      writer = outputFactory.createXMLEventWriter(out);

      while (eventReader.hasNext()) {
        XMLEvent e = eventReader.nextEvent();
        // Stream it to an output stream.
        writer.add(e);

        if (!isValid) {
          if (e.getEventType() == XMLEvent.START_ELEMENT) {
            StartElement el = e.asStartElement();
            String name = el.getName().toString().toLowerCase();
            if (checkedElements.containsKey(name)) {
              checkedElements.put(name, true);
            }

            boolean all = true;
            for (Entry<String, Boolean> es : checkedElements.entrySet()) {
              if (!checkedElements.get(es.getKey())) {
                all = false;
                break;
              }
            }
            if (all) isValid = true;
          }

          if (i > 100) {
            response.sendError(
                HttpServletResponse.SC_FORBIDDEN,
                "This file does not match an RSS formatted XML file..");
            break;
          }
          i++;
        }
      }

      if (!isValid) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid RSS file.");
        return;
      }

      // Check if we are not streaming a gigantic file..
      if (out.size() > MAX_RSS_LENGTH) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "This file is to big.");
        return;
      }

      for (Entry<String, String[]> h : proxyResponse.getResponseHeaders().entrySet()) {
        for (String v : h.getValue()) {
          response.setHeader(h.getKey(), v);
        }
      }
      // We always return 200 when we get to this point.
      response.setStatus(200);
      response.setHeader("Content-Length", "" + out.size());
      // Write the cached stream to the output.
      out.writeTo(response.getOutputStream());

    } catch (XMLStreamException e) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN, "This is not a valid XML file.");
    } catch (Exception e) {
      logger.warn("Exception reading RSS feed.");
      response.sendError(HttpServletResponse.SC_FORBIDDEN, "General exception caught.");
    } finally {
      out.close();
      reader.close();
      try {
        writer.close();
      } catch (XMLStreamException e) {
        // Not much we can do?
        e.printStackTrace();
      }
    }
  }
  public void dataAvailable(String inputStreamName, StreamElement data) {
    if (inputStreamName.equalsIgnoreCase("SSTREAM")) {
      String action = (String) data.getData("STATUS");
      /** */
      String moteId = (String) data.getData("ID");
      if (moteId.toLowerCase().indexOf("mica") < 0) return;
      if (action.toLowerCase().indexOf("add") >= 0) counter++;
      if (action.toLowerCase().indexOf("remove") >= 0) counter--;
    }
    if (inputStreamName.equalsIgnoreCase("CSTREAM")) {

      BufferedImage bufferedImage = null;
      outputStream.reset();
      byte[] rawData = (byte[]) data.getData("IMAGE");
      input = new ByteArrayInputStream(rawData);
      try {
        bufferedImage = ImageIO.read(input);
      } catch (IOException e) {
        e.printStackTrace();
      }
      Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
      int size = 30;
      int locX = 0;
      int locY = 0;
      if (counter < 0) counter = 0;
      switch (counter) {
        case 0:
          graphics.setColor(Color.RED);
          break;
        case 1:
          graphics.setColor(Color.ORANGE);
          break;

        case 2:
          graphics.setColor(Color.YELLOW);
          break;

        case 3:
          graphics.setColor(Color.GREEN);
          break;
        default:
          logger.warn(
              new StringBuilder()
                  .append("Shouldn't happen.>")
                  .append(counter)
                  .append("<")
                  .toString());
      }
      graphics.fillOval(locX, locY, size, size);
      try {
        ImageIO.write(bufferedImage, "jpeg", outputStream);
        outputStream.close();

      } catch (Exception e) {
        logger.error(e.getMessage(), e);
      }

      StreamElement outputSE =
          new StreamElement(
              OUTPUT_FIELDS,
              OUTPUT_TYPES,
              new Serializable[] {outputStream.toByteArray()},
              data.getTimeStamp());
      dataProduced(outputSE);
    }
    if (logger.isInfoEnabled())
      logger.info(
          new StringBuilder()
              .append("Data received under the name: ")
              .append(inputStreamName)
              .toString());
  }
Example #19
0
  /**
   * Build, send and process a tracker announce request.
   *
   * <p>This function first builds an announce request for the specified event with all the required
   * parameters. Then, the request is made to the tracker and the response analyzed.
   *
   * <p>All registered {@link AnnounceResponseListener} objects are then fired with the decoded
   * payload.
   *
   * @param event The announce event type (can be AnnounceEvent.NONE for periodic updates).
   * @param inhibitEvents Prevent event listeners from being notified.
   */
  @Override
  public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents)
      throws AnnounceException {
    logger.info(
        "Announcing{} to tracker with {}U/{}D/{}L bytes...",
        new Object[] {
          this.formatAnnounceEvent(event),
          this.torrent.getUploaded(),
          this.torrent.getDownloaded(),
          this.torrent.getLeft()
        });

    URL target = null;
    try {
      HTTPAnnounceRequestMessage request = this.buildAnnounceRequest(event);
      target = request.buildAnnounceURL(this.tracker.toURL());
    } catch (MalformedURLException mue) {
      throw new AnnounceException("Invalid announce URL (" + mue.getMessage() + ")", mue);
    } catch (MessageValidationException mve) {
      throw new AnnounceException(
          "Announce request creation violated " + "expected protocol (" + mve.getMessage() + ")",
          mve);
    } catch (IOException ioe) {
      throw new AnnounceException(
          "Error building announce request (" + ioe.getMessage() + ")", ioe);
    }

    HttpURLConnection conn = null;
    InputStream in = null;
    try {
      conn = (HttpURLConnection) target.openConnection();
      in = conn.getInputStream();
    } catch (IOException ioe) {
      if (conn != null) {
        in = conn.getErrorStream();
      }
    }

    // At this point if the input stream is null it means we have neither a
    // response body nor an error stream from the server. No point in going
    // any further.
    if (in == null) {
      throw new AnnounceException("No response or unreachable tracker!");
    }

    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      baos.write(in);

      // Parse and handle the response
      HTTPTrackerMessage message = HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray()));
      baos.close(); // close stream
      this.handleTrackerAnnounceResponse(message, inhibitEvents);
    } catch (IOException ioe) {
      throw new AnnounceException("Error reading tracker response!", ioe);
    } catch (MessageValidationException mve) {
      throw new AnnounceException(
          "Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve);
    } finally {
      // Make sure we close everything down at the end to avoid resource
      // leaks.
      try {
        in.close();
      } catch (IOException ioe) {
        logger.warn("Problem ensuring error stream closed!", ioe);
      }

      // This means trying to close the error stream as well.
      InputStream err = conn.getErrorStream();
      if (err != null) {
        try {
          err.close();
        } catch (IOException ioe) {
          logger.warn("Problem ensuring error stream closed!", ioe);
        }
      }
    }
  }
  /**
   * Sends nested multipart response. Outer multipart wraps all the keys requested. Each key has a
   * separate multipart for the versioned values.
   */
  @Override
  public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs)
      throws Exception {

    // multiPartKeys is the outer multipart
    MimeMultipart multiPartKeys = new MimeMultipart();
    ByteArrayOutputStream keysOutputStream = new ByteArrayOutputStream();

    for (Entry<ByteArray, List<Versioned<byte[]>>> entry : versionedResponses.entrySet()) {
      ByteArray key = entry.getKey();
      String contentLocationKey =
          "/" + this.storeName + "/" + new String(Base64.encodeBase64(key.get()));

      // Create the individual body part - for each key requested
      MimeBodyPart keyBody = new MimeBodyPart();
      try {
        // Add the right headers
        keyBody.addHeader(CONTENT_TYPE, "application/octet-stream");
        keyBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
        keyBody.addHeader(CONTENT_LOCATION, contentLocationKey);
      } catch (MessagingException me) {
        logger.error("Exception while constructing key body headers", me);
        keysOutputStream.close();
        throw me;
      }
      // multiPartValues is the inner multipart
      MimeMultipart multiPartValues = new MimeMultipart();
      for (Versioned<byte[]> versionedValue : entry.getValue()) {

        byte[] responseValue = versionedValue.getValue();

        VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
        String eTag = RestUtils.getSerializedVectorClock(vectorClock);

        // Create the individual body part - for each versioned value of
        // a key
        MimeBodyPart valueBody = new MimeBodyPart();
        try {
          // Add the right headers
          valueBody.addHeader(CONTENT_TYPE, "application/octet-stream");
          valueBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
          valueBody.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);
          valueBody.setContent(responseValue, "application/octet-stream");

          multiPartValues.addBodyPart(valueBody);
        } catch (MessagingException me) {
          logger.error("Exception while constructing value body part", me);
          keysOutputStream.close();
          throw me;
        }
      }
      try {
        // Add the inner multipart as the content of the outer body part
        keyBody.setContent(multiPartValues);
        multiPartKeys.addBodyPart(keyBody);
      } catch (MessagingException me) {
        logger.error("Exception while constructing key body part", me);
        keysOutputStream.close();
        throw me;
      }
    }
    try {
      multiPartKeys.writeTo(keysOutputStream);
    } catch (Exception e) {
      logger.error("Exception while writing mutipart to output stream", e);
      throw e;
    }

    ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
    responseContent.writeBytes(keysOutputStream.toByteArray());

    // Create the Response object
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    // Set the right headers
    response.setHeader(CONTENT_TYPE, "multipart/binary");
    response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");

    // Copy the data into the payload
    response.setContent(responseContent);
    response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());

    // Write the response to the Netty Channel
    this.messageEvent.getChannel().write(response);

    if (performanceStats != null && isFromLocalZone) {
      recordStats(performanceStats, startTimeInMs, Tracked.GET_ALL);
    }

    keysOutputStream.close();
  }