Esempio n. 1
0
 @Override
 public Future<Void> pasteHtmlAtCaret(String html) {
   String escapedHtml = this.escape(html);
   try {
     File js = File.createTempFile("paste", ".js");
     FileUtils.write(
         js,
         "if(['input','textarea'].indexOf(document.activeElement.tagName.toLowerCase()) != -1) { document.activeElement.value = '");
     FileOutputStream outStream = new FileOutputStream(js, true);
     IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream);
     IOUtils.copy(
         IOUtils.toInputStream(
             "';} else { var t,n;if(window.getSelection){t=window.getSelection();if(t.getRangeAt&&t.rangeCount){n=t.getRangeAt(0);n.deleteContents();var r=document.createElement(\"div\");r.innerHTML='"),
         outStream);
     IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream);
     IOUtils.copy(
         IOUtils.toInputStream(
             "';var i=document.createDocumentFragment(),s,o;while(s=r.firstChild){o=i.appendChild(s)}n.insertNode(i);if(o){n=n.cloneRange();n.setStartAfter(o);n.collapse(true);t.removeAllRanges();t.addRange(n)}}}else if(document.selection&&document.selection.type!=\"Control\"){document.selection.createRange().pasteHTML('"),
         outStream);
     IOUtils.copy(IOUtils.toInputStream(escapedHtml + "')}}"), outStream);
     return this.injectJsFile(js);
   } catch (Exception e) {
     return new CompletedFuture<Void>(null, e);
   }
 }
 public void testMemberSeek() throws IOException {
   GZIPMembersInputStream gzin = new GZIPMembersInputStream(new ByteArrayInputStream(allfour_gz));
   gzin.setEofEachMember(true);
   gzin.compressedSeek(noise1k_gz.length + noise32k_gz.length);
   int count2 = IOUtils.copy(gzin, ByteStreams.nullOutputStream());
   assertEquals("wrong 1-byte member count", 1, count2);
   //        assertEquals("wrong Member number", 2, gzin.getMemberNumber());
   assertEquals(
       "wrong Member2 start",
       noise1k_gz.length + noise32k_gz.length,
       gzin.getCurrentMemberStart());
   assertEquals(
       "wrong Member2 end",
       noise1k_gz.length + noise32k_gz.length + a_gz.length,
       gzin.getCurrentMemberEnd());
   gzin.nextMember();
   int count3 = IOUtils.copy(gzin, ByteStreams.nullOutputStream());
   assertEquals("wrong 5-byte member count", 5, count3);
   //        assertEquals("wrong Member number", 3, gzin.getMemberNumber());
   assertEquals(
       "wrong Member3 start",
       noise1k_gz.length + noise32k_gz.length + a_gz.length,
       gzin.getCurrentMemberStart());
   assertEquals(
       "wrong Member3 end",
       noise1k_gz.length + noise32k_gz.length + a_gz.length + hello_gz.length,
       gzin.getCurrentMemberEnd());
   gzin.nextMember();
   int countEnd = IOUtils.copy(gzin, ByteStreams.nullOutputStream());
   assertEquals("wrong eof count", 0, countEnd);
 }
 public void send(
     SlingHttpServletRequest request, SlingHttpServletResponse response, HtmlLibrary library) {
   InputStream libraryInputStream = null;
   // NOTE: HtmlLibraryManager#getLibrary should have prepared ClientLibraryImpl
   // and related binary stream should be ready
   try {
     Node node =
         JcrUtils.getNodeIfExists(getLibraryNode(request, library), JcrConstants.JCR_CONTENT);
     response.setDateHeader(
         "Last-Modified", JcrUtils.getLongProperty(node, JcrConstants.JCR_LASTMODIFIED, 0L));
     response.setContentType(library.getType().contentType);
     response.setCharacterEncoding("utf-8");
     libraryInputStream = JcrUtils.readFile(node);
   } catch (RepositoryException re) {
     log.debug("JCR issue retrieving library node at {}: ", library.getPath(), re.getMessage());
   }
   try {
     if (libraryManager.isGzipEnabled()) {
       response.setHeader("Content-Encoding", "gzip");
       GZIPOutputStream gzipOut = new GZIPOutputStream(response.getOutputStream());
       IOUtils.copy(libraryInputStream, gzipOut);
       gzipOut.finish();
     } else {
       IOUtils.copy(libraryInputStream, response.getOutputStream());
     }
   } catch (IOException ioe) {
     log.debug("gzip IO issue for library {}: ", library.getPath(), ioe.getMessage());
   } finally {
     IOUtils.closeQuietly(libraryInputStream);
   }
 }
