Example #1
0
 // convert bitmap to base64
 public static String bitmapToBase64(Bitmap bitmap) {
   String result = null;
   ByteArrayOutputStream baos = null;
   try {
     if (bitmap != null) {
       baos = new ByteArrayOutputStream();
       bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
       baos.flush();
       baos.close();
       byte[] bitmapBytes = baos.toByteArray();
       result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
     }
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (baos != null) {
         baos.flush();
         baos.close();
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return result;
 }
Example #2
0
  /**
   * 将图片转化为Base64的格式
   *
   * @param imgPath 图片的路径
   * @return 返回图片的String类型
   */
  public static String imageToBase64(String imgPath) {
    Bitmap bitmap = null;
    if (imgPath != null && imgPath.length() > 0) {
      bitmap = readBitmap(imgPath);
    }
    if (bitmap == null) {
      return null;
    }
    ByteArrayOutputStream out = null;
    try {
      out = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

      out.flush();
      out.close();

      byte[] imgBytes = out.toByteArray();
      return Base64.encodeToString(imgBytes, Base64.DEFAULT);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      try {
        out.flush();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Example #3
0
  /**
   * Writes to the designated output stream the DER encoding of the current contents of this
   * instance.
   *
   * @param out the destination output stream.
   * @throws IOException if an I/O related exception occurs during the process.
   * @throws CRLException if an exception occurs while encoding the certificate revocation lists
   *     associated with this instance.
   * @throws CertificateEncodingException if an exception occurs while encoding the certificate
   *     chains associated with this instance.
   */
  public void encode(OutputStream out)
      throws IOException, CRLException, CertificateEncodingException {
    DERValue derVersion = new DERValue(DER.INTEGER, version);

    DERValue derDigestAlgorithms = new DERValue(DER.CONSTRUCTED | DER.SET, digestAlgorithms);

    DERValue derContentType = new DERValue(DER.OBJECT_IDENTIFIER, PKCS7Data.PKCS7_DATA);
    ArrayList contentInfo = new ArrayList(2);
    contentInfo.add(derContentType);
    if (content == null) contentInfo.add(new DERValue(DER.NULL, null));
    else contentInfo.add(content);

    DERValue derContentInfo = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, contentInfo);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
    for (int i = 0; i < certificates.length; i++) baos.write(certificates[i].getEncoded());

    baos.flush();
    byte[] b = baos.toByteArray();
    DERValue derExtendedCertificatesAndCertificates =
        new DERValue(DER.CONSTRUCTED | DER.CONTEXT | 0, b.length, b, null);

    DERValue derCertificateRevocationLists = null;
    if (crls != null && crls.length > 0) {
      baos.reset();
      for (int i = 0; i < crls.length; i++) baos.write(((X509CRL) crls[i]).getEncoded());

      baos.flush();
      byte[] b2 = baos.toByteArray();
      derCertificateRevocationLists =
          new DERValue(DER.CONSTRUCTED | DER.CONTEXT | 1, b2.length, b2, null);
    }

    baos.reset();
    for (Iterator it = signerInfos.iterator(); it.hasNext(); ) {
      SignerInfo signerInfo = (SignerInfo) it.next();
      signerInfo.encode(baos);
    }
    baos.flush();
    byte[] b3 = baos.toByteArray();
    DERValue derSignerInfos = new DERValue(DER.CONSTRUCTED | DER.SET, b3.length, b3, null);

    ArrayList signedData = new ArrayList(6);
    signedData.add(derVersion);
    signedData.add(derDigestAlgorithms);
    signedData.add(derContentInfo);
    signedData.add(derExtendedCertificatesAndCertificates);
    if (derCertificateRevocationLists != null) signedData.add(derCertificateRevocationLists);

    signedData.add(derSignerInfos);
    DERValue derSignedData = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, signedData);
    // now the outer contents
    ArrayList outer = new ArrayList(3);
    outer.add(new DERValue(DER.OBJECT_IDENTIFIER, PKCS7_SIGNED_DATA));
    outer.add(new DERValue(DER.CONTEXT | 0, null));
    outer.add(derSignedData);
    DERValue derOuter = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, outer);

    DERWriter.write(out, derOuter);
  }
Example #4
0
  @Test
  public void serializeStringAsAsciiBytes() throws Exception {
    final String data = "abc123";
    final Charset asciiCharset = Charset.forName("US-ASCII");
    final int loops = 1000;
    ByteArrayOutputStream out = new ByteArrayOutputStream(10);
    byte[] expecteds = new byte[] {'a', 'b', 'c', '1', '2', '3'};
    long start = 0;

    start = System.nanoTime();
    for (int i = 0; i < loops; i++) {
      AsciiUtils.writeStringAsAsciiBytes(data, out);
      out.flush();
      assertArrayEquals(expecteds, out.toByteArray());
      out.reset();
    }
    System.out.println(
        "AsciiUtils#writeStringAsAsciiBytes() elapsed time: "
            + ((System.nanoTime() - start) / 1000000)
            + " ms");

    start = System.nanoTime();
    for (int i = 0; i < loops; i++) {
      out.write(data.getBytes(asciiCharset));
      out.flush();
      assertArrayEquals(expecteds, out.toByteArray());
      out.reset();
    }
    System.out.println(
        "String#getBytes() elapsed time: " + ((System.nanoTime() - start) / 1000000) + " ms");
  }
  /**
   * Save all nodes and edges in GraphColor format.
   *
   * @param gra
   * @param outFileName must end with ".col"
   */
  public void saveAGG2ColorGraph(GraGra gra, String outFileName) {
    if (outputFileName.endsWith(".col")) {

      final List<Arc> edges = new Vector<Arc>();
      edges.addAll(gragra.getGraph(this.indx).getArcsSet());

      final List<Node> nodes = new Vector<Node>();
      nodes.addAll(gragra.getGraph(this.indx).getNodesSet());

      final File f = new File(outputFileName);
      ByteArrayOutputStream baOut = null;
      FileOutputStream fos = null;
      try {
        fos = new FileOutputStream(f);

        // write comment
        baOut = new ByteArrayOutputStream();
        String comment = "c AGG (.ggx) to Color Graph (.col)\n";
        // put in out stream and file
        baOut.write(comment.getBytes());
        fos.write(baOut.toByteArray());
        baOut.flush();

        // write problem
        baOut = new ByteArrayOutputStream();
        String problem = "p edge ";
        problem = problem.concat(String.valueOf(nodes.size()));
        problem = problem.concat(" ");
        problem = problem.concat(String.valueOf(edges.size()));
        problem = problem.concat("\n");
        // put in out stream and file
        baOut.write(problem.getBytes());
        fos.write(baOut.toByteArray());
        baOut.flush();

        for (int i = 0; i < edges.size(); i++) {
          final Arc a = edges.get(i);

          int src = nodes.indexOf(a.getSource()) + 1;
          int tar = nodes.indexOf(a.getTarget()) + 1;

          String str = "e ";
          str = str.concat(String.valueOf(src)).concat(" ");
          str = str.concat(String.valueOf(tar).concat("\n"));

          // write edge line
          baOut = new ByteArrayOutputStream();
          baOut.write(str.getBytes());
          fos.write(baOut.toByteArray());
          baOut.flush();
        }
      } catch (IOException e) {
      }
    }
  }
Example #6
0
  private Icon makeIcon(final String gifFile) throws IOException {
    /* Copy resource into a byte array.  This is
     * necessary because several browsers consider
     * Class.getResource a security risk because it
     * can be used to load additional classes.
     * Class.getResourceAsStream just returns raw
     * bytes, which we can convert to an image.
     */
    InputStream resource = MyImageView.class.getResourceAsStream(gifFile);

    if (resource == null) {
      // MMClient.mwClientLog.clientErrLog(MyImageView.class.getName() + "/" +gifFile + " not
      // found.");
      return null;
    }
    BufferedInputStream in = new BufferedInputStream(resource);
    ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
    byte[] buffer = new byte[1024];
    int n;
    while ((n = in.read(buffer)) > 0) {
      out.write(buffer, 0, n);
    }
    in.close();
    out.flush();

    buffer = out.toByteArray();
    if (buffer.length == 0) {
      CampaignData.mwlog.errLog("warning: " + gifFile + " is zero-length");
      return null;
    }
    return new ImageIcon(buffer);
  }
  private static Bitmap getCaptchaImage(HttpClient client, String captchaId)
      throws ClientProtocolException, IOException {
    final HttpGet request = new HttpGet(String.format(CAPTCHA_IMAGE, captchaId));
    request.addHeader("User-Agent", USER_AGENT);
    request.addHeader("Referer", REFERER);
    request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

    final HttpResponse response = client.execute(request);

    final HttpEntity entity = response.getEntity();
    final InputStream in = entity.getContent();

    int next;
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while ((next = in.read()) != -1) {
      bos.write(next);
    }
    bos.flush();
    byte[] result = bos.toByteArray();

    bos.close();

    entity.consumeContent();
    return BitmapFactory.decodeByteArray(result, 0, result.length);
  }
Example #8
0
  public void run() {

    byte[] tmp = new byte[10000];
    int read;
    try {
      FileInputStream fis = new FileInputStream(fileToSend.getFile());

      read = fis.read(tmp);
      while (read != -1) {
        baos.write(tmp, 0, read);
        read = fis.read(tmp);
        System.out.println(read);
      }
      fis.close();
      baos.writeTo(sWriter);
      sWriter.flush();
      baos.flush();
      baos.close();
      System.out.println("fileSent");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {

      this.closeSocket();
    }
  }
  public static String serializeCar(Car car) {
    ObjectOutputStream oos = null;
    Base64OutputStream b64 = null;
    try {
      ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
      oos = new ObjectOutputStream(byteArrayOut);
      oos.writeObject(car);
      oos.flush();

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      b64 = new Base64OutputStream(out, Base64.DEFAULT);
      b64.write(byteArrayOut.toByteArray());
      b64.flush();
      b64.close();
      out.flush();
      out.close();

      String result = new String(out.toByteArray());
      return result;
    } catch (IOException e) {
      logger.warn(e.getMessage(), e);
    } finally {
      if (oos != null)
        try {
          b64.close();
          oos.close();
        } catch (IOException e) {
          logger.warn(e.getMessage(), e);
        }
    }
    return null;
  }
 /**
  * Serializes the passed object to a byte array, returning a zero byte array if the passed object
  * is null, or fails serialization
  *
  * @param arg The object to serialize
  * @return the serialized object
  */
 public static byte[] serializeNoCompress(Object arg) {
   if (arg == null) return new byte[] {};
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   ObjectOutputStream oos = null;
   try {
     oos = new ObjectOutputStream(baos);
     oos.writeObject(arg);
     oos.flush();
     baos.flush();
     return baos.toByteArray();
   } catch (Exception ex) {
     return new byte[] {};
   } finally {
     try {
       baos.close();
     } catch (Exception ex) {
       /* No Op */
     }
     if (oos != null)
       try {
         oos.close();
       } catch (Exception ex) {
         /* No Op */
       }
   }
 }
Example #11
0
  public byte[] read() {
    if (socket != null && !isClose()) {
      try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ins = socket.getInputStream();
        byte[] b = new byte[bufferSize];
        int fb = ins.read();
        bout.write(fb);
        while ((ins.available()) > 0) {
          int n = ins.read(b);
          bout.write(b, 0, n);
        }
        bout.flush();
        return bout.toByteArray();
      } catch (IOException e) {

        log.info("socket 读取数据出现异常");
        if (ins != null) {
          try {
            ins.close();
          } catch (IOException ie) {
            ie.printStackTrace();
          }
        }
        e.printStackTrace();
      }
    }
    return null;
  }
 /**
  * reads the content of an existing file using the current domain
  *
  * @param domain The namespace used to identify the application domain (1st level directory) to
  *     use
  * @param path The path relative to the domain for the file
  * @param offset the offset from the beginning of the file.
  * @param len The length of the block in bytes
  * @return The contents of the file
  */
 public byte[] readByteFromFile(String path, long offset, int len)
     throws EOFException, FileAccessException {
   try {
     if (_isLocal) {
       File tmpFile = new File(_rootFile.getCanonicalPath() + File.separatorChar + path);
       if (tmpFile.isFile()) {
         RandomAccessFile raf = new RandomAccessFile(tmpFile, "r");
         byte[] buffer = new byte[len];
         raf.seek(offset);
         int totalByteRead = 0;
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         int result = 0;
         while (totalByteRead < len && raf.getFilePointer() < raf.length()) {
           result = raf.read(buffer, 0, (len - totalByteRead));
           if (result != -1) {
             out.write(buffer, 0, result);
             totalByteRead += result;
           } else if (totalByteRead == 0) throw new EOFException("End of file reached!");
           else break;
         }
         raf.close();
         out.flush();
         out.close();
         return out.toByteArray();
       } else throw new FileAccessException("Path is not a file");
     } else return _remote.readByteFromFile(_domain, path, offset, len);
   } catch (EOFException eofe) {
     throw eofe;
   } catch (FileAccessException fae) {
     throw fae;
   } catch (Exception e) {
     throw new FileAccessException(e);
   }
 }
  public static byte[] loadBytes(InputStream is) throws JRException {
    ByteArrayOutputStream baos = null;

    try {
      baos = new ByteArrayOutputStream();

      byte[] bytes = new byte[10000];
      int ln = 0;
      while ((ln = is.read(bytes)) > 0) {
        baos.write(bytes, 0, ln);
      }

      baos.flush();
    } catch (IOException e) {
      throw new JRException("Error loading byte data from input stream.", e);
    } finally {
      if (baos != null) {
        try {
          baos.close();
        } catch (IOException e) {
        }
      }
    }

    return baos.toByteArray();
  }
  public byte[] picdecolour(String picid, String type, boolean profPic) {
    try {
      BufferedImage BI = ImageIO.read(new File("/var/tmp/instagrAndrew/" + picid));
      BufferedImage processed = doTints(BI, this.tintValue, this.greyValue, false, profPic);

      if (this.contrastValue != 0f) {
        processed = doContrast(processed, this.contrastValue);
      }

      if (this.rotateValue != null) {
        processed = rotate(processed, rotateValue, null);
      }
      if (this.flipValue != null) {
        processed = rotate(processed, flipValue, null);
      }

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ImageIO.write(processed, type, baos);
      baos.flush();
      byte[] imageInByte = baos.toByteArray();
      baos.close();
      return imageInByte;
    } catch (IOException et) {

    }
    return null;
  }
Example #15
0
  @Override
  public byte[] packLog(long index, int itemsToPack) {
    if (index < this.startIndex.get() || index >= this.nextIndex.get()) {
      throw new IllegalArgumentException("index out of range");
    }

    try {
      ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
      GZIPOutputStream gzipStream = new GZIPOutputStream(memoryStream);
      PreparedStatement ps = this.connection.prepareStatement(SELECT_RANGE_SQL);
      ps.setLong(1, index);
      ps.setLong(2, index + itemsToPack);
      ResultSet rs = ps.executeQuery();
      while (rs.next()) {
        byte[] value = rs.getBytes(4);
        int size = value.length + Long.BYTES + 1 + Integer.BYTES;
        ByteBuffer buffer = ByteBuffer.allocate(size);
        buffer.putInt(size);
        buffer.putLong(rs.getLong(2));
        buffer.put(rs.getByte(3));
        buffer.put(value);
        gzipStream.write(buffer.array());
      }

      rs.close();
      gzipStream.flush();
      memoryStream.flush();
      gzipStream.close();
      return memoryStream.toByteArray();
    } catch (Throwable error) {
      this.logger.error("failed to pack log entries", error);
      throw new RuntimeException("log store error", error);
    }
  }
  /**
   * Test of printHelp, of class CliParser.
   *
   * @throws Exception thrown when an excpetion occurs.
   */
  @Test
  public void testParse_printHelp() throws Exception {
    System.out.println("printHelp");

    PrintStream out = System.out;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    System.setOut(new PrintStream(baos));

    CliParser instance = new CliParser();
    String[] args = {"-h"};
    instance.parse(args);
    instance.printHelp();
    args[0] = "-ah";
    instance.parse(args);
    instance.printHelp();
    try {
      baos.flush();
      String text = (new String(baos.toByteArray()));
      String[] lines = text.split(System.getProperty("line.separator"));
      assertTrue(lines[0].startsWith("usage: "));
      assertTrue((lines.length > 2));
    } catch (IOException ex) {
      System.setOut(out);
      fail("CliParser.printVersionInfo did not write anything to system.out.");
    } finally {
      System.setOut(out);
    }
  }
Example #17
0
  protected void assertMatchExample(Syntax.Builder builder, String type, String exampleName)
      throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    String exampleContent = fetch(type, exampleName);
    String expectedContent = fetch(type, expectedName(exampleName));

    builder.output(out);
    builder.encoderType(ASSERT_ENCODER);
    builder.scanner(Scanner.Factory.byFileName(exampleName));
    builder.execute(exampleContent);
    out.flush();

    String result = new String(out.toByteArray());

    String[] resultLines = result.split("\n");
    String[] expectedLines = expectedContent.split("\n");

    for (int i = 0; i < resultLines.length; i++) {
      String s = resultLines[i];
      String t = expectedLines[i];

      if (!s.equals(t)) {
        System.out.println("--------------------------->" + (i + 1));
        System.out.println(exampleContent.split("\n")[i]);
        System.out.println("---------------------------");
        System.out.println("> " + s);
        System.out.println("< " + t);
        System.out.println("---------------------------");
        Assert.assertEquals("verify line: " + (i + 1), t, s);
      }
    }
    Assert.assertEquals(expectedContent, result);
  }
Example #18
0
 public static byte[] readBinary(File file) {
   FileInputStream fis = null;
   ByteArrayOutputStream baos = null;
   try {
     fis = new FileInputStream(file);
     baos = new ByteArrayOutputStream();
     byte[] bs = new byte[1024];
     int readLen = -1;
     while ((readLen = fis.read(bs)) != -1) {
       baos.write(bs, 0, readLen);
     }
     baos.flush();
     return baos.toByteArray();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (fis != null) {
       try {
         fis.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
     if (baos != null) {
       try {
         baos.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   return null;
 }
 /**
  * 将InputStream转为byte[]
  *
  * @param is
  * @return
  */
 public static final byte[] getDataSource(InputStream is) {
   if (is == null) {
     return null;
   }
   ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
   byte[] bytes = new byte[8192];
   try {
     int read;
     while ((read = is.read(bytes)) >= 0) {
       byteArrayOutputStream.write(bytes, 0, read);
     }
     bytes = byteArrayOutputStream.toByteArray();
   } catch (IOException e) {
     return null;
   } finally {
     try {
       if (byteArrayOutputStream != null) {
         byteArrayOutputStream.flush();
         byteArrayOutputStream = null;
       }
       if (is != null) {
         is.close();
         is = null;
       }
     } catch (IOException e) {
     }
   }
   return bytes;
 }
  protected Class<?> loadClass(String className, File file) throws IOException {
    FileInputStream fis = null;
    ByteArrayOutputStream baos = null;

    byte[] bytecodes = new byte[10000];
    int ln = 0;

    try {
      fis = new FileInputStream(file);
      baos = new ByteArrayOutputStream();

      while ((ln = fis.read(bytecodes)) > 0) {
        baos.write(bytecodes, 0, ln);
      }

      baos.flush();
    } finally {
      if (baos != null) {
        try {
          baos.close();
        } catch (IOException e) {
        }
      }

      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
        }
      }
    }

    return loadClass(className, baos.toByteArray());
  }
Example #21
0
 /**
  * 发送GET请求
  *
  * @param link 链接
  * @param charset 编码
  */
 public static String doGet(String link) {
   HttpURLConnection conn = null;
   try {
     URL url = new URL(link);
     conn = (HttpURLConnection) url.openConnection();
     conn.setRequestMethod("GET");
     conn.setRequestProperty("User-Agent", "Mozilla/5.0");
     BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     byte[] buf = new byte[1024];
     for (int i = 0; (i = in.read(buf)) > 0; ) {
       out.write(buf, 0, i);
     }
     out.flush();
     out.close();
     String s = new String(out.toByteArray(), "UTF-8");
     return s;
   } catch (Exception e) {
     throw new RuntimeException(e.getMessage(), e);
   } finally {
     if (conn != null) {
       conn.disconnect();
     }
   }
 }
Example #22
0
 public StringDataSource(String content, String contentType) throws IOException {
   this.contentType = contentType;
   contentArray = new ByteArrayOutputStream();
   contentArray.write(content.getBytes("iso-8859-1"));
   contentArray.flush();
   contentArray.close();
 }
  protected void cacheBufferedImage(
      Element imageElement, BufferedImage buf, SVGGeneratorContext generatorContext)
      throws SVGGraphics2DIOException {

    ByteArrayOutputStream os;

    if (generatorContext == null) throw new SVGGraphics2DRuntimeException(ERR_CONTEXT_NULL);

    try {
      os = new ByteArrayOutputStream();
      // encode the image in memory
      encodeImage(buf, os);
      os.flush();
      os.close();
    } catch (IOException e) {
      // should not happen since we do in-memory processing
      throw new SVGGraphics2DIOException(ERR_UNEXPECTED, e);
    }

    // ask the cacher for a reference
    String ref = imageCacher.lookup(os, buf.getWidth(), buf.getHeight(), generatorContext);

    // set the URL
    imageElement.setAttributeNS(XLINK_NAMESPACE_URI, XLINK_HREF_QNAME, getRefPrefix() + ref);
  }
Example #24
0
  /**
   * Handles the write serialization of the Package. Patterns in Rules may reference generated data
   * which cannot be serialized by default methods. The Package uses PackageCompilationData to hold
   * a reference to the generated bytecode. The generated bytecode must be restored before any
   * Rules.
   *
   * @param stream out the stream to write the object to; should be an instance of
   *     DroolsObjectOutputStream or OutputStream
   */
  public void writeExternal(ObjectOutput stream) throws IOException {
    boolean isDroolsStream = stream instanceof DroolsObjectOutputStream;
    ByteArrayOutputStream bytes = null;
    ObjectOutput out;

    if (isDroolsStream) {
      out = stream;
    } else {
      bytes = new ByteArrayOutputStream();
      out = new DroolsObjectOutputStream(bytes);
    }
    out.writeObject(this.dialectRuntimeRegistry);
    out.writeObject(this.typeDeclarations);
    out.writeObject(this.name);
    out.writeObject(this.imports);
    out.writeObject(this.staticImports);
    out.writeObject(this.functions);
    out.writeObject(this.accumulateFunctions);
    out.writeObject(this.factTemplates);
    out.writeObject(this.ruleFlows);
    out.writeObject(this.globals);
    out.writeBoolean(this.valid);
    out.writeBoolean(this.needStreamMode);
    out.writeObject(this.rules);
    out.writeObject(this.classFieldAccessorStore);
    out.writeObject(this.entryPointsIds);
    out.writeObject(this.windowDeclarations);
    out.writeObject(this.traitRegistry);
    // writing the whole stream as a byte array
    if (!isDroolsStream) {
      bytes.flush();
      bytes.close();
      stream.writeObject(bytes.toByteArray());
    }
  }
Example #25
0
 /**
  * 根据文件以byte[]形式返回文件的数据
  *
  * @param file
  * @return
  */
 public static byte[] getFileData(File file) {
   FileInputStream in = null;
   ByteArrayOutputStream out = null;
   try {
     in = new FileInputStream(file);
     out = new ByteArrayOutputStream(BUFFER_SIZE);
     int byteCount = 0;
     byte[] buffer = new byte[BUFFER_SIZE];
     int bytesRead = -1;
     while ((bytesRead = in.read(buffer)) != -1) {
       out.write(buffer, 0, bytesRead);
       byteCount += bytesRead;
     }
     out.flush();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (in != null) in.close();
       if (out != null) out.close();
     } catch (IOException ex) {
       ex.printStackTrace();
     }
   }
   return out.toByteArray();
 }
 public void testInputStream() throws Exception {
   ByteArrayDataSource bads = new ByteArrayDataSource(EXAMPLE_XML.getBytes(), "text/xml", "name");
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   out.write(bads.getBytes());
   out.flush();
   assertEquals("XML", out.toString(), EXAMPLE_XML);
 }
Example #27
0
 /**
  * <根据URL下载图片,并保存到本地> <功能详细描述>
  *
  * @param imageURL
  * @param context
  * @return
  * @see [类、类#方法、类#成员]
  */
 public static Bitmap loadImageFromUrl(String imageURL, File file, Context context) {
   Bitmap bitmap = null;
   try {
     URL url = new URL(imageURL);
     HttpURLConnection con = (HttpURLConnection) url.openConnection();
     con.setDoInput(true);
     con.connect();
     if (con.getResponseCode() == 200) {
       InputStream inputStream = con.getInputStream();
       FileUtil.deleteDirectory(FileSystemManager.getUserHeadPath(context, Global.getUserId()));
       ByteArrayOutputStream OutputStream = new ByteArrayOutputStream();
       FileOutputStream out = new FileOutputStream(file.getPath());
       byte buf[] = new byte[1024 * 20];
       int len = 0;
       while ((len = inputStream.read(buf)) != -1) {
         OutputStream.write(buf, 0, len);
       }
       OutputStream.flush();
       OutputStream.close();
       inputStream.close();
       out.write(OutputStream.toByteArray());
       out.close();
       BitmapFactory.Options imageOptions = new BitmapFactory.Options();
       imageOptions.inPreferredConfig = Bitmap.Config.RGB_565;
       imageOptions.inPurgeable = true;
       imageOptions.inInputShareable = true;
       bitmap = BitmapFactory.decodeFile(file.getPath(), imageOptions);
     }
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return bitmap;
 }
  @Test
  public void shouldRetrieveAdminToken() throws IOException, JAXBException {

    JAXBContext coreJaxbContext =
        JAXBContext.newInstance(
            org.openstack.docs.identity.api.v2.ObjectFactory.class,
            com.rackspace.docs.identity.api.ext.rax_auth.v1.ObjectFactory.class);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    AuthenticateResponse response = getServiceResponse();
    ObjectFactory factory = new ObjectFactory();
    Marshaller marshaller = coreJaxbContext.createMarshaller();
    marshaller.marshal(factory.createAccess(response), baos);

    baos.flush();
    baos.close();

    InputStream is = new ByteArrayInputStream(baos.toByteArray());
    ServiceClientResponse resp = new ServiceClientResponse(200, is);
    when(client.post(
            anyString(),
            anyString(),
            anyMapOf(String.class, String.class),
            anyString(),
            eq(MediaType.APPLICATION_XML_TYPE)))
        .thenReturn(resp);
    provider = new AdminTokenProvider(client, "authUrl", "user", "pass");

    String adminToken = provider.getAdminToken();
    assertTrue(adminToken.equals("tokenid"));
  }
Example #29
0
  public static String zip(String param) {
    try {
      byte[] unzip = param.getBytes("UTF-8");

      ByteArrayInputStream bif = new ByteArrayInputStream(unzip);
      ByteArrayOutputStream zipbof = new ByteArrayOutputStream();
      //			DeflaterOutputStream dos = new DeflaterOutputStream(zipbof);
      GZIPOutputStream gos = new GZIPOutputStream(zipbof);
      int position = 0;

      for (int read_byte = 0; (read_byte = bif.read()) != -1; position++) {
        //				dos.write(read_byte);
        gos.write(read_byte);
      }

      //			dos.finish();
      gos.finish();
      zipbof.flush();

      byte[] zipbyteArray = zipbof.toByteArray();
      //			return new sun.misc.BASE64Encoder().encode(zipbyteArray);
      return Base64.encodeBase64String(zipbyteArray);
    } catch (Exception ex) {
      return null;
    }
  }
Example #30
0
 /**
  * Create this dialog's drop-down list component.
  *
  * @param parent the parent composite
  * @return the drop-down list component
  */
 protected void createDropDownText(Composite parent) {
   // create the list
   text = new Text(parent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
   // print the stacktrace in the text field
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     PrintStream ps = new PrintStream(baos);
     detail.printStackTrace(ps);
     if ((detail instanceof SWTError) && (((SWTError) detail).throwable != null)) {
       ps.println("\n*** Stack trace of contained exception ***"); // $NON-NLS-1$
       ((SWTError) detail).throwable.printStackTrace(ps);
     } else if ((detail instanceof SWTException) && (((SWTException) detail).throwable != null)) {
       ps.println("\n*** Stack trace of contained exception ***"); // $NON-NLS-1$
       ((SWTException) detail).throwable.printStackTrace(ps);
     }
     ps.flush();
     baos.flush();
     text.setText(baos.toString());
   } catch (IOException e) {
   }
   GridData data =
       new GridData(
           GridData.HORIZONTAL_ALIGN_FILL
               | GridData.GRAB_HORIZONTAL
               | GridData.VERTICAL_ALIGN_FILL
               | GridData.GRAB_VERTICAL);
   data.heightHint = text.getLineHeight() * TEXT_LINE_COUNT;
   text.setLayoutData(data);
 }