Example #1
0
  public static String postXml(String url, String xmlData) {
    HttpPost post = new HttpPost(url);
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    try {
      StringEntity entity = new StringEntity(xmlData);
      post.setEntity(entity);
      post.setHeader("Content-Type", "text/xml;charset=UTF-8");

      HttpResponse response = httpClient.execute(post);
      is = response.getEntity().getContent();
      baos = new ByteArrayOutputStream();
      byte[] data = new byte[1024];
      int count = is.read(data);
      while (count != -1) {
        baos.write(data, 0, count);
        count = is.read(data);
      }
      return baos.toString();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (is != null)
        try {
          is.close();
        } catch (Exception ignore) {
        }
      if (baos != null)
        try {
          baos.close();
        } catch (Exception ignore) {
        }
    }
    return null;
  }
  void encode(DEROutputStream out) throws IOException {
    if (!empty) {
      ByteArrayOutputStream bOut = new ByteArrayOutputStream();
      DEROutputStream dOut = new DEROutputStream(bOut);

      dOut.writeObject(obj);
      dOut.close();

      byte[] bytes = bOut.toByteArray();

      if (explicit) {
        out.writeEncoded(CONSTRUCTED | TAGGED | tagNo, bytes);
      } else {
        //
        // need to mark constructed types...
        //
        if ((bytes[0] & CONSTRUCTED) != 0) {
          bytes[0] = (byte) (CONSTRUCTED | TAGGED | tagNo);
        } else {
          bytes[0] = (byte) (TAGGED | tagNo);
        }

        out.write(bytes);
      }
    } else {
      out.writeEncoded(CONSTRUCTED | TAGGED | tagNo, new byte[0]);
    }
  }
  @Test
  public void testDoFilterGzipResponseCompression() throws Exception {
    MockHttpServletRequest request =
        new MockHttpServletRequest(HttpMethod.POST.name(), "http://localhost:8080/gzip");
    request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");

    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain =
        new MockFilterChain(
            servlet,
            new GzipServletFilter(),
            new OncePerRequestFilter() {
              @Override
              protected void doFilterInternal(
                  HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                  throws ServletException, IOException {
                response.getOutputStream().write("Should be compressed".getBytes());
              }
            });
    filterChain.doFilter(request, response);

    ByteArrayOutputStream unzippedStream = new ByteArrayOutputStream();
    StreamUtils.copy(
        new GZIPInputStream(new ByteArrayInputStream(response.getContentAsByteArray())),
        unzippedStream);
    String unzipped = new String(unzippedStream.toByteArray());

    Assert.assertEquals(unzipped, "Should be compressed");
  }
  public static String xmlToJson(String xml, boolean formatted) throws XMLStreamException {
    InputStream input = new ByteArrayInputStream(xml.getBytes());
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    JsonXMLConfig config =
        new JsonXMLConfigBuilder()
            .autoArray(true)
            .autoPrimitive(true)
            .prettyPrint(formatted)
            .build();

    try {
      XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);
      XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
      writer.add(reader);
      reader.close();
      writer.close();
      try {
        return output.toString("UTF-8");
      } catch (UnsupportedEncodingException e) {
        throw new XMLStreamException(e.getMessage());
      }
    } finally {
      // dp nothing
    }
  }
  /**
   * Retrieve the bytes at the specified path.
   *
   * @param path - encoded but not fully qualified. Must NOT be slash prefixed as it will be
   *     appended to the host's url
   * @return
   * @throws com.ettrema.httpclient.HttpException
   */
  public synchronized byte[] get(String path)
      throws com.ettrema.httpclient.HttpException, NotAuthorizedException, BadRequestException,
          ConflictException, NotFoundException {
    String url = this.encodedUrl() + path;
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      transferService.get(
          url,
          new StreamReceiver() {

            @Override
            public void receive(InputStream in) {
              try {
                IOUtils.copy(in, out);
              } catch (IOException ex) {
                throw new RuntimeException(ex);
              }
            }
          },
          null,
          null);
    } catch (CancelledException ex) {
      throw new RuntimeException("Should never happen because no progress listener is set", ex);
    }
    return out.toByteArray();
  }