Esempio n. 4
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    logger.info("get: " + req.getQueryString());

    String sessionId = req.getParameter("sessionId");
    if (!Utils.isNullOrEmpty(sessionId)) {
      Session session = getSessionCache().getSessionForSessionId(sessionId);
      if (session.getUserProfile() != null) {
        String picture = req.getParameter("picture");
        if ("tmp".equals(picture)) {
          String fileName = req.getParameter("filename");
          if (fileName.contains("..")) return;
          System.out.println("fnis:" + fileName);
          File picFile = new File(Backend.getWorkDir() + "tmpfiles" + File.separator + fileName);

          OutputStream out = resp.getOutputStream();
          FileInputStream fi = new FileInputStream(picFile);
          resp.setContentType("image");
          IOUtils.copy(fi, out);
          fi.close();
          out.close();

        } else if ("user".equals(picture)) {
          try {
            byte[] rawPicture = null;
            String fromUniqueUserId = req.getParameter("uniqueUserId");

            if (session.getUserProfile().getUniqueUserID().equals(fromUniqueUserId)) {
              if (Boolean.parseBoolean(req.getParameter("bigPicture"))) {
                logger.info("sending big user picture");
                rawPicture = session.getUserProfile().getUserCredentials().getPicture();
              } else {
                logger.info("sending small user picture");
                rawPicture = session.getUserProfile().getUserCredentials().getSmallPicture();
              }
            }
            OutputStream out = resp.getOutputStream();
            if (rawPicture == null) {
              FileInputStream fi =
                  new FileInputStream(
                      Backend.getWebContentFolder().getAbsolutePath()
                          + File.separator
                          + "images"
                          + File.separator
                          + "replacement_user_image.png");
              resp.setContentType("image");
              IOUtils.copy(fi, out);
              fi.close();
            } else {
              out.write(rawPicture);
            }
            out.close();
          } catch (Exception e) {
            logger.error("error sending user picture", e);
          }
        }
      }
    } else super.doGet(req, resp);
  }
