Example #1
0
  protected void respondWithToken(LockToken tok, Request request, Response response) {
    response.setStatus(Status.SC_OK);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    XmlWriter writer = new XmlWriter(out);
    writer.writeXMLHeader();
    String d = WebDavProtocol.DAV_PREFIX;
    writer.open(d + ":prop  xmlns:" + d + "=\"DAV:\"");
    writer.newLine();
    writer.open(d + ":lockdiscovery");
    writer.newLine();
    writer.open(d + ":activelock");
    writer.newLine();
    lockWriterHelper.appendType(writer, tok.info.type);
    lockWriterHelper.appendScope(writer, tok.info.scope);
    lockWriterHelper.appendDepth(writer, tok.info.depth);
    lockWriterHelper.appendOwner(writer, tok.info.lockedByUser);
    lockWriterHelper.appendTimeout(writer, tok.timeout.getSeconds());
    lockWriterHelper.appendTokenId(writer, tok.tokenId);
    String url = PropFindPropertyBuilder.fixUrlForWindows(request.getAbsoluteUrl());
    lockWriterHelper.appendRoot(writer, url);
    writer.close(d + ":activelock");
    writer.close(d + ":lockdiscovery");
    writer.close(d + ":prop");
    writer.flush();

    LogUtils.debug(log, "lock response: ", out);
    response.setEntity(new ByteArrayEntity(out.toByteArray()));
    //        response.close();

  }
  private InputStream generateTxt(List<Map<String, Object>> detailList) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    OutputStreamWriter output = new OutputStreamWriter(outputStream);
    if (detailList.size() == 0) {
      output.append(NO_RECORD);
    } else {
      output.append(getText("page.accountDetail.accountNum") + ",");
      output.append(getText("page.accountDetail.accountName") + ",");
      output.append(getText("title.accountDetail.tranDate") + ",");
      output.append(getText("title.accountDetail.currency") + ",");
      output.append(getText("title.accountDetail.expenditure") + ",");
      output.append(getText("title.accountDetail.income") + ",");
      output.append(getText("title.accountDetail.balance") + "\r\n");
      for (Map<String, Object> detail : detailList) {
        output.append(detail.get("accountNo") + ",");
        output.append(new String(cstNameHost.getBytes("ISO8859_1"), "UTF8") + ",");
        output.append(formatDate((String) detail.get("transDate")) + ",");
        output.append(detail.get("currency") + ",");
        output.append(detail.get("debitamt") + ",");
        output.append(detail.get("creditamt") + ",");
        output.append(detail.get("balance") + "\r\n");
      }
    }
    output.flush();

    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    output.close();
    return inputStream;
  }
    public GhostReport ghostCalculation(int maxImageSmallDimension, int numThreads)
        throws IOException {
      File ghostOutputfile;
      byte[] imageInByte;
      String ghostBase64; // convert to base64 the image file
      GhostReport ghostReport = new GhostReport();
      GhostExtractor ghostExtractor;
      ghostExtractor = new GhostExtractor(sourceFile, maxImageSmallDimension, numThreads);
      BufferedImage ghostMap;
      for (int ghostMapInd = 0; ghostMapInd < ghostExtractor.ghostMaps.size(); ghostMapInd++) {
        ghostOutputfile =
            new File(baseFolder, "GhostOutput" + String.format("%02d", ghostMapInd) + ".png");
        ghostMap = ghostExtractor.ghostMaps.get(ghostMapInd);
        ImageIO.write(ghostMap, "png", ghostOutputfile);
        ByteArrayOutputStream ghostbytes = new ByteArrayOutputStream();
        ImageIO.write(ghostMap, "png", ghostbytes);
        imageInByte = ghostbytes.toByteArray();

        ghostReport.maps.add(ghostOutputfile.getCanonicalPath());
        ghostReport.differences = ghostExtractor.allDifferences;
        ghostReport.minQuality = ghostExtractor.qualityMin;
        ghostReport.maxQuality = ghostExtractor.qualityMax;
        ghostReport.qualities = ghostExtractor.ghostQualities;
        ghostReport.minValues = ghostExtractor.ghostMin;
        ghostReport.maxValues = ghostExtractor.ghostMax;
      }
      ghostReport.completed = true;
      return ghostReport;
    }
  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;
  }
  @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();
    }
  }
  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    /*
     * outState.putParcelable("newUID",
     * editNewUID.onSaveInstanceState()); outState.putParcelable(
     * "newEmail", editNewEmail.onSaveInstanceState());
     * outState.putParcelable( "newPass",
     * editNewPassword.onSaveInstanceState()); outState.putParcelable(
     * "repeatPass", editRetypeNewPassword.onSaveInstanceState());
     * outState.putParcelable( "newNickname",
     * editNewNickname.onSaveInstanceState());
     * outState.putParcelable("studID",
     * editStudID.onSaveInstanceState()); outState.putParcelable(
     * "realname", editRealName.onSaveInstanceState());
     * outState.putParcelable("phone", editPhone.onSaveInstanceState());
     * outState.putParcelable("captcha",
     * editCaptcha.onSaveInstanceState());
     */

    // captcha image
    ByteArrayOutputStream captchaOutStream = new ByteArrayOutputStream();
    Bitmap captchaBitmap = ((BitmapDrawable) imageRegCaptcha.getDrawable()).getBitmap();
    captchaBitmap.compress(CompressFormat.PNG, 100, captchaOutStream);

    outState.putByteArray("captchaImage", captchaOutStream.toByteArray());
  }