Example #6
0
  private void save2RS() {
    RecordStore rs = null;
    try {
      RecordStore.deleteRecordStore("score");
      rs = RecordStore.openRecordStore("score", true);

      try {
        for (int i = 0; i < 5; i++) {
          ByteArrayOutputStream bytes;
          DataOutputStream dataOut = new DataOutputStream(bytes = new ByteArrayOutputStream());
          ScoreItem item = (ScoreItem) list.elementAt(i);
          dataOut.writeUTF(item.name);
          dataOut.writeInt(item.points);
          dataOut.writeInt(item.level);
          dataOut.writeLong(item.date);
          byte[] byteA = bytes.toByteArray();
          rs.addRecord(byteA, 0, byteA.length);
        }
      } catch (IOException exp) {
        RecordStore.deleteRecordStore("score");
        System.out.println("XXXXXXXXXXXXXXXXXXXXXX");
      }
      // System.out.println("size of rs after saving: "+ rs.getNumRecords());
      rs.closeRecordStore();
    } catch (RecordStoreException exp) {
      System.out.println("fehler: " + exp.toString());
      exp.printStackTrace();
    }
  }
  /**
   * Test method for {@link cpath.converter.internal.UniprotCleanerImpl#cleane(java.lang.String)}.
   *
   * @throws IOException
   */
  @Test
  public void testCleaner() throws IOException {
    // read data from file and look for accessions before being cleaned
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    CPathUtils.unzip(
        new ZipInputStream(
            CPathUtils.LOADER.getResource("/test_uniprot_data.dat.zip").getInputStream()),
        os);
    byte[] bytes = os.toByteArray();
    String data = new String(bytes);
    assertTrue(data.indexOf(CALR3_HUMAN_BEFORE) != -1);
    assertTrue(data.indexOf(CALRL_HUMAN_BEFORE) != -1);

    Cleaner cleaner = new UniProtCleanerImpl();
    os.reset();
    cleaner.clean(new ByteArrayInputStream(bytes), os);
    bytes = os.toByteArray();

    data = new String(bytes);
    assertTrue(data.indexOf(CALR3_HUMAN_AFTER) != -1);
    assertTrue(data.indexOf(CALRL_HUMAN_AFTER) != -1);

    // dump owl for review
    String outFilename =
        getClass().getClassLoader().getResource("").getPath()
            + File.separator
            + "testCleanUniProt.out.dat";
    Writer out = new OutputStreamWriter(new FileOutputStream(outFilename));
    out.write(data);
    out.close();
  }
 /**
  * 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 block The sequential block number for the data to be read starting with 1
  * @param len The length of the block in bytes
  * @return The contents of the file
  */
 public byte[] readFromFile(String path, int block, int len) {
   byte[] buffer = null;
   try {
     if (_isLocal) {
       File tmpFile = new File(_rootFile.getCanonicalPath() + File.separatorChar + path);
       if (tmpFile.isFile()) {
         RandomAccessFile in = new RandomAccessFile(tmpFile, "r");
         in.seek((block - 1) * len);
         int result = -1;
         buffer = new byte[len];
         if (in.getFilePointer() < in.length()) {
           result = in.read(buffer);
           ByteArrayOutputStream out = new ByteArrayOutputStream(result);
           out.write(buffer, 0, result);
           in.close();
           return out.toByteArray();
         } else {
           in.close();
         }
       }
     } else {
       buffer = _remote.readFromFile(_domain, path, block, len);
     }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   return buffer;
 }
 /**
  * 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);
   }
 }
  /**
   * DO NOT call symbolTable.addReference in writeObject as this (may) result in a
   * concurrentModificationException.
   *
   * <p>All references should be created in the constructor
   */
  public void writeObject(DataOutput out) throws IOException {
    boolean sgIO = node instanceof com.sun.j3d.utils.scenegraph.io.SceneGraphIO;
    out.writeBoolean(sgIO);
    out.writeInt(symbol.nodeID);

    int nodeClassID = control.getNodeClassID(node);

    out.writeShort(nodeClassID);

    if (nodeClassID == -1) out.writeUTF(nodeClassName);

    writeConstructorParams(out);

    if (sgIO) {
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      DataOutputStream tmpOut = new DataOutputStream(byteStream);
      ((com.sun.j3d.utils.scenegraph.io.SceneGraphIO) node).writeSceneGraphObject(tmpOut);
      tmpOut.close();
      out.writeInt(byteStream.size());
      out.write(byteStream.toByteArray());
    }

    writeUserData(out);
    writeString(node.getName(), out);

    writeCapabilities(out);
  }
Example #11
0
  public void run() {
    try {
      for (Slice.FileData data = slice.readNextFile(); data != null; data = slice.readNextFile()) {
        FileList.FileLocation file = data.file;

        ByteArrayInputStream in = new ByteArrayInputStream(data.data);
        decoder.SetDecoderProperties(data.props);

        String fileName = destpath + "/" + file.fileName;
        File f = new File(fileName);
        f.getParentFile().mkdirs();

        // check if we need to undo the tranformation on x86 executables
        if ((file.fileName.contains(".exe")
            || file.fileName.contains(".dll"))) { // TODO there is an attribute for this
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          decoder.Code(in, out, file.originalSize);
          byte[] decompressedData = out.toByteArray();
          Util.transformCallInstructions(decompressedData);
          BufferedOutputStream outfile = new BufferedOutputStream(new FileOutputStream(f));
          outfile.write(decompressedData);
          outfile.close();
        } else {
          BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
          decoder.Code(in, out, file.originalSize);
          out.close();
        }
        f.setLastModified(file.mtime.getTime());
        ui.increaseProgress();
      }
    } catch (Exception e) {
      ui.showError(e.getLocalizedMessage());
      e.printStackTrace();
    }
  }
Example #12
0
  void run() throws Exception {
    File classesDir = new File("classes");
    classesDir.mkdirs();
    writeFile(baseFile, baseText);
    String[] javacArgs = {"-d", classesDir.getPath(), baseFile.getPath()};
    com.sun.tools.javac.Main.compile(javacArgs);

    writeFile(srcFile, srcText);
    String[] args = {
      "-d", "api", "-classpath", classesDir.getPath(), "-package", "p", srcFile.getPath()
    };

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    PrintStream prev = System.err;
    System.setErr(ps);
    try {
      int rc = com.sun.tools.javadoc.Main.execute(args);
    } finally {
      System.err.flush();
      System.setErr(prev);
    }
    String out = baos.toString();
    System.out.println(out);

    String errorMessage = "java.lang.IllegalArgumentException: <clinit>";
    if (out.contains(errorMessage)) throw new Exception("error message found: " + errorMessage);
  }
Example #13
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();
    }
  }
    private static void createBrokenMarkerFile(@Nullable Throwable reason) {
      final File brokenMarker = getCorruptionMarkerFile();

      try {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final PrintStream stream = new PrintStream(out);
        try {
          new Exception().printStackTrace(stream);
          if (reason != null) {
            stream.print("\nReason:\n");
            reason.printStackTrace(stream);
          }
        } finally {
          stream.close();
        }
        LOG.info("Creating VFS corruption marker; Trace=\n" + out.toString());

        final FileWriter writer = new FileWriter(brokenMarker);
        try {
          writer.write(
              "These files are corrupted and must be rebuilt from the scratch on next startup");
        } finally {
          writer.close();
        }
      } catch (IOException e) {
        // No luck.
      }
    }