Esempio n. 5
0
 /**
  * Copy bytes from an <code>InputStream</code> to chars on a <code>Writer</code> using the
  * specified character encoding.
  *
  * <p>This method buffers the input internally, so there is no need to use a <code>
  * BufferedInputStream</code>.
  *
  * <p>Character encoding names can be found at <a
  * href="http://www.iana.org/assignments/character-sets">IANA</a>.
  *
  * <p>This method uses {@link InputStreamReader}.
  *
  * @param input the <code>InputStream</code> to read from
  * @param output the <code>Writer</code> to write to
  * @param encoding the encoding to use, null means platform default
  * @throws NullPointerException if the input or output is null
  * @throws IOException if an I/O error occurs
  * @since Commons IO 1.1
  */
 public static void copy(InputStream input, Writer output, String encoding) throws IOException {
   if (encoding == null) {
     copy(input, output);
   } else {
     InputStreamReader in = new InputStreamReader(input, encoding);
     copy(in, output);
   }
 }
 /*
  * @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;
 }
Esempio n. 7
0
 public static void copy(Reader var0, OutputStream var1, String var2) throws IOException {
   if (var2 == null) {
     copy(var0, var1);
   } else {
     OutputStreamWriter var3 = new OutputStreamWriter(var1, var2);
     copy(var0, (Writer) var3);
     var3.flush();
   }
 }
Esempio n. 8
0
  @Override
  void transform() throws IOException {
    assert this.inputStream != null;

    try (InputStream stream = (InputStream) this.inputStream) {
      IOUtils.copy(stream, getOutputStream());
    } catch (Exception e) {
      IOUtils.copy(this.getErrorResponseStream(), getOutputStream());
    }
  }
Esempio n. 9
0
 /**
  * Copy chars from a <code>Reader</code> to bytes on an <code>OutputStream</code> using the
  * specified character encoding, and calling flush.
  *
  * <p>This method buffers the input internally, so there is no need to use a <code>BufferedReader
  * </code>.
  *
  * <p>Character encoding names can be found at <a
  * href="http://www.iana.org/assignments/character-sets">IANA</a>.
  *
  * <p>Due to the implementation of OutputStreamWriter, this method performs a flush.
  *
  * <p>This method uses {@link OutputStreamWriter}.
  *
  * @param input the <code>Reader</code> to read from
  * @param output the <code>OutputStream</code> to write to
  * @param encoding the encoding to use, null means platform default
  * @throws NullPointerException if the input or output is null
  * @throws IOException if an I/O error occurs
  * @since Commons IO 1.1
  */
 public static void copy(Reader input, OutputStream output, String encoding) throws IOException {
   if (encoding == null) {
     copy(input, output);
   } else {
     OutputStreamWriter out = new OutputStreamWriter(output, encoding);
     copy(input, out);
     // XXX Unless anyone is planning on rewriting OutputStreamWriter,
     // we have to flush here.
     out.flush();
   }
 }
  /** Return the primary text content of the message. */
  private static String getText(Part p) throws MessagingException, IOException {

    if (p.isMimeType("text/enriched")) {
      InputStream is = (InputStream) p.getContent();
      StringWriter writer = new StringWriter();
      IOUtils.copy(is, writer);
      return writer.toString();
    }

    if (p.isMimeType("text/*") && !p.isMimeType("text/enriched")) {
      p.getContentType();

      try {
        String s = (String) p.getContent();
        textIsHtml = p.isMimeType("text/html");
        return s;
      } catch (ClassCastException e) {
        InputStream is = (InputStream) p.getContent();
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer);
        textIsHtml = p.isMimeType("text/html");
        return writer.toString();
      }
    }

    if (p.isMimeType("multipart/alternative")) {
      // prefer html text over plain text
      Multipart mp = (Multipart) p.getContent();
      String text = null;
      for (int i = 0; i < mp.getCount(); i++) {
        Part bp = mp.getBodyPart(i);
        if (bp.isMimeType("text/plain")) {
          if (text == null) text = getText(bp);
          return text;
          // continue;
        } else if (bp.isMimeType("text/html")) {
          String s = getText(bp);
          if (s != null) return s;
        } else {
          return getText(bp);
        }
      }
      return text;
    } else if (p.isMimeType("multipart/*")) {
      Multipart mp = (Multipart) p.getContent();
      for (int i = 0; i < mp.getCount(); i++) {
        String s = getText(mp.getBodyPart(i));
        if (s != null) return s;
      }
    }

    return null;
  }
Esempio n. 11
0
 /* all private methods */
 private void readEntries(
     final ZipInputStream zis, final ExtractedMetadata metadata, final Asset asset)
     throws Exception {
   ZipEntry entry;
   while ((entry = zis.getNextEntry()) != null) {
     final String name = entry.getName();
     if (name.equals(ENTRY_CORE) || name.equals(ENTRY_APP)) {
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       IOUtils.copy(zis, out);
       // build xml document to extract meta info
       DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
       documentBuilderFactory.setNamespaceAware(true);
       Document document =
           documentBuilderFactory
               .newDocumentBuilder()
               .parse(new ByteArrayInputStream(out.toByteArray()));
       IOUtils.closeQuietly(out);
       DocumentTraversal dt = (DocumentTraversal) document;
       NodeIterator nit = dt.createNodeIterator(document, NodeFilter.SHOW_ELEMENT, null, true);
       nit.nextNode(); // skip first node
       Element next;
       while ((next = (Element) nit.nextNode()) != null) {
         metadata.setMetaDataProperty(next.getLocalName(), next.getTextContent());
       }
     } else if (name.equals(ENTRY_THUMBNAIL)) {
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       try {
         IOUtils.copy(zis, out);
         metadata.setProperty(META_KEY_THUMBNAIL, out.toByteArray());
       } finally {
         IOUtils.closeQuietly(out);
       }
     } else if (name.equals(ENTRY_THUMBNAIL_EMF)) {
       String mimeType = mimeTypeService.getMimeType(name);
       AssetHandler handler = store.getAssetHandler(mimeType);
       Rendition rend = asset.addRendition("thumbnail.emf", zis, mimeType);
       BufferedImage img = handler.getImage(rend);
       if (img != null) {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         try {
           ImageIO.write(img, JPEG_FORMAT, baos);
           baos.flush();
           metadata.setProperty(META_KEY_THUMBNAIL, baos.toByteArray());
         } finally {
           IOUtils.closeQuietly(baos);
         }
       } else {
         log.info("Cannot extract image from EMF format");
       }
     }
   }
 }