Example #7
0
 public static MD5InputStreamResult generateMD5Result(InputStream toEncode) {
   MD5Digest eTag = new MD5Digest();
   byte[] resBuf = new byte[eTag.getDigestSize()];
   byte[] buffer = new byte[1024];
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   long length = 0;
   int numRead = -1;
   try {
     do {
       numRead = toEncode.read(buffer);
       if (numRead > 0) {
         length += numRead;
         eTag.update(buffer, 0, numRead);
         out.write(buffer, 0, numRead);
       }
     } while (numRead != -1);
   } catch (IOException e) {
     throw new RuntimeException(e);
   } finally {
     IOUtils.closeQuietly(out);
     IOUtils.closeQuietly(toEncode);
   }
   eTag.doFinal(resBuf, 0);
   return new MD5InputStreamResult(out.toByteArray(), resBuf, length);
 }
Example #8
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 #9
0
  public static byte[] encrypt(
      InputStream plaintextInputStream, List<CipherSpec> cipherSuites, String password)
      throws IOException {
    ByteArrayOutputStream ciphertextOutputStream = new ByteArrayOutputStream();
    encrypt(plaintextInputStream, ciphertextOutputStream, cipherSuites, password);

    return ciphertextOutputStream.toByteArray();
  }
Example #10
0
  private void generateFontTexture(Font font) {
    Map<Character, CharImage> charImages = new HashMap<>();

    int imageWidth = 0;
    int imageHeight = 0;

    boolean antiAlias = false;

    /* Start at char #32, because ASCII 0 to 31 are just control codes */
    for (int i = 32; i < 256; i++) {
      if (i == 127) {
          /* ASCII 127 is the DEL control code, so we can skip it */
        continue;
      }
      char c = (char) i;
      CharImage charImage = createCharImage(font, imageWidth, c, antiAlias);
      if (charImage == null) {
        /* If char image is null that font does not contain the char */
        continue;
      }

      /* Create glyph and draw char on image */
      charImages.put(c, charImage);
      imageWidth += charImage.getWidth();
      imageHeight = Math.max(imageHeight, charImage.getHeight());
    }

    BufferedImage image =
        new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB_PRE);

    Graphics2D g = image.createGraphics();

    if (antiAlias) {
      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }
    g.setFont(font);
    g.setPaint(Color.WHITE);

    /* Create BufferedImage from all character images */
    for (Map.Entry<Character, CharImage> entry : charImages.entrySet()) {

      CharImage charImage = entry.getValue();
      Glyph glyph = charImage.getGlyph();

      g.drawString(String.valueOf(entry.getKey()), glyph.getX(), charImage.getAscent());
      glyphs.put(entry.getKey(), glyph);
    }
    g.dispose();

    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
      PngEncoder encoder = new PngEncoder();
      encoder.write(image, os);
      int textureId = TextureUtils.loadTexture(new ByteArrayInputStream(os.toByteArray()));
      fontTexture = new Texture(textureId, imageWidth, imageHeight);
    } catch (IOException e) {
      throw new IllegalStateException(e);
    }
  }
