Пример #1
0
 /**
  * 压缩Cookie
  *
  * @param cookie Cookie
  * @param response HttpServletResponse
  */
 public static final void compressCookie(Cookie cookie, HttpServletResponse response) {
   if (new NullChecker().add(cookie).add(response).hasNull()) {
     return;
   }
   String value = cookie.getValue();
   if (StringUtils.isEmpty(value)) {
     return;
   }
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   DeflaterOutputStream dos = new DeflaterOutputStream(bos);
   try {
     dos.write(value.getBytes());
     dos.close();
     String compress = new BASE64Encoder().encode(bos.toByteArray());
     bos.close();
     response.addCookie(new Cookie("compress", compress));
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (ObjectUtils.isNotNull(dos)) {
       try {
         dos.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
     if (ObjectUtils.isNotNull(bos)) {
       try {
         bos.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
 /**
  * 获取Raw下文本内容
  *
  * @param context
  * @param rawId
  * @return
  */
 public static final String getStringFormRaw(Context context, int rawId) {
   ByteArrayOutputStream baos = null;
   InputStream in = context.getResources().openRawResource(rawId);
   try {
     baos = new ByteArrayOutputStream();
     byte[] buffer = new byte[1024];
     int len = 0;
     while ((len = in.read(buffer)) != -1) {
       baos.write(buffer, 0, len);
     }
     baos.close();
     return baos.toString();
   } catch (Exception e) {
     e.printStackTrace();
     return "";
   } finally {
     if (baos != null) {
       try {
         baos.close();
         baos = null;
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
Пример #3
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();
      }
    }
  }
Пример #4
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;
 }
Пример #5
0
  private boolean saveToPath(File file, Bitmap bitmap) {
    boolean isSuccess = true;
    try {
      if (file.exists()) return true;

      //			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
      byte[] imageInByte = stream.toByteArray();
      long length = imageInByte.length;
      com.netease.vendor.util.log.LogUtil.vendor("length=" + length);
      if (MIN_IMAGE_SIZE >= length) {
        stream.close();
        return false;
      }
      FileOutputStream fos = new FileOutputStream(file);
      stream.writeTo(fos);
      fos.flush();
      stream.close();
      fos.close();
    } catch (Exception e) {
      e.printStackTrace();
      isSuccess = false;
    }
    return isSuccess;
  }
Пример #6
0
 @AfterClass
 public static void tearDown() throws IOException {
   out.close();
   err.close();
   if (tajoCli != null) {
     tajoCli.close();
   }
 }
 /*
  * @param shellCommand
  * @param params: the params to pass to the shellCommand
  * @param workingDirectory: the working directory for the process
  * @return the shell output of the command
  */
 public static String executeShellCommand(
     String shellCommand, String[] params, List<String> envp, File workingDirectory)
     throws IOException {
   String[] commandAndParams = new String[params.length + 1];
   int i = 0;
   commandAndParams[i++] = shellCommand;
   if (commandAndParams.length != i + params.length) throw new IllegalStateException();
   System.arraycopy(params, 0, commandAndParams, i, params.length);
   System.out.println("\n\n");
   for (int j = 0; j < commandAndParams.length; j++) {
     System.out.print(commandAndParams[j] + " ");
   }
   System.out.println("");
   Process process =
       Runtime.getRuntime()
           .exec(commandAndParams, envp.toArray(new String[] {}), workingDirectory);
   int exitValue = -1;
   long processStartTime = System.currentTimeMillis();
   long maxScriptExecutionTimeMillis =
       Long.parseLong(getProperty("MAX_SCRIPT_EXECUTION_TIME_MILLIS"));
   while (System.currentTimeMillis() - processStartTime < maxScriptExecutionTimeMillis) {
     try {
       exitValue = process.exitValue();
       break;
     } catch (IllegalThreadStateException e) {
       // not done yet
     }
     exitValue = -1;
     try {
       Thread.sleep(1000L);
     } catch (InterruptedException e) {
       throw new RuntimeException(e);
     }
   }
   if (exitValue == -1
       && System.currentTimeMillis() - processStartTime >= maxScriptExecutionTimeMillis) {
     throw new RuntimeException("Process exceeded alloted time.");
   }
   ByteArrayOutputStream resultOS = new ByteArrayOutputStream();
   String output = null;
   try {
     if (exitValue == 0) {
       IOUtils.copy(process.getInputStream(), resultOS);
     } else {
       IOUtils.copy(process.getErrorStream(), resultOS);
     }
     resultOS.close();
     output = new String(resultOS.toByteArray(), "UTF-8");
   } finally {
     if (resultOS != null) resultOS.close();
   }
   if (exitValue != 0) {
     System.out.println(output);
     throw new RuntimeException(output);
   }
   System.out.println(output);
   return output;
 }
Пример #8
0
  /**
   * 执行查询
   *
   * @param requestURL 请求地址
   * @param cookie COOKIE
   * @param reffer 引用页
   */
  public byte[] request4Body(String requestURL, String cookie, String reffer) {
    System.out.println("登录请求时的SESSIONID:" + cookie);
    URL url = null;
    InputStream in = null;
    ByteArrayOutputStream byteArray = null;
    byte[] body = null;
    try {
      if (null == url) {
        url = new URL(requestURL);
      }
      connection = (HttpURLConnection) url.openConnection();
      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.setReadTimeout(10 * 1000);
      connection.setConnectTimeout(15 * 1000);
      connection.setRequestMethod("GET");
      setCommonHeardFileds(connection);
      connection.setRequestProperty("Referer", reffer);
      connection.setRequestProperty("Cookie", cookie + "; cust_type=2");
      connection.connect();

      int code = -1;
      code = connection.getResponseCode();
      switch (code) {
        case 200:
          in = connection.getInputStream();
          byteArray = new ByteArrayOutputStream();
          byte[] buffer = new byte[1024];
          int ch;
          while ((ch = in.read(buffer)) != -1) {
            byteArray.write(buffer, 0, ch);
          }
          byteArray.flush();
          byteArray.close();
          body = byteArray.toByteArray();
          break;
        default:
          System.out.println(connection.getResponseCode() + ":" + connection.getResponseMessage());
          break;
      }

      if (null != in) {
        in.close();
      }
    } catch (Exception e) {
      if (null != byteArray) {
        try {
          byteArray.close();
        } catch (IOException e1) {
          e1.printStackTrace();
        }
      }
      if (null != url) {
        url = null;
      }
    }
    return body;
  }
Пример #9
0
  public void run() {
    URL url;
    Base64Encoder base64 = new Base64Encoder();

    try {
      url = new URL(urlString);
    } catch (MalformedURLException e) {
      System.err.println("Invalid URL");
      return;
    }

    try {
      conn = (HttpURLConnection) url.openConnection();
      conn.setRequestProperty("Authorization", "Basic " + base64.encode(user + ":" + pass));
    } catch (IOException e) {
      System.err.println("Unable to connect: " + e.getMessage());
      return;
    }
    try {
      httpIn = new BufferedInputStream(conn.getInputStream(), 8192);
      jpgOut = new ByteArrayOutputStream(8192);
    } catch (IOException e) {
      System.err.println("Unable to open I/O streams: " + e.getMessage());
      return;
    }

    int prev = 0;
    int cur = 0;

    try {
      while (keepAlive && (cur = httpIn.read()) >= 0) {
        if (prev == 0xFF && cur == 0xD8) {
          frameStarted = true;
          jpgOut.close();
          jpgOut = new ByteArrayOutputStream(8192);
          jpgOut.write((byte) prev);
        }
        if (frameStarted) {
          jpgOut.write((byte) cur);
          if (prev == 0xFF && cur == 0xD9) {
            curFrame = jpgOut.toByteArray();
            frameStarted = false;
            frameAvailable = true;
          }
        }
        prev = cur;
      }
    } catch (IOException e) {
      System.err.println("I/O Error: " + e.getMessage());
    }
    try {
      jpgOut.close();
      httpIn.close();
    } catch (IOException e) {
      System.err.println("Error closing I/O streams: " + e.getMessage());
    }
    conn.disconnect();
  }
  /** @see org.jlibrary.core.repository.RepositoryService#exportRepository(Ticket) */
  public byte[] exportRepository(Ticket ticket)
      throws RepositoryNotFoundException, RepositoryException, SecurityException {

    try {
      javax.jcr.Session session = SessionManager.getInstance().getSession(ticket);
      if (session == null) {
        throw new RepositoryException("Session has expired. Please log in again.");
      }
      javax.jcr.Node root = JCRUtils.getRootNode(session);
      if (!JCRSecurityService.canRead(root, ticket.getUser().getId())) {
        throw new SecurityException(SecurityException.NOT_ENOUGH_PERMISSIONS);
      }

      ByteArrayOutputStream baos1 = null;
      byte[] rootContent;
      try {
        baos1 = new ByteArrayOutputStream();
        session.exportSystemView(JCRUtils.getRootNode(session).getPath(), baos1, false, false);
        rootContent = baos1.toByteArray();
      } finally {
        if (baos1 != null) {
          baos1.close();
        }
      }
      byte[] systemContent;
      ByteArrayOutputStream baos2 = null;
      try {
        baos2 = new ByteArrayOutputStream();
        session.exportSystemView(JCRUtils.getSystemNode(session).getPath(), baos2, false, false);
        systemContent = baos2.toByteArray();
      } finally {
        if (baos2 != null) {
          baos2.close();
        }
      }

      String tag = String.valueOf(rootContent.length) + "*";
      byte[] header = tag.getBytes();

      byte[] content = new byte[header.length + rootContent.length + systemContent.length];
      System.arraycopy(header, 0, content, 0, header.length);
      System.arraycopy(rootContent, 0, content, header.length, rootContent.length);
      System.arraycopy(
          systemContent, 0, content, header.length + rootContent.length, systemContent.length);

      return zipContent(content);
    } catch (PathNotFoundException e) {
      logger.error(e.getMessage(), e);
      throw new RepositoryException(e);
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
      throw new RepositoryException(e);
    } catch (javax.jcr.RepositoryException e) {
      logger.error(e.getMessage(), e);
      throw new RepositoryException(e);
    }
  }
  private void verifyMessageBytes(MimeBodyPart a, MimeBodyPart b)
      throws IOException, MessagingException {
    ByteArrayOutputStream _baos = new ByteArrayOutputStream();
    a.writeTo(_baos);
    _baos.close();
    byte[] _msgBytes = _baos.toByteArray();
    _baos = new ByteArrayOutputStream();
    b.writeTo(_baos);
    _baos.close();
    byte[] _resBytes = _baos.toByteArray();

    assertEquals(true, Arrays.equals(_msgBytes, _resBytes));
  }
Пример #12
0
  private void verifyMessageBytes(MimeBodyPart a, MimeBodyPart b) throws Exception {
    ByteArrayOutputStream bOut1 = new ByteArrayOutputStream();

    a.writeTo(bOut1);
    bOut1.close();

    ByteArrayOutputStream bOut2 = new ByteArrayOutputStream();

    b.writeTo(bOut2);
    bOut2.close();

    assertEquals(true, Arrays.equals(bOut1.toByteArray(), bOut2.toByteArray()));
  }
Пример #13
0
  public static void main(String[] args) throws Exception {
    TransportStream stream = new TransportStream(new SourceURL("http://cb00.virtual/rtl.ts"));
    stream.setLimit(100L);
    stream.init();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Data item = stream.read();
    int items = 0;
    long bytesWritten = 0L;

    while (item != null) {
      // log.info("item: {}", item);

      int pid = (Integer) item.get("packet:pid");
      if (pid == 0) {

        if (bytesWritten > 0) {
          log.info("Closing old block...");
          baos.close();

          File file =
              new File("/Volumes/RamDisk/video-block-" + System.currentTimeMillis() + ".ts");
          FileOutputStream fos = new FileOutputStream(file);
          fos.write(baos.toByteArray());
          fos.close();
          log.info("Write TS chunk of size {} to {}", bytesWritten, file);
          baos = new ByteArrayOutputStream();
          bytesWritten = 0;
        }
      }

      if (baos != null) {
        byte[] data = (byte[]) item.get("packet:data");
        baos.write(data);
        bytesWritten += data.length;
      }

      items++;
      item = stream.read();
    }

    if (baos != null) {
      baos.close();
    }

    log.info("{} items read.", items);
    stream.close();
  }
Пример #14
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;
 }
  public String securityCode() {

    ByteArrayOutputStream output = null;
    try {
      output = new ByteArrayOutputStream();
      ImgCaptcha captcha =
          new ImgCaptcha.Builder(200, 45)
              .addText()
              .addBackground(new TransparentBackgroundProducer())
              .gimp()
              .addNoise()
              .addBorder()
              .build();

      String code = captcha.getCode();
      // Store this code in the session.
      storeInSession(ActionConts.SESS_SECURITY_CODE, code);
      BufferedImage img = captcha.getImage();
      ImageUtil.writeImage(output, img);
      this.imageStream = new ByteArrayInputStream(output.toByteArray());
    } catch (Exception e) {
      e.printStackTrace();
      return ERROR;
    } finally {
      if (output != null) {
        try {
          output.close();
        } catch (Exception e) {
          // ignore whatever.
        }
      }
    }
    return SUCCESS;
  }
Пример #16
0
  /**
   * 获得文件的字节数组
   *
   * @param filename
   * @return
   * @throws IOException
   */
  public static byte[] getByteFromFile(String filename) throws IOException {

    File f = new File(filename);
    if (!f.exists()) {
      throw new FileNotFoundException(filename);
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
    BufferedInputStream in = null;
    try {
      in = new BufferedInputStream(new FileInputStream(f));
      int buf_size = 1024;
      byte[] buffer = new byte[buf_size];
      int len = 0;
      while (-1 != (len = in.read(buffer, 0, buf_size))) {
        bos.write(buffer, 0, len);
      }
      return bos.toByteArray();
    } catch (IOException e) {
      e.printStackTrace();
      throw e;
    } finally {
      try {
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      bos.close();
    }
  }
Пример #17
0
  /**
   * Pack the structure to the network message
   *
   * @return the network message in byte[]
   * @throws MeasurementError stream writer failed
   */
  public byte[] getByteArray() throws MeasurementError {

    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream dataOut = new DataOutputStream(byteOut);

    try {
      dataOut.writeInt(type);
      dataOut.writeInt(burstCount);
      dataOut.writeInt(packetNum);
      dataOut.writeInt(intervalNum);
      dataOut.writeLong(timestamp);
      dataOut.writeInt(packetSize);
      dataOut.writeInt(seq);
      dataOut.writeInt(udpInterval);
    } catch (IOException e) {
      throw new MeasurementError("Create rawpacket failed! " + e.getMessage());
    }

    byte[] rawPacket = byteOut.toByteArray();

    try {
      byteOut.close();
    } catch (IOException e) {
      throw new MeasurementError("Error closing outputstream!");
    }
    return rawPacket;
  }
 private static byte[] getKeyRing(String fileName) throws IOException {
   InputStream is = PGPDataFormatTest.class.getClassLoader().getResourceAsStream(fileName);
   ByteArrayOutputStream output = new ByteArrayOutputStream();
   IOHelper.copyAndCloseInput(is, output);
   output.close();
   return output.toByteArray();
 }
  private void readJsonStream(InputStream istream, JsonObjectCallback callback)
      throws IOException, UnsupportedEncodingException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[8192];
    int count;
    while ((count = istream.read(buffer)) > 0) {
      baos.write(buffer, 0, count);
      String s = new String(baos.toByteArray(), "UTF-8");
      JsonReader reader = Json.createReader(new StringReader(s));
      JsonObject json = null;

      try {
        json = reader.readObject();
      } catch (JsonParsingException e) {
        // just ignore and continue
        continue;
      }

      baos.close();
      baos = new ByteArrayOutputStream();

      callback.callback(json);
    }
  }
Пример #20
0
  @Test
  public void validateJsonSerialization() throws IOException {

    final JsonSerializer serializer = new JsonSerializer();

    Record record = new StandardRecord("cisco");
    record.setId("firewall_record1");
    record.setField("timestamp", FieldType.LONG, new Date().getTime());
    record.setField("method", FieldType.STRING, "GET");
    record.setField("ip_source", FieldType.STRING, "123.34.45.123");
    record.setField("ip_target", FieldType.STRING, "255.255.255.255");
    record.setField("url_scheme", FieldType.STRING, "http");
    record.setField("url_host", FieldType.STRING, "origin-www.20minutes.fr");
    record.setField("url_port", FieldType.STRING, "80");
    record.setField("url_path", FieldType.STRING, "/r15lgc-100KB.js");
    record.setField("request_size", FieldType.INT, 1399);
    record.setField("response_size", FieldType.INT, 452);
    record.setField("is_outside_office_hours", FieldType.BOOLEAN, false);
    record.setField("is_host_blacklisted", FieldType.BOOLEAN, false);
    // record.setField("tags", FieldType.ARRAY, new ArrayList<>(Arrays.asList("spam", "filter",
    // "mail")));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    serializer.serialize(baos, record);
    baos.close();

    String strEvent = new String(baos.toByteArray());
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    Record deserializedRecord = serializer.deserialize(bais);

    assertTrue(deserializedRecord.equals(record));
  }
 /**
  * compare the byte-array representation of two TaskObjects.
  *
  * @param f TaskObject
  * @param s TaskObject
  * @return true if the two arguments have the same byte-array
  */
 private boolean sameBytes(TaskObject f, TaskObject s) {
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   ObjectOutput out = null;
   try {
     out = new ObjectOutputStream(bos);
     out.writeObject(f);
     byte[] fs = bos.toByteArray();
     out.writeObject(s);
     byte[] ss = bos.toByteArray();
     if (fs.length != ss.length) return false;
     for (int i = 0; i < fs.length; i++) {
       if (fs[i] != ss[i]) return false;
     }
     return true;
   } catch (IOException e) {
     e.printStackTrace();
     return false;
   } finally {
     if (out != null) {
       try {
         out.close();
       } catch (IOException e) {
         // ignore
       }
       try {
         bos.close();
       } catch (IOException e) {
         // ignore
       }
     }
   }
 }
Пример #22
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());
    }
  }
Пример #23
0
  private static void writeStaticAssets(AssetManager assets, ZipOutputStream out, String path) {
    try {
      for (String item : assets.list(path)) {
        try {
          InputStream fileIn = assets.open(path + "/" + item);

          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          BufferedInputStream bin = new BufferedInputStream(fileIn);

          byte[] buffer = new byte[8192];
          int read = 0;

          while ((read = bin.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, read);
          }

          bin.close();
          baos.close();

          ZipEntry entry = new ZipEntry(path + "/" + item);
          out.putNextEntry(entry);
          out.write(baos.toByteArray());
          out.closeEntry();
        } catch (IOException e) {
          BootstrapSiteExporter.writeStaticAssets(assets, out, path + "/" + item);
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #24
0
  /** Save the modifications */
  public static String dumpNode(Node written) {
    Transformer transformer = null;
    try {
      transformer = ScilabTransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException e1) {
      System.err.println("Cannot dump xml");
      return "";
    } catch (TransformerFactoryConfigurationError e1) {
      System.err.println("Cannot dump xml");
      return "";
    }
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(new BufferedOutputStream(stream));
    DOMSource source = new DOMSource(written);
    String str = "";
    try {
      transformer.transform(source, result);
      str = stream.toString();
    } catch (TransformerException e) {
      System.err.println("Cannot dump xml");
      return str;
    } finally {
      try {
        stream.close();
      } catch (Exception e) {
      }
    }

    return str;
  }
Пример #25
0
  /**
   * maintains a list of last <i>committedLog</i> or so committed requests. This is used for fast
   * follower synchronization.
   *
   * @param request committed request
   */
  public void addCommittedProposal(Request request) {
    WriteLock wl = logLock.writeLock();
    try {
      wl.lock();
      if (committedLog.size() > commitLogCount) {
        committedLog.removeFirst();
        minCommittedLog = committedLog.getFirst().packet.getZxid();
      }
      if (committedLog.isEmpty()) {
        minCommittedLog = request.zxid;
        maxCommittedLog = request.zxid;
      }

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
      try {
        request.getHdr().serialize(boa, "hdr");
        if (request.getTxn() != null) {
          request.getTxn().serialize(boa, "txn");
        }
        baos.close();
      } catch (IOException e) {
        LOG.error("This really should be impossible", e);
      }
      QuorumPacket pp = new QuorumPacket(Leader.PROPOSAL, request.zxid, baos.toByteArray(), null);
      Proposal p = new Proposal();
      p.packet = pp;
      p.request = request;
      committedLog.add(p);
      maxCommittedLog = p.packet.getZxid();
    } finally {
      wl.unlock();
    }
  }
Пример #26
0
 public synchronized void close() throws IOException {
   if (isOutputOpen) {
     super.close();
     payload = toByteArray();
     isOutputOpen = false;
   }
 }
Пример #27
0
 public void processImage(String fileName) throws IOException {
   if (fileName.startsWith("/")) {
     throw new IllegalArgumentException();
   }
   final SourceStringReader sourceStringReader = new SourceStringReader(incoming.get(fileName));
   final ByteArrayOutputStream baos = new ByteArrayOutputStream();
   final FileFormat format = FileFormat.PNG;
   final DiagramDescription desc =
       sourceStringReader.generateDiagramDescription(baos, new FileFormatOption(format));
   final String pngFileName = format.changeName(fileName, 0);
   final String errorFileName = pngFileName.substring(0, pngFileName.length() - 4) + ".err";
   synchronized (this) {
     outgoing.remove(pngFileName);
     outgoing.remove(errorFileName);
     if (desc != null && desc.getDescription() != null) {
       outgoing.put(pngFileName, baos.toByteArray());
       if (desc.getDescription().startsWith("(Error)")) {
         final ByteArrayOutputStream errBaos = new ByteArrayOutputStream();
         sourceStringReader.generateImage(errBaos, new FileFormatOption(FileFormat.ATXT));
         errBaos.close();
         outgoing.put(errorFileName, errBaos.toByteArray());
       }
     }
   }
 }
Пример #28
0
  /**
   * checks again for the necessary file and makes sure that they exist
   *
   * @throws IOException error processing
   */
  public void execute() throws IOException {
    // get from the in record and translate
    int translated = 0;
    int passed = 0;

    for (Record r : this.inStore) {
      if (this.force || r.needsProcessed(this.getClass())) {
        log.trace("Translating Record " + r.getID());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        xmlTranslate(
            new ByteArrayInputStream(r.getData().getBytes("UTF-8")),
            baos,
            new ByteArrayInputStream(this.translationString.getBytes()));
        this.outStore.addRecord(r.getID(), baos.toString(), this.getClass());
        r.setProcessed(this.getClass());
        baos.close();
        translated++;
      } else {
        log.trace("No Translation Needed: " + r.getID());
        passed++;
      }
    }
    log.info(Integer.toString(translated) + " records translated.");
    log.info(Integer.toString(passed) + " records did not need translation");
  }
Пример #29
0
  public static void downloadIt() {
    URL website;
    try {
      website = new URL(MainConstants.SOURCES_URL);

      try {
        InputStream in = new BufferedInputStream(website.openStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int n = 0;
        while (-1 != (n = in.read(buf))) {
          out.write(buf, 0, n);
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();
        FileOutputStream fos = new FileOutputStream(MainConstants.INPUT_ZIP_FILE);
        fos.write(response);
        fos.close();
        System.out.println("Download finished.");
      } catch (IOException ce) {
        System.out.print("Connection problem : " + ce);
      }

    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
  }
Пример #30
0
  /**
   * Read the input stream, attach Carriage_Return at the end of each segment
   *
   * @param in
   * @throws IOException
   */
  private void processInupt(InputStream in) throws IOException {
    // convert the InputStream into a BufferedReader
    InputStreamReader streamIn = new InputStreamReader(in);
    BufferedReader br = new BufferedReader(streamIn);
    byteOutList = new ArrayList<byte[]>();
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();

    // read each line of the file until EOF is reached
    String curLine = null;
    //        char lfChar=10; //line feed character
    char crtChar = 13; // Carriage return character

    while ((curLine = br.readLine()) != null) {
      curLine = curLine.trim();
      // skip blank line
      if (curLine.equals("")) continue;

      if (curLine.startsWith("MSH")) {
        if (byteOut.toByteArray().length > 0) {
          byteOutList.add(byteOut.toByteArray());
          byteOut = new ByteArrayOutputStream();
        }
      }
      byteOut.write(curLine.getBytes());
      byteOut.write((byte) crtChar);
    }
    byteOutList.add(byteOut.toByteArray());
    byteOut.close();
    in.close();
  }