Esempio n. 12
0
    private void importExistingXml() throws IOException {
      InputStream xmlIn = TestSzenario.class.getResourceAsStream("/rsc/existing4_1.xml");
      StringWriter stringWriter = new StringWriter();
      IOUtils.copy(xmlIn, stringWriter, "UTF-8");
      NamedBlob blob = NamedBlob.load(XMLExporter.PREFIX + EXISTING_4_RNR);
      blob.putString(stringWriter.toString());

      xmlIn = TestSzenario.class.getResourceAsStream("/rsc/existing44_1.xml");
      stringWriter = new StringWriter();
      IOUtils.copy(xmlIn, stringWriter, "UTF-8");
      blob = NamedBlob.load(XMLExporter.PREFIX + EXISTING_44_RNR);
      blob.putString(stringWriter.toString());
    }
  @SuppressWarnings("deprecation")
  public void testMemberIterator() throws IOException {
    GZIPMembersInputStream gzin = new GZIPMembersInputStream(new ByteArrayInputStream(allfour_gz));
    Iterator<GZIPMembersInputStream> iter = gzin.memberIterator();
    assertTrue(iter.hasNext());
    GZIPMembersInputStream gzMember0 = iter.next();
    int count0 = IOUtils.copy(gzMember0, ByteStreams.nullOutputStream());
    assertEquals("wrong 1k member count", 1024, count0);
    assertEquals("wrong member number", 0, gzin.getMemberNumber());
    assertEquals("wrong member0 start", 0, gzin.getCurrentMemberStart());
    assertEquals("wrong member0 end", noise1k_gz.length, gzin.getCurrentMemberEnd());

    assertTrue(iter.hasNext());
    GZIPMembersInputStream gzMember1 = iter.next();
    int count1 = IOUtils.copy(gzMember1, ByteStreams.nullOutputStream());
    assertEquals("wrong 32k member count", (32 * 1024), count1);
    assertEquals("wrong member number", 1, gzin.getMemberNumber());
    assertEquals("wrong member1 start", noise1k_gz.length, gzin.getCurrentMemberStart());
    assertEquals(
        "wrong member1 end", noise1k_gz.length + noise32k_gz.length, gzin.getCurrentMemberEnd());

    assertTrue(iter.hasNext());
    GZIPMembersInputStream gzMember2 = iter.next();
    int count2 = IOUtils.copy(gzMember2, ByteStreams.nullOutputStream());
    assertEquals("wrong 1-byte member count", 1, count2);
    assertEquals("wrong member number", 2, gzin.getMemberNumber());
    assertEquals(
        "wrong member2 start",
        noise1k_gz.length + noise32k_gz.length,
        gzin.getCurrentMemberStart());
    assertEquals(
        "wrong member2 end",
        noise1k_gz.length + noise32k_gz.length + a_gz.length,
        gzin.getCurrentMemberEnd());

    assertTrue(iter.hasNext());
    GZIPMembersInputStream gzMember3 = iter.next();
    int count3 = IOUtils.copy(gzMember3, ByteStreams.nullOutputStream());
    assertEquals("wrong 5-byte member count", 5, count3);
    assertEquals("wrong member number", 3, gzin.getMemberNumber());
    assertEquals(
        "wrong member3 start",
        noise1k_gz.length + noise32k_gz.length + a_gz.length,
        gzin.getCurrentMemberStart());
    assertEquals(
        "wrong member3 end",
        noise1k_gz.length + noise32k_gz.length + a_gz.length + hello_gz.length,
        gzin.getCurrentMemberEnd());

    assertFalse(iter.hasNext());
  }
 public void testReadPerMemberSixSmall() throws IOException {
   GZIPMembersInputStream gzin = new GZIPMembersInputStream(new ByteArrayInputStream(sixsmall_gz));
   gzin.setEofEachMember(true);
   for (int i = 0; i < 3; i++) {
     int count2 = IOUtils.copy(gzin, ByteStreams.nullOutputStream());
     assertEquals("wrong 1-byte member count", 1, count2);
     gzin.nextMember();
     int count3 = IOUtils.copy(gzin, ByteStreams.nullOutputStream());
     assertEquals("wrong 5-byte member count", 5, count3);
     gzin.nextMember();
   }
   int countEnd = IOUtils.copy(gzin, ByteStreams.nullOutputStream());
   assertEquals("wrong eof count", 0, countEnd);
 }