Example #15
0
  public static String RenderTemplatePage(Bindings b, String templateName) throws IOException {

    MediaType mt = MediaType.TEXT_HTML;
    Resource config = model.createResource("eh:/root");
    Mode prefixMode = Mode.PreferPrefixes;
    ShortnameService sns = new StandardShortnameService();

    List<Resource> noResults = CollectionUtils.list(root.inModel(model));
    Graph resultGraph = graphModel.getGraph();

    resultGraph.getPrefixMapping().setNsPrefix("api", API.NS);
    resultGraph.add(Triple.create(root.asNode(), API.items.asNode(), RDF.nil.asNode()));

    APIResultSet rs = new APIResultSet(resultGraph, noResults, true, true, "details", View.ALL);
    VelocityRenderer vr = new VelocityRenderer(mt, null, config, prefixMode, sns);

    VelocityRendering vx = new VelocityRendering(b, rs, vr);

    VelocityEngine ve = vx.createVelocityEngine();
    VelocityContext vc = vx.createVelocityContext(b);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    Writer w = new OutputStreamWriter(bos, "UTF-8");
    Template t = ve.getTemplate(templateName);

    t.merge(vc, w);
    w.close();

    return bos.toString();
  }
Example #16
0
 @Override
 public byte[] getRawFile(String path) throws SVNException {
   org.tmatesoft.svn.core.io.SVNRepository repository = getSVNRepository();
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   repository.getFile(path, -1l, null, baos);
   return baos.toByteArray();
 }
  public static void main(String[] args) throws IOException {
    final int BUFF_SIZE = 4;
    final byte[] DATA_IN = {0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1};

    // Создаем файл 1
    try (OutputStream file =
        new FileOutputStream("/home/aleks/Java/JavaITCourses-master/tmp_files/1.txt")) {
      file.write(DATA_IN);
    } catch (IOException e) {
      System.out.println("Ой!");
    }
    // Сортируем данные файла 1 и записываем в файл java_out
    try (InputStream src =
            new FileInputStream("/home/aleks/Java/JavaITCourses-master/tmp_files/1.txt");
        OutputStream out =
            new FileOutputStream("/home/aleks/Java/JavaITCourses-master/tmp_files/java_out.txt")) {
      filterArray(src, out, BUFF_SIZE);
    } catch (IOException e) {
      System.out.println("Ой!!!");
    }
    // Печатаем из java_out в консоль
    //        byte[] arr = new byte[10];
    //        try (InputStream in = new
    // FileInputStream("/home/aleks/Java/JavaITCourses-master/tmp_files/java_out.txt")){
    //            in.read(arr);
    //        }
    try (ByteArrayOutputStream buff = new ByteArrayOutputStream();
        InputStream in =
            new FileInputStream("/home/aleks/Java/JavaITCourses-master/tmp_files/java_out.txt"); ) {
      copy(in, buff);
      System.out.println(Arrays.toString(buff.toByteArray()));
    }
  }