Example #11
0
  private void readFiles(InputStream csar_file) throws IOException, NotFoundException {

    ZipInputStream zipStream = new ZipInputStream(csar_file);
    ZipEntry entry;
    this.scripts.clear();
    this.folderNames.clear();
    this.template = new ByteArrayOutputStream();
    this.metadata = new ByteArrayOutputStream();

    while ((entry = zipStream.getNextEntry()) != null) {

      if (!entry.isDirectory()) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int count;
        byte[] buffer = new byte[1024];
        while ((count = zipStream.read(buffer)) != -1) {
          baos.write(buffer, 0, count);
        }

        String fileName = entry.getName();

        if (fileName.toLowerCase().endsWith(".meta")) {
          this.metadata = baos;
        } else if (fileName.toLowerCase().endsWith(".yaml")) {
          if (fileName.toLowerCase().endsWith("metadata.yaml")) {
            this.vnfMetadata = baos;
          } else {
            this.template = baos;
          }
        } else {

          Script script = new Script();
          String[] splittedName = fileName.split("/");
          if (splittedName.length > 2) {
            String scriptName = splittedName[1] + "!_!" + splittedName[splittedName.length - 1];
            folderNames.add(splittedName[1]);
            script.setName(scriptName);

          } else script.setName(splittedName[splittedName.length - 1]);

          script.setPayload(baos.toByteArray());
          this.scripts.add(script);
        }
      }
    }
    if (this.metadata == null) {
      throw new NotFoundException("CSARParser: Not found TOSCA.meta");
    }
    if (this.vnfMetadata == null) {
      throw new NotFoundException("CSARParser: Not found Metadata.yaml");
    }
    if (this.template == null) {
      throw new NotFoundException("CSARParser: Not found VNFD / NSD Template");
    }

    // zipStream.close();
  }
Example #12
0
 private static byte[] resizeImage(
     BufferedImage bufferedImage, WritebleImageFormat format, int width, int height)
     throws IOException {
   BufferedImage thumbnail =
       Scalr.resize(bufferedImage, Scalr.Method.SPEED, Scalr.Mode.FIT_EXACT, width, height);
   ByteArrayOutputStream output = new ByteArrayOutputStream();
   ImageIO.write(thumbnail, format.name(), output);
   return output.toByteArray();
 } // convertSizeToDimensions
  // 序列化
  public static byte[] serialize(Writable writable) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DataOutputStream dataOut = new DataOutputStream(out);
    // 数据输出流,允许应用程序以适当方式将基本 Java数据类型写入输出流中。然后,应用程序可以使用数据输入流将数据读入
    // 创建一个新的数据输出流,将数据写入指定基础输出流out

    writable.write(dataOut);
    dataOut.close();
    return out.toByteArray();
  }
Example #14
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 #15
0
  private static String readInputAsString(InputStream in) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buf = new byte[512];
    int nRead = 0;
    while ((nRead = in.read(buf)) >= 0) {
      baos.write(buf, 0, nRead);
    }

    return new String(baos.toByteArray(), "UTF-8");
  }
Example #16
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 #17
0
  @RequestMapping(value = "/images/captcha.jpeg")
  public ResponseEntity<byte[]> captcha(HttpSession session) throws IOException {

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    g.setColor(getRandColor(200, 250));
    g.fillRect(1, 1, width - 1, height - 1);
    g.setColor(new Color(102, 102, 102));
    g.drawRect(0, 0, width - 1, height - 1);
    g.setFont(new Font("Times New Roman", Font.PLAIN, 17));
    g.setColor(getRandColor(160, 200));

    // 画随机线
    for (int i = 0; i < 155; i++) {
      int x = RANDOM.nextInt(width - 1);
      int y = RANDOM.nextInt(height - 1);
      int xl = RANDOM.nextInt(6) + 1;
      int yl = RANDOM.nextInt(12) + 1;
      g.drawLine(x, y, x + xl, y + yl);
    }

    // 从另一方向画随机线
    for (int i = 0; i < 70; i++) {
      int x = RANDOM.nextInt(width - 1);
      int y = RANDOM.nextInt(height - 1);
      int xl = RANDOM.nextInt(12) + 1;
      int yl = RANDOM.nextInt(6) + 1;
      g.drawLine(x, y, x - xl, y - yl);
    }

    // 生成随机数,并将随机数字转换为字母
    String captchaStr = "";
    for (int i = 0; i < 6; i++) {
      int itmp = RANDOM.nextInt(26) + 65;
      char ctmp = (char) itmp;
      captchaStr += String.valueOf(ctmp);
      g.setColor(
          new Color(20 + RANDOM.nextInt(110), 20 + RANDOM.nextInt(110), 20 + RANDOM.nextInt(110)));
      g.drawString(String.valueOf(ctmp), 15 * i + 10, 16);
    }
    g.dispose();

    session.setAttribute(CAPTCHA_SESSION_ATTR_NAME, captchaStr);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ImageIO.write(image, "JPEG", out);

    try {
      return new ResponseEntity<byte[]>(out.toByteArray(), HTTP_HEADERS, HttpStatus.OK);
    } finally {
      IOUtils.closeQuietly(out);
    }
  }