Esempio n. 15
0
  private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
      throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
      throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileInputStream input = new FileInputStream(srcFile);
    try {
      FileOutputStream output = new FileOutputStream(destFile);
      try {
        IOUtils.copy(input, output);
      } finally {
        IOUtils.closeQuietly(output);
      }
    } finally {
      IOUtils.closeQuietly(input);
    }

    if (srcFile.length() != destFile.length()) {
      throw new IOException(
          "Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
      destFile.setLastModified(srcFile.lastModified());
    }
  }
Esempio n. 16
0
  private String query(String method, HashMap<String, String> args) {
    Mac mac = null;
    SecretKeySpec key = null;
    args.put("method", method);
    long time = System.currentTimeMillis() / 1000L;
    args.put("nonce", "" + (int) (time));
    String postData = "";
    for (Iterator argumentIterator = args.entrySet().iterator(); argumentIterator.hasNext(); ) {
      Map.Entry argument = (Map.Entry) argumentIterator.next();

      if (postData.length() > 0) {
        postData += "&";
      }
      postData += argument.getKey() + "=" + argument.getValue();
    }
    try {
      key = new SecretKeySpec(apisecret.getBytes("UTF-8"), "HmacSHA512");
      mac = Mac.getInstance("HmacSHA512");
      mac.init(key);
      URL queryUrl = new URL("https://btc-e.com/tapi/");
      HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();
      connection.setDoOutput(true);
      connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; Java Test client)");
      connection.setRequestProperty("Key", apikey);
      connection.setRequestProperty(
          "Sign", Hex.encodeHexString(mac.doFinal(postData.getBytes("UTF-8"))));
      connection.getOutputStream().write(postData.getBytes());
      StringWriter writer = new StringWriter();
      IOUtils.copy(connection.getInputStream(), writer, "UTF-8");
      return writer.toString();
    } catch (Exception ex) {
      utils.logger.log(true, ex.getMessage());
    }
    return new String();
  }
 /*
  * (non-Javadoc)
  *
  * @see org.abstracthorizon.proximity.storage.local.AbstractLocalStorage#storeItem(org.abstracthorizon.proximity.Item)
  */
 public void storeItem(Item item) throws StorageException {
   if (!item.getProperties().isFile()) {
     throw new IllegalArgumentException("Only files can be stored!");
   }
   logger.debug(
       "Storing item in [{}] in storage directory {}",
       item.getProperties().getPath(),
       getStorageBaseDir());
   try {
     if (item.getStream() != null) {
       File file = new File(getStorageBaseDir(), item.getProperties().getPath());
       file.getParentFile().mkdirs();
       FileOutputStream os = new FileOutputStream(file);
       try {
         IOUtils.copy(item.getStream(), os);
         item.getStream().close();
         os.flush();
       } finally {
         os.close();
       }
       item.setStream(new FileInputStream(file));
       file.setLastModified(item.getProperties().getLastModified().getTime());
       if (isMetadataAware()) {
         item.getProperties()
             .putAllMetadata(
                 getProxiedItemPropertiesFactory()
                     .expandItemProperties(item.getProperties().getPath(), file, false)
                     .getAllMetadata());
         storeItemProperties(item.getProperties());
       }
     }
   } catch (IOException ex) {
     throw new StorageException("IOException in FS storage " + getStorageBaseDir(), ex);
   }
 }
Esempio n. 18
0
  public static boolean CopyResourceToStorage(int resourceId, String path, boolean force) {
    File file = new File(path);

    // 파일이 존재하면 true return
    if (file.exists() && !force) {
      return true;
    }

    InputStream inputStream = null;
    OutputStream outputStream = null;

    try {
      // Stream 복사
      inputStream = context.getResources().openRawResource(resourceId);
      outputStream = context.openFileOutput(path, Context.MODE_PRIVATE);

      IOUtils.copy(inputStream, outputStream);
    } catch (Exception e) {
      path = e.getMessage();
      return false;
    } finally {
      IOUtils.closeQuietly(inputStream);
      IOUtils.closeQuietly(outputStream);
    }

    return true;
  }