Example #18
0
 // -----------------------------------------------------------
 // for "SrvRqst"
 // find the matched URLs with (type, scope, predicate, ltag)
 // return: error code (short)
 //         number of matched URLs (short)
 //         URL blocks (decided bt previous #URL)
 // -----------------------------------------------------------
 public synchronized byte[] getMatchedURL(String type, String scope, String pred, String ltag) {
   byte[] buf = null;
   int ecode = Const.OK;
   if (!Util.shareString(daf.getScope(), scope, ",")) {
     ecode = Const.SCOPE_NOT_SUPPORTED;
   }
   b.reset();
   try {
     int count = 0;
     d.writeShort(ecode); // error code
     d.writeShort(count); // URL count, place holder
     if (ecode == Const.OK) { // no error, find matched URLs
       Iterator values = table.values().iterator();
       while (values.hasNext()) {
         Entry e = (Entry) values.next();
         if (e.match(type, scope, pred, ltag)) {
           count++;
           d.writeByte(0);
           d.writeShort(e.getLifetime());
           d.writeShort(e.getURL().length());
           d.writeBytes(e.getURL());
           d.writeByte(0);
         }
       }
     }
     buf = b.toByteArray();
     if (count > 0) Util.writeInt(buf, 2, count, 2); // update count
   } catch (Exception e) {
     if (ServiceLocationManager.displayMSLPTrace) e.printStackTrace();
   }
   return buf;
 }
  /** @throws IOException If failed. */
  private void initFavicon() throws IOException {
    assert favicon == null;

    InputStream in = getClass().getResourceAsStream("favicon.ico");

    if (in != null) {
      BufferedInputStream bis = new BufferedInputStream(in);

      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      try {
        byte[] buf = new byte[2048];

        while (true) {
          int n = bis.read(buf);

          if (n == -1) break;

          bos.write(buf, 0, n);
        }

        favicon = bos.toByteArray();
      } finally {
        U.closeQuiet(bis);
      }
    }
  }