Example #18
0
 public static byte[] encode(Message msg) {
   String encode = JsonMessage.encode(msg);
   ByteArrayOutputStream bytes = new ByteArrayOutputStream();
   try {
     GZIPOutputStream out = new GZIPOutputStream(bytes);
     out.write(encode.getBytes(StandardCharsets.UTF_8));
     out.finish();
   } catch (IOException e) {
     throw bomb(e);
   }
   return bytes.toByteArray();
 }
Example #19
0
  /**
   * Display information about licensing. Implemented here because this is one of the few classes in
   * milton which is generally not replaceable.
   */
  private void displayCopyrightNotice() {
    Properties validatedLicenseProps = getValidatedLicenseProperties();
    System.out.println("Initializing Milton2 Webdav library. Checking for license file...");
    if (validatedLicenseProps == null) {
      System.out.println(
          "No license file found. By using this software you are agreeing to the terms of the Affero GPL - http://www.gnu.org/licenses/agpl-3.0.html");
      System.out.println(
          "For non-FOSS/commercial usage you should obtain a commercial license. Please see http://milton.io/license for details");
      System.out.println("Copyright McEvoy Software Limited");
      try {
        URL url = new URL("http://milton.io/downloads/version.txt");
        InputStream in = url.openStream();
        if (in != null) {
          ByteArrayOutputStream bout = new ByteArrayOutputStream();
          IOUtils.copy(in, bout);
          String latestVersion = bout.toString("UTF-8").trim();
          in =
              LockHandler.class.getResourceAsStream(
                  "/META-INF/maven/io.milton/milton-server-ent/pom.properties");
          // in = LockHandler.class.getResourceAsStream("/test/pom.properties");
          if (in != null) {
            Properties props = new Properties();
            props.load(in);
            in.close();
            String localVersion = props.getProperty("version");
            if (localVersion != null) {
              localVersion = localVersion.trim();
              if (!localVersion.equals(latestVersion)) {
                System.out.println(
                    "A new version of Milton2 Webdav has been released: "
                        + latestVersion
                        + " - see http://milton.io/downloads");
              } else {
                System.out.println("using latest");
              }
            } else {
              System.out.println("no version prop");
            }
          } else {
            System.out.println("no meta information, can't check latest version");
          }
        }
      } catch (Throwable e) {

      }

    } else {
      System.out.println("Milton2 license found:");
      for (String key : validatedLicenseProps.stringPropertyNames()) {
        System.out.println(key + ": " + validatedLicenseProps.getProperty(key));
      }
    }
  }
Example #20
0
  public static ByteBuffer readChannelToBuffer(ReadableByteChannel channel) throws NetIOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
      logger.debug(
          "bytes read from channel: " + IOUtils.copy(Channels.newInputStream(channel), bos));
    } catch (IOException e) {
      throw new NetIOException(e);
    }

    return ByteBuffer.wrap(ArrayUtils.subarray(bos.toByteArray(), 0, bos.size()));
  }
Example #21
0
  /**
   * Converts the provided object to a byte array that can be written to the buffer.
   *
   * @param obj The object to be converted to a byte array.
   * @return The object's byte array representation.
   */
  public static byte[] convertToByteArray(Object obj) {
    final ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();

    try {
      final ObjectOutputStream objectOutput = new ObjectOutputStream(byteOutput);
      objectOutput.writeObject(obj);
      objectOutput.close();
    } catch (final IOException e) {
      e.printStackTrace();
    }

    return byteOutput.toByteArray();
  }