Esempio n. 19
0
 private JarFile loadModuleJarFile(String moduleId, String version) throws IOException {
   InputStream moduleStream = null;
   File tempFile = null;
   OutputStream tempFileStream = null;
   JarFile jarFile = null;
   try {
     moduleStream =
         getClass()
             .getClassLoader()
             .getResourceAsStream(
                 "org/openmrs/module/include/" + moduleId + "-" + version + ".omod");
     Assert.assertNotNull(moduleStream);
     tempFile = File.createTempFile("moduleTest", "omod");
     tempFileStream = new FileOutputStream(tempFile);
     IOUtils.copy(moduleStream, tempFileStream);
     jarFile = new JarFile(tempFile);
   } finally {
     IOUtils.closeQuietly(moduleStream);
     IOUtils.closeQuietly(tempFileStream);
     if (tempFile != null) {
       tempFile.delete();
     }
   }
   return jarFile;
 }
Esempio n. 20
0
  /**
   * The method fetches the specified file from the amazon s3 bucket
   *
   * @throws IOException
   */
  public void getObjectFromS3() throws IOException {
    /**
     * Initializing the GetObjectRequest of Amazon S3. It is used to read files stored in amazon s3
     * bucket. It is initialized with the Aws_Bucket_Name, in which the file is stored, and the file
     * name which we want to read
     */
    GetObjectRequest getObj = new GetObjectRequest("AWS_BUCKET_NAME", "fileName");

    /**
     * Use the Amazon S3 client and the GetObjectRequest to fetch the files and hold it in the
     * S3Object container.
     */
    S3Object s3FileObj = getS3Client().getObject(getObj);
    /**
     * creating a temp file in memory for writing the file content
     *
     * <p>The Amazon S3Object does not directly converts to a File, nor does it has any built-in
     * function to do so. Hence we need to use the IOUtils of common.io for writing the input Stream
     * to a file. We can do the same using the conventional manual style but IOUtils provide the
     * built-in function for it, thus lessening our work.
     */
    File tempJsFile = File.createTempFile("temp", ".js");
    FileOutputStream out = new FileOutputStream(tempJsFile);
    IOUtils.copy(s3FileObj.getObjectContent(), out);
    out.close();
  }
  private void doSaveImage(final String diagramFileString, BpmnMemoryModel model) {
    boolean saveImage =
        PreferencesUtil.getBooleanPreference(Preferences.SAVE_IMAGE, ActivitiPlugin.getDefault());
    if (saveImage) {
      List<String> languages =
          PreferencesUtil.getStringArray(
              Preferences.ACTIVITI_LANGUAGES, ActivitiPlugin.getDefault());
      if (languages != null && languages.size() > 0) {

        for (String language : languages) {
          for (Process process : model.getBpmnModel().getProcesses()) {
            fillContainerWithLanguage(process, language);
          }

          ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
          InputStream imageStream =
              processDiagramGenerator.generatePngDiagram(model.getBpmnModel());

          if (imageStream != null) {
            String imageFileName = null;
            if (diagramFileString.endsWith(".bpmn20.xml")) {
              imageFileName =
                  diagramFileString.substring(0, diagramFileString.length() - 11)
                      + "_"
                      + language
                      + ".png";
            } else {
              imageFileName =
                  diagramFileString.substring(0, diagramFileString.lastIndexOf("."))
                      + "_"
                      + language
                      + ".png";
            }
            File imageFile = new File(imageFileName);
            FileOutputStream outStream = null;
            ByteArrayOutputStream baos = null;
            try {
              outStream = new FileOutputStream(imageFile);
              baos = new ByteArrayOutputStream();
              IOUtils.copy(imageStream, baos);
              baos.writeTo(outStream);

            } catch (Exception e) {
              e.printStackTrace();
            } finally {
              if (outStream != null) {
                IOUtils.closeQuietly(outStream);
              }
              if (baos != null) {
                IOUtils.closeQuietly(baos);
              }
            }
          }
        }

      } else {
        marshallImage(model, diagramFileString);
      }
    }
  }
 public String addVideo(String json, InputStream is, String fileName)
     throws ClientProtocolException, IOException {
   HttpClient httpclient = getHttpClient();
   try {
     File video = new File(fileName);
     OutputStream out = new FileOutputStream(video);
     IOUtils.copy(is, out);
     httpclient
         .getParams()
         .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
     HttpPost post = new HttpPost(BC_MEDIA_URL);
     MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
     ContentBody content =
         new FileBody(video, new MimetypesFileTypeMap().getContentType(fileName));
     multipart.addPart("JSON-RPC", new StringBody(json));
     multipart.addPart("file", content);
     post.setEntity(multipart);
     HttpResponse response = httpclient.execute(post);
     HttpEntity entity = response.getEntity();
     if (entity != null) {
       String result = EntityUtils.toString(entity);
       return result;
     }
   } finally {
     httpclient.getConnectionManager().shutdown();
   }
   return "";
 }
  public void download(File file) throws ExtensionException {
    InputStream sourceStream = null;
    OutputStream targetStream = null;

    try {
      sourceStream = new FileInputStream(getFile());
      targetStream = new FileOutputStream(file);

      IOUtils.copy(sourceStream, targetStream);
    } catch (Exception e) {
      throw new ExtensionException("Failed to copy file", e);
    } finally {
      IOException closeException = null;

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

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

      if (closeException != null) {
        throw new ExtensionException("Failed to close file", closeException);
      }
    }
  }