Example #20
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();
 }
  /**
   * 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;
  }
Example #22
0
 /**
  * Resize image bytes to a max width or height image size.
  *
  * @param inputBytes input image bytes
  * @param max max size
  * @return scaled image bytes
  * @throws IOException on error
  */
 public static byte[] resizeImage(byte[] inputBytes, int max) throws IOException {
   BufferedImage inputImage = ImageIO.read(new ByteArrayInputStream(inputBytes));
   BufferedImage outputImage = resizeImage(inputImage, max);
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   ImageIO.write(outputImage, "jpg", baos);
   return baos.toByteArray();
 }
 /**
  * Serialize an object to a byte array. (code by CB)
  *
  * @param object object to serialize
  * @return byte array that represents the object
  * @throws Exception
  */
 public static byte[] toByte(Object object) throws Exception {
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   ObjectOutputStream oos = new ObjectOutputStream((OutputStream) os);
   oos.writeObject(object);
   oos.close();
   return os.toByteArray();
 }
Example #24
0
  /** Test of execute method, of class ToolProcessor. */
  public void testExecuteFileIdentify() throws Exception {
    Tool tool = repo.getTool("file");

    String tmpInputFile = this.getClass().getClassLoader().getResource("ps2pdf-input.ps").getFile();

    LOG.debug("tmpInputFile = " + tmpInputFile);

    LOG.info("TEST file-identify");

    ToolProcessor processor = new ToolProcessor(tool);

    Operation operation = processor.findOperation("identify");
    processor.setOperation(operation);

    Map<String, String> mapInput = new HashMap<String, String>();
    mapInput.put("input", tmpInputFile);

    processor.setInputFileParameters(mapInput);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    processor.next(new StreamProcessor(baos));
    try {
      processor.execute();
    } catch (IOException ex) {
      LOG.error("Exception during execution (maybe unresolved system dependency?): " + ex);
    }
    LOG.info("output: " + new String(baos.toByteArray()));
  }
Example #25
0
 /**
  * POSTs the variables and returns the body
  *
  * @param url - fully qualified and encoded URL to post to
  * @param params
  * @return
  */
 public String doPost(String url, Map<String, String> params)
     throws com.ettrema.httpclient.HttpException, NotAuthorizedException, ConflictException,
         BadRequestException, NotFoundException {
   notifyStartRequest();
   HttpPost m = new HttpPost(url);
   List<NameValuePair> formparams = new ArrayList<NameValuePair>();
   for (Entry<String, String> entry : params.entrySet()) {
     formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
   }
   UrlEncodedFormEntity entity;
   try {
     entity = new UrlEncodedFormEntity(formparams);
   } catch (UnsupportedEncodingException ex) {
     throw new RuntimeException(ex);
   }
   m.setEntity(entity);
   try {
     ByteArrayOutputStream bout = new ByteArrayOutputStream();
     int res = Utils.executeHttpWithStatus(client, m, bout);
     Utils.processResultCode(res, url);
     return bout.toString();
   } catch (HttpException ex) {
     throw new RuntimeException(ex);
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   } finally {
     notifyFinishRequest();
   }
 }