Example #22
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();
  }
Example #23
0
 public void sample(InputStream in) {
   Logger.debug(this, "outputting sample");
   try {
     ByteArrayOutputStream out = FileUtils.readIn(in);
     writer.write(out.toString());
   } catch (FileNotFoundException ex) {
     Logger.error(this, "", ex);
   } catch (IOException ex) {
     Logger.error(this, "", ex);
   } finally {
     FileUtils.close(in);
   }
 }
  @Override
  public TemplateRef copyTemplate(TemplateRef ref) {
    // get complete template and change name
    Template template = dao.getTemplate(ref);
    template.setName(compileCopyOfName(ref.getName()));

    // export existing template to buffer
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    dao.exportTemplate(template, buffer);

    // import from buffer
    return dao.importTemplate(new ByteArrayInputStream(buffer.toByteArray()));
  }
Example #25
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);
    }
  }
  public static ScalingReport scale(byte[] fileData, int width, int height)
      throws ApplicationException {
    ByteArrayInputStream in = new ByteArrayInputStream(fileData);
    ScalingReport imagedata = new ScalingReport();
    try {

      BufferedImage img = ImageIO.read(in);

      if (img.getHeight() > img.getWidth()) {
        if (img.getHeight() > height) {
          width = (height * img.getWidth()) / img.getHeight();
          Image scaledImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
          BufferedImage imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
          imageBuff.getGraphics().drawImage(scaledImage, 0, 0, new Color(0, 0, 0), null);

          ByteArrayOutputStream buffer = new ByteArrayOutputStream();
          ImageIO.write(imageBuff, "jpg", buffer);
          imagedata.scaledByte = buffer.toByteArray();
          imagedata.width = width;
          imagedata.height = height;
        } else {
          imagedata.scaledByte = fileData;
          imagedata.width = img.getWidth();
          imagedata.height = img.getHeight();
        }
      } else {
        if (img.getWidth() > width) {
          height = (width * img.getHeight()) / img.getWidth();

          Image scaledImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
          BufferedImage imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
          imageBuff.getGraphics().drawImage(scaledImage, 0, 0, new Color(0, 0, 0), null);

          ByteArrayOutputStream buffer = new ByteArrayOutputStream();

          ImageIO.write(imageBuff, "jpg", buffer);
          imagedata.scaledByte = buffer.toByteArray();
          imagedata.width = width;
          imagedata.height = height;
        } else {
          imagedata.scaledByte = fileData;
          imagedata.width = img.getWidth();
          imagedata.height = img.getHeight();
        }
      }
      return imagedata;
    } catch (IOException e) {
      throw new ApplicationException("IOException in scale", null);
    }
  }
  private void checkSize() throws IOException {
    if (log.isTraceEnabled()) {
      log.trace("checkSize: " + size);
    }
    if (tempMemoryBuffer == null) return;

    if (tempMemoryBuffer.size() < maxMemorySize) return;

    tempFile = File.createTempFile("" + System.currentTimeMillis(), ".buffer");
    fout = new FileOutputStream(tempFile);
    bufOut = new BufferedOutputStream(fout);
    bufOut.write(tempMemoryBuffer.toByteArray());
    tempMemoryBuffer = null;
  }
Example #28
0
  void writeAttachmentBody(MessageContext context, OutMessage message) throws XFireException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    writeWithoutAttachments(context, message, bos);

    Attachments atts = message.getAttachments();

    ByteDataSource ds = new ByteDataSource(bos.toByteArray());
    ds.setContentType(getSoapMimeType(message));
    DataHandler dh = new DataHandler(ds);

    SimpleAttachment att = new SimpleAttachment("soap-message.xml", dh);

    atts.setSoapMessage(att);
  }
Example #29
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;
  }
 public void writeDataToStream() {
   try {
     IOUtils.copy(new ByteArrayInputStream(bos.toByteArray()), servletOutputStream);
   } catch (Exception e) {
     throw new RuntimeException("Cannot copy data", e);
   }
 }