Esempio n. 24
0
  private double[] getSparkModelInfoFromHDFS(Path location, Configuration conf) throws Exception {

    FileSystem fileSystem = FileSystem.get(location.toUri(), conf);
    FileStatus[] files = fileSystem.listStatus(location);

    if (files == null) throw new Exception("Couldn't find Spark Truck ML weights at: " + location);

    ArrayList<Double> modelInfo = new ArrayList<Double>();
    for (FileStatus file : files) {

      if (file.getPath().getName().startsWith("_")) {
        continue;
      }

      InputStream stream = fileSystem.open(file.getPath());

      StringWriter writer = new StringWriter();
      IOUtils.copy(stream, writer, "UTF-8");
      String raw = writer.toString();
      for (String str : raw.split("\n")) {
        modelInfo.add(Double.valueOf(str));
      }
    }

    return Doubles.toArray(modelInfo);
  }
Esempio n. 25
0
  static {
    String outputPath = null;
    try {
      outputPath =
          "/tmp/" + md5(ResourceUtils.getResourceAsString("r/stl-wrapper.R") + "-stl-wrapper.R");
    } catch (IOException e) {
      e.printStackTrace();
    }
    TMP_STL_WRAPPER_R_PATH = outputPath;

    InputStream in = null;
    OutputStream out = null;
    try {
      in = STLDecompositionUtils.class.getClassLoader().getResourceAsStream("r/stl-wrapper.R");
      out = new FileOutputStream(TMP_STL_WRAPPER_R_PATH);
      IOUtils.copy(in, out);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
Esempio n. 26
0
  /** 申請ファイルアップロード準備 */
  private String prepareUploadDate(Shinsei shinsei, File toDir) {
    File receivedFile = null;
    byte[] receivedData = shinsei.getShinseiData();
    String outDirPath = toDir.getAbsolutePath();
    InputStream in = null;
    OutputStream out = null;

    try {
      receivedFile = File.createTempFile("dataset", ".zip");

      in = new ByteArrayInputStream(receivedData);
      out = new FileOutputStream(receivedFile);
      IOUtils.copy(in, out);

      if (receivedFile.length() > MAX_ZIP_FILE_SIZE) {
        log.debug("ZIPファイルサイズの制限超過しています。[" + receivedFile.length() + "]");
        return "TOO_LARGE_FILE";
      }

      new ZipFile(receivedFile.getAbsolutePath(), "UTF-8").extract(outDirPath);
      log.debug("申請データの展開先:" + outDirPath);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      IOUtils.closeQuietly(in);
      IOUtils.closeQuietly(out);
      if (!receivedFile.delete()) {
        log.info("申請ファイルが削除できませんでした。:" + receivedFile.getAbsolutePath());
      }
    }
    return "SUCCESS";
  }
  public synchronized ClassLoader getClassLoader(ProcessDefinition def) throws IOException {
    ClassLoader cl = cache.get(def.getId());
    if (cl == null) {
      File pdCache = new File(cacheRoot, Long.toString(def.getId()));
      if (!pdCache.exists()) {
        FileDefinition fd = def.getFileDefinition();
        for (Map.Entry<String, byte[]> entry :
            ((Map<String, byte[]>) fd.getBytesMap()).entrySet()) {
          File f = new File(pdCache, entry.getKey());
          f.getParentFile().mkdirs();
          FileOutputStream fos = new FileOutputStream(f);
          IOUtils.copy(new ByteArrayInputStream(entry.getValue()), fos);
          fos.close();
        }
      }
      cl =
          new URLClassLoader(
              new URL[] {new URL(pdCache.toURI().toURL(), "classes/")},
              Hudson.getInstance().getPluginManager().uberClassLoader) {

            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
              System.out.println(name);
              return super.loadClass(name);
            }
          };
      cache.put(def.getId(), cl);
    }
    return cl;
  }
Esempio n. 28
0
 public static LinkedHashMap readJarFileEntries(File jarFile) throws Exception {
   LinkedHashMap entries = new LinkedHashMap();
   JarFile jarFileWrapper = null;
   if (jarFile != null) {
     logger.debug("Reading jar entries from " + jarFile.getAbsolutePath());
     try {
       jarFileWrapper = new JarFile(jarFile);
       Enumeration iter = jarFileWrapper.entries();
       while (iter.hasMoreElements()) {
         ZipEntry zipEntry = (ZipEntry) iter.nextElement();
         InputStream entryStream = jarFileWrapper.getInputStream(zipEntry);
         ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
         try {
           IOUtils.copy(entryStream, byteArrayStream);
           entries.put(zipEntry.getName(), byteArrayStream.toByteArray());
           logger.debug(
               "Read jar entry " + zipEntry.getName() + " from " + jarFile.getAbsolutePath());
         } finally {
           byteArrayStream.close();
         }
       }
     } finally {
       if (jarFileWrapper != null) {
         try {
           jarFileWrapper.close();
         } catch (Exception ignore) {
           logger.debug(ignore);
         }
       }
     }
   }
   return entries;
 }
 /** Play Monument Handler for the server */
 @Override
 public void handle(HttpExchange exchange) throws IOException {
   exchange.getResponseHeaders().set("Content-type", "application/json");
   try {
     int gameID = checkCookie(exchange);
     if (gameID == -1) {
       System.err.print("\nInvalid Cookie. Thowing Error");
       throw new Exception("INVALID COOKIE!");
     }
     Gson gson = new Gson();
     StringWriter writer = new StringWriter();
     IOUtils.copy(exchange.getRequestBody(), writer);
     shared.communication.toServer.moves.Monument_ move =
         gson.fromJson(writer.toString(), Monument_.class);
     server.commands.Monument command = new server.commands.Monument(gameID);
     command.setParams(move);
     command.execute(server);
     this.addCommand(command, gameID);
     exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
     OutputStreamWriter output = new OutputStreamWriter(exchange.getResponseBody());
     output.write(server.getModel(gameID));
     output.flush();
     exchange.getResponseBody().close();
     exchange.close();
   } catch (Exception e) {
     exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, -1);
     exchange.getResponseBody().close();
     exchange.close();
   }
 }
  @Override
  public String processForm(Map<String, String> parameters, Map<String, FileItem> files)
      throws BadRequestException, NotAuthorizedException, ConflictException {
    log.trace("process");
    try {
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      Request request = HttpManager.request();
      IOUtils.copy(request.getInputStream(), bout);
      String iCalText = bout.toString("UTF-8");
      if (log.isTraceEnabled()) {
        log.trace("Freebusy query: " + iCalText);
      }
      List<SchedulingResponseItem> respItems = queryFreeBusy(iCalText);

      String xml = schedulingHelper.generateXml(respItems);
      xmlResponse = xml.getBytes(StringUtils.UTF8);
      if (log.isTraceEnabled()) {
        log.trace("FreeBusy response= " + xml);
      }

    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }
    return null;
  }