Example #26
0
  public void testExecuteFileIdentifyStdin() throws Exception {

    LOG.info("TEST file-identify-stdin");

    // This test may throw an "Broken pipe" IOException
    // because file needs not to read the whole file data from
    // stdin and will terminate while the other thread is reading streams.

    Tool tool = repo.getTool("file");

    String tmpInputFile = this.getClass().getClassLoader().getResource("ps2pdf-input.ps").getFile();

    ToolProcessor processor = new ToolProcessor(tool);
    Operation operation = processor.findOperation("identify-stdin");
    processor.setOperation(operation);

    FileInputStream fin = new FileInputStream(new File(tmpInputFile));
    StreamProcessor in = new StreamProcessor(fin);
    in.next(processor);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos = new ByteArrayOutputStream();

    processor.next(new StreamProcessor(baos));
    try {
      in.execute();
    } catch (IOException ex) {
      LOG.error("Exception during execution (maybe unresolved system dependency?): " + ex);
    }
    LOG.info("output: " + new String(baos.toByteArray()));
  }
Example #27
0
  public static String getResTxtContent(ClassLoader cl, String p) throws IOException {
    String s = res2txt_cont.get(p);
    if (s != null) return s;

    InputStream is = null;
    try {
      is = cl.getResourceAsStream(p);
      // is = this.getClass().getResourceAsStream(p);
      if (is == null) return null;

      byte[] buf = new byte[1024];
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int len;
      while ((len = is.read(buf)) >= 0) {
        baos.write(buf, 0, len);
      }

      byte[] cont = baos.toByteArray();
      s = new String(cont, "UTF-8");

      res2txt_cont.put(p, s);
      return s;
    } finally {
      if (is != null) is.close();
    }
  }
Example #28
0
  private Suggestions transformJsonResponse(final InputStream is, final Path transformation)
      throws IOException, TransformationException {
    try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
      jsonTransformer.transform(is, transformation, os);

      try (final InputStream resultIs = new ByteArrayInputStream(os.toByteArray())) {
        final JAXBContext context =
            org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(
                new Class[] {Suggestions.class}, null);

        final Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setProperty(
            UnmarshallerProperties.MEDIA_TYPE,
            org.eclipse.persistence.oxm.MediaType.APPLICATION_JSON);
        unmarshaller.setProperty(UnmarshallerProperties.JSON_ATTRIBUTE_PREFIX, null);
        unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, false);
        unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
        unmarshaller.setProperty(
            UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER, namespacePrefixMapper);
        unmarshaller.setProperty(UnmarshallerProperties.JSON_NAMESPACE_SEPARATOR, ':');

        final JAXBElement<Suggestions> jaxbElement =
            unmarshaller.unmarshal(new StreamSource(resultIs), Suggestions.class);
        return jaxbElement.getValue();
      } catch (final JAXBException e) {
        throw new TransformationException(e);
      }
    }
  }
 /**
  * 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
       }
     }
   }
 }
  private synchronized void init() throws IOException {
    // Need the extra test, to avoid throwing an IOException from the Transcoder
    if (imageInput == null) {
      throw new IllegalStateException("input == null");
    }

    if (reader == null) {
      WMFTranscoder transcoder = new WMFTranscoder();

      ByteArrayOutputStream output = new ByteArrayOutputStream();
      Writer writer = new OutputStreamWriter(output, "UTF8");
      try {
        TranscoderInput in = new TranscoderInput(IIOUtil.createStreamAdapter(imageInput));
        TranscoderOutput out = new TranscoderOutput(writer);

        // TODO: Transcodinghints?

        transcoder.transcode(in, out);
      } catch (TranscoderException e) {
        throw new IIOException(e.getMessage(), e);
      }

      reader = new SVGImageReader(getOriginatingProvider());
      reader.setInput(
          ImageIO.createImageInputStream(new ByteArrayInputStream(output.toByteArray())));
    }
  }