Exemple #1
0
  public static void patchFile(File originalFile, File deltaFile, File patchedFile)
      throws PortalException {

    FileInputStream originalFileInputStream = null;
    FileChannel originalFileChannel = null;
    FileOutputStream patchedFileOutputStream = null;
    WritableByteChannel patchedWritableByteChannel = null;
    ReadableByteChannel deltaReadableByteChannel = null;

    try {
      originalFileInputStream = new FileInputStream(originalFile);

      originalFileChannel = originalFileInputStream.getChannel();

      patchedFileOutputStream = new FileOutputStream(patchedFile);

      patchedWritableByteChannel = Channels.newChannel(patchedFileOutputStream);

      FileInputStream deltaInputStream = new FileInputStream(deltaFile);

      deltaReadableByteChannel = Channels.newChannel(deltaInputStream);

      ByteChannelReader deltaByteChannelReader = new ByteChannelReader(deltaReadableByteChannel);

      DeltaUtil.patch(originalFileChannel, patchedWritableByteChannel, deltaByteChannelReader);
    } catch (Exception e) {
      throw new PortalException(e);
    } finally {
      StreamUtil.cleanUp(originalFileInputStream);
      StreamUtil.cleanUp(originalFileChannel);
      StreamUtil.cleanUp(patchedFileOutputStream);
      StreamUtil.cleanUp(patchedWritableByteChannel);
      StreamUtil.cleanUp(deltaReadableByteChannel);
    }
  }
Exemple #2
0
  protected void addTempAttachment(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

    long nodeId = ParamUtil.getLong(actionRequest, "nodeId");
    String sourceFileName = uploadPortletRequest.getFileName("file");

    InputStream inputStream = null;

    try {
      inputStream = uploadPortletRequest.getFileAsStream("file");

      String mimeType = uploadPortletRequest.getContentType("file");

      String tempFileName = TempFileEntryUtil.getTempFileName(sourceFileName);

      FileEntry fileEntry =
          _wikiPageService.addTempFileEntry(
              nodeId, _TEMP_FOLDER_NAME, tempFileName, inputStream, mimeType);

      JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

      jsonObject.put("groupId", fileEntry.getGroupId());
      jsonObject.put("name", fileEntry.getTitle());
      jsonObject.put("title", sourceFileName);
      jsonObject.put("uuid", fileEntry.getUuid());

      JSONPortletResponseUtil.writeJSON(actionRequest, actionResponse, jsonObject);
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }
  protected Map<String, String> getMetadata(ZipReader zipReader) throws KBArticleImportException {

    InputStream inputStream = null;

    try {
      inputStream = zipReader.getEntryAsInputStream(".METADATA");

      if (inputStream == null) {
        return Collections.emptyMap();
      }

      Properties properties = new Properties();

      properties.load(inputStream);

      Map<String, String> metadata = new HashMap<String, String>(properties.size());

      for (Object key : properties.keySet()) {
        Object value = properties.get(key);

        if (value != null) {
          metadata.put(key.toString(), value.toString());
        }
      }

      return metadata;
    } catch (IOException ioe) {
      throw new KBArticleImportException(ioe);
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }
Exemple #4
0
  protected void exportThumbnail(
      PortletDataContext portletDataContext,
      FileEntry fileEntry,
      Element fileEntryElement,
      String binPathName,
      int index)
      throws PortalException, SystemException {

    FileVersion fileVersion = fileEntry.getFileVersion();

    if (!hasThumbnail(fileVersion, index)) {
      return;
    }

    InputStream is = null;

    try {
      is = doGetThumbnailAsStream(fileVersion, index);

      String binPath = getBinPath(portletDataContext, fileEntry, index);

      fileEntryElement.addAttribute(binPathName, binPath);

      exportBinary(portletDataContext, fileEntryElement, fileVersion, is, binPath, binPathName);
    } finally {
      StreamUtil.cleanUp(is);
    }
  }
Exemple #5
0
  protected void importThumbnail(
      PortletDataContext portletDataContext,
      FileEntry fileEntry,
      FileEntry importedFileEntry,
      Element fileEntryElement,
      String binPathName,
      int index)
      throws Exception {

    if (!portletDataContext.isPerformDirectBinaryImport()) {
      importThumbnailFromLAR(
          portletDataContext, importedFileEntry, fileEntryElement, binPathName, index);
    } else {
      FileVersion fileVersion = fileEntry.getFileVersion();

      if (!hasThumbnail(fileVersion, index)) {
        return;
      }

      InputStream is = null;

      try {
        is = doGetThumbnailAsStream(fileVersion, index);

        FileVersion importedFileVersion = importedFileEntry.getFileVersion();

        String thumbnailFilePath =
            getThumbnailFilePath(importedFileVersion, getThumbnailType(importedFileVersion), index);

        addFileToStore(portletDataContext.getCompanyId(), THUMBNAIL_PATH, thumbnailFilePath, is);
      } finally {
        StreamUtil.cleanUp(is);
      }
    }
  }
  public void addAttachment(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

    String portletId = PortalUtil.getPortletId(actionRequest);

    long resourcePrimKey = ParamUtil.getLong(uploadPortletRequest, "resourcePrimKey");

    String dirName = ParamUtil.getString(uploadPortletRequest, "dirName");
    String fileName = uploadPortletRequest.getFileName("file");

    InputStream inputStream = null;

    try {
      inputStream = uploadPortletRequest.getFileAsStream("file");

      ServiceContext serviceContext =
          ServiceContextFactory.getInstance(KBArticle.class.getName(), actionRequest);

      KBArticleServiceUtil.addAttachment(
          portletId, resourcePrimKey, dirName, fileName, inputStream, serviceContext);
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }
Exemple #7
0
  protected void importThumbnailFromLAR(
      PortletDataContext portletDataContext,
      FileEntry fileEntry,
      Element fileEntryElement,
      String binPathName,
      int index)
      throws Exception {

    FileVersion fileVersion = fileEntry.getFileVersion();

    String binPath = fileEntryElement.attributeValue(binPathName);

    InputStream is = null;

    try {
      is = portletDataContext.getZipEntryAsInputStream(binPath);

      if (is == null) {
        return;
      }

      String thumbnailFilePath =
          getThumbnailFilePath(fileVersion, getThumbnailType(fileVersion), index);

      addFileToStore(portletDataContext.getCompanyId(), THUMBNAIL_PATH, thumbnailFilePath, is);
    } finally {
      StreamUtil.cleanUp(is);
    }
  }
  private Properties _getProperties(String fileName) {
    if (Validator.isNull(fileName)) {
      fileName = PATCHER_PROPERTIES;
    }

    Properties properties = new Properties();

    Class<?> clazz = getClass();

    if (Objects.equals(fileName, PATCHER_SERVICE_PROPERTIES)) {
      clazz = clazz.getInterfaces()[0];
    }

    ClassLoader classLoader = clazz.getClassLoader();

    InputStream inputStream = classLoader.getResourceAsStream(fileName);

    if (inputStream == null) {
      if (_log.isDebugEnabled()) {
        _log.debug("Unable to load " + fileName);
      }
    } else {
      try {
        properties.load(inputStream);
      } catch (IOException ioe) {
        _log.error(ioe, ioe);
      } finally {
        StreamUtil.cleanUp(inputStream);
      }
    }

    return properties;
  }
  protected void indexKeywords(
      long companyId,
      long groupId,
      String languageId,
      String[] dictionaryFileNames,
      String keywordFieldName,
      String typeFieldValue,
      int maxNGramLength)
      throws Exception {

    for (String dictionaryFileName : dictionaryFileNames) {
      InputStream inputStream = null;

      if (_log.isInfoEnabled()) {
        _log.info("Start indexing dictionary for " + dictionaryFileName);
      }

      try {
        URL url = getResource(dictionaryFileName);

        if (url == null) {
          if (_log.isWarnEnabled()) {
            _log.warn("Unable to read " + dictionaryFileName);
          }

          continue;
        }

        inputStream = url.openStream();

        if (inputStream == null) {
          if (_log.isWarnEnabled()) {
            _log.warn("Unable to read " + dictionaryFileName);
          }

          continue;
        }

        indexKeywords(
            companyId,
            groupId,
            languageId,
            inputStream,
            keywordFieldName,
            typeFieldValue,
            maxNGramLength);
      } finally {
        StreamUtil.cleanUp(inputStream);
      }

      if (_log.isInfoEnabled()) {
        _log.info("Finished indexing dictionary for " + dictionaryFileName);
      }
    }
  }
  private void _generateImages(FileVersion sourceFileVersion, FileVersion destinationFileVersion)
      throws Exception {

    InputStream inputStream = null;

    try {
      if (sourceFileVersion != null) {
        copy(sourceFileVersion, destinationFileVersion);

        return;
      }

      if (_hasImages(destinationFileVersion)) {
        return;
      }

      String extension = destinationFileVersion.getExtension();

      if (extension.equals("pdf")) {
        if (destinationFileVersion instanceof LiferayFileVersion) {
          try {
            LiferayFileVersion liferayFileVersion = (LiferayFileVersion) destinationFileVersion;

            File file = liferayFileVersion.getFile(false);

            _generateImages(destinationFileVersion, file);

            return;
          } catch (UnsupportedOperationException uoe) {
          }
        }

        inputStream = destinationFileVersion.getContentStream(false);

        _generateImages(destinationFileVersion, inputStream);
      } else if (DocumentConversionUtil.isEnabled()) {
        inputStream = destinationFileVersion.getContentStream(false);

        String tempFileId =
            DLUtil.getTempFileId(
                destinationFileVersion.getFileEntryId(), destinationFileVersion.getVersion());

        File file = DocumentConversionUtil.convert(tempFileId, inputStream, extension, "pdf");

        _generateImages(destinationFileVersion, file);
      }
    } catch (NoSuchFileEntryException nsfee) {
    } finally {
      StreamUtil.cleanUp(inputStream);

      _fileVersionIds.remove(destinationFileVersion.getFileVersionId());
    }
  }
Exemple #11
0
  protected void importPreviewFromLAR(
      PortletDataContext portletDataContext,
      FileEntry fileEntry,
      Element fileEntryElement,
      String binPathSuffix,
      String previewType,
      int fileIndex)
      throws Exception {

    FileVersion fileVersion = fileEntry.getFileVersion();

    String binPathSegment = null;

    if (fileIndex < 0) {
      binPathSegment = previewType;
    } else {
      binPathSegment = Integer.toString(fileIndex + 1);
    }

    StringBundler sb = new StringBundler(4);

    sb.append("bin-path-preview-");
    sb.append(binPathSegment);
    sb.append("-");
    sb.append(binPathSuffix);

    String binPathName = sb.toString();

    String binPath = fileEntryElement.attributeValue(binPathName);

    InputStream is = null;

    try {
      is = portletDataContext.getZipEntryAsInputStream(binPath);

      if (is == null) {
        return;
      }

      String previewFilePath = null;

      if (fileIndex < 0) {
        previewFilePath = getPreviewFilePath(fileVersion, previewType);
      } else {
        previewFilePath = getPreviewFilePath(fileVersion, fileIndex + 1);
      }

      addFileToStore(portletDataContext.getCompanyId(), PREVIEW_PATH, previewFilePath, is);
    } finally {
      StreamUtil.cleanUp(is);
    }
  }
Exemple #12
0
  public static String getChecksum(File file) throws PortalException {
    FileInputStream fileInputStream = null;

    try {
      fileInputStream = new FileInputStream(file);

      return getChecksum(fileInputStream);
    } catch (Exception e) {
      throw new PortalException(e);
    } finally {
      StreamUtil.cleanUp(fileInputStream);
    }
  }
  public String getContentType(File file, String title) {
    InputStream is = null;

    try {
      is = TikaInputStream.get(file);

      return getContentType(is, title);
    } catch (FileNotFoundException fnfe) {
      return getContentType(title);
    } finally {
      StreamUtil.cleanUp(is);
    }
  }
Exemple #14
0
  protected void exportPreview(
      PortletDataContext portletDataContext,
      FileEntry fileEntry,
      Element fileEntryElement,
      String binPathSuffix,
      String previewType,
      int fileIndex)
      throws Exception {

    if (portletDataContext.isPerformDirectBinaryImport()) {
      return;
    }

    String binPathSegment = null;

    if (fileIndex < 0) {
      binPathSegment = previewType;
    } else {
      binPathSegment = Integer.toString(fileIndex + 1);
    }

    String binPath = getBinPath(portletDataContext, fileEntry, binPathSegment);

    StringBundler sb = new StringBundler(4);

    sb.append("bin-path-preview-");
    sb.append(binPathSegment);
    sb.append("-");
    sb.append(binPathSuffix);

    String binPathName = sb.toString();

    fileEntryElement.addAttribute(binPathName, binPath);

    FileVersion fileVersion = fileEntry.getFileVersion();

    InputStream is = null;

    try {
      if (fileIndex < 0) {
        is = doGetPreviewAsStream(fileVersion, previewType);
      } else {
        is = doGetPreviewAsStream(fileVersion, fileIndex + 1, previewType);
      }

      exportBinary(portletDataContext, fileEntryElement, fileVersion, is, binPath, binPathName);
    } finally {
      StreamUtil.cleanUp(is);
    }
  }
  protected Layout importLayoutFromLAR(StagedModel stagedModel)
      throws DocumentException, IOException {

    LayoutSetPrototypeStagedModelDataHandler layoutSetPrototypeStagedModelDataHandler =
        new LayoutSetPrototypeStagedModelDataHandler();

    String fileName =
        layoutSetPrototypeStagedModelDataHandler.getLayoutSetPrototypeLARFileName(
            (LayoutSetPrototype) stagedModel);

    String modelPath = ExportImportPathUtil.getModelPath(stagedModel, fileName);

    InputStream inputStream = portletDataContext.getZipEntryAsInputStream(modelPath);

    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(inputStream);

    Document document = UnsecureSAXReaderUtil.read(zipReader.getEntryAsString("manifest.xml"));

    Element rootElement = document.getRootElement();

    Element layoutElement = rootElement.element("Layout");

    List<Element> elements = layoutElement.elements();

    List<Layout> importedLayouts = new ArrayList<>(elements.size());

    for (Element element : elements) {
      String layoutPrototypeUuid = element.attributeValue("layout-prototype-uuid");

      if (Validator.isNotNull(layoutPrototypeUuid)) {
        String path = element.attributeValue("path");

        Layout layout = (Layout) portletDataContext.fromXML(zipReader.getEntryAsString(path));

        importedLayouts.add(layout);
      }
    }

    Assert.assertEquals(1, importedLayouts.size());

    try {
      return importedLayouts.get(0);
    } finally {
      zipReader.close();

      StreamUtil.cleanUp(inputStream);
    }
  }
Exemple #16
0
  protected void addAttachment(ActionRequest actionRequest) throws Exception {
    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

    long nodeId = ParamUtil.getLong(actionRequest, "nodeId");
    String title = ParamUtil.getString(actionRequest, "title");

    int numOfFiles = ParamUtil.getInteger(actionRequest, "numOfFiles");

    List<ObjectValuePair<String, InputStream>> inputStreamOVPs = new ArrayList<>();

    try {
      if (numOfFiles == 0) {
        String fileName = uploadPortletRequest.getFileName("file");
        InputStream inputStream = uploadPortletRequest.getFileAsStream("file");

        if (inputStream != null) {
          ObjectValuePair<String, InputStream> inputStreamOVP =
              new ObjectValuePair<>(fileName, inputStream);

          inputStreamOVPs.add(inputStreamOVP);
        }
      } else {
        for (int i = 1; i <= numOfFiles; i++) {
          String fileName = uploadPortletRequest.getFileName("file" + i);
          InputStream inputStream = uploadPortletRequest.getFileAsStream("file" + i);

          if (inputStream == null) {
            continue;
          }

          ObjectValuePair<String, InputStream> inputStreamOVP =
              new ObjectValuePair<>(fileName, inputStream);

          inputStreamOVPs.add(inputStreamOVP);
        }
      }

      _wikiPageService.addPageAttachments(nodeId, title, inputStreamOVPs);
    } finally {
      for (ObjectValuePair<String, InputStream> inputStreamOVP : inputStreamOVPs) {

        InputStream inputStream = inputStreamOVP.getValue();

        StreamUtil.cleanUp(inputStream);
      }
    }
  }
  protected void importKBArticleAttachments(
      PortletDataContext portletDataContext, KBArticle kbArticle, KBArticle importedKBArticle)
      throws Exception {

    List<Element> dlFileEntryElements =
        portletDataContext.getReferenceDataElements(kbArticle, DLFileEntry.class);

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setCompanyId(portletDataContext.getCompanyId());
    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());

    InputStream inputStream = null;

    for (Element dlFileEntryElement : dlFileEntryElements) {
      try {
        byte[] bytes =
            portletDataContext.getZipEntryAsByteArray(dlFileEntryElement.attributeValue("path"));

        inputStream = new UnsyncByteArrayInputStream(bytes);

        String fileName = dlFileEntryElement.attributeValue("file-name");

        String mimeType = KnowledgeBaseUtil.getMimeType(bytes, fileName);

        PortletFileRepositoryUtil.addPortletFileEntry(
            portletDataContext.getScopeGroupId(),
            portletDataContext.getUserId(importedKBArticle.getUserUuid()),
            KBArticle.class.getName(),
            importedKBArticle.getClassPK(),
            PortletKeys.KNOWLEDGE_BASE_ADMIN,
            importedKBArticle.getAttachmentsFolderId(),
            inputStream,
            fileName,
            mimeType,
            true);
      } catch (DuplicateFileException dfe) {
        continue;
      } finally {
        StreamUtil.cleanUp(inputStream);
      }
    }
  }
  @Override
  protected Metadata extractMetadata(String extension, String mimeType, File file) {

    Metadata metadata = super.extractMetadata(extension, mimeType, file);

    boolean forkProcess = false;

    if (PropsValues.TEXT_EXTRACTION_FORK_PROCESS_ENABLED) {
      if (ArrayUtil.contains(PropsValues.TEXT_EXTRACTION_FORK_PROCESS_MIME_TYPES, mimeType)) {

        forkProcess = true;
      }
    }

    if (forkProcess) {
      ExtractMetadataProcessCallable extractMetadataProcessCallable =
          new ExtractMetadataProcessCallable(file, metadata, _parser);

      try {
        Future<Metadata> future =
            ProcessExecutor.execute(
                ClassPathUtil.getPortalProcessConfig(), extractMetadataProcessCallable);

        return future.get();
      } catch (Exception e) {
        throw new SystemException(e);
      }
    }

    InputStream inputStream = null;

    try {
      inputStream = new FileInputStream(file);

      return extractMetadata(inputStream, metadata, _parser);
    } catch (IOException ioe) {
      throw new SystemException(ioe);
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }
  protected void importLayouts(
      PortletDataContext portletDataContext,
      LayoutSetPrototype layoutSetPrototype,
      LayoutSetPrototype importedLayoutSetPrototype,
      ServiceContext serviceContext)
      throws PortalException {

    InputStream inputStream = null;

    try {
      String layoutSetPrototypeLARPath =
          ExportImportPathUtil.getModelPath(
              layoutSetPrototype, getLayoutSetPrototypeLARFileName(layoutSetPrototype));

      inputStream = portletDataContext.getZipEntryAsInputStream(layoutSetPrototypeLARPath);

      SitesUtil.importLayoutSetPrototype(importedLayoutSetPrototype, inputStream, serviceContext);
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }
Exemple #20
0
  protected void importPreview(
      PortletDataContext portletDataContext,
      FileEntry fileEntry,
      FileEntry importedFileEntry,
      Element fileEntryElement,
      String binPathSuffix,
      String previewType,
      int fileIndex)
      throws Exception {

    if (!portletDataContext.isPerformDirectBinaryImport()) {
      importPreviewFromLAR(
          portletDataContext,
          importedFileEntry,
          fileEntryElement,
          binPathSuffix,
          previewType,
          fileIndex);
    } else {
      FileVersion importedFileVersion = importedFileEntry.getFileVersion();

      String previewFilePath = getPreviewFilePath(importedFileVersion, previewType);

      FileVersion fileVersion = fileEntry.getFileVersion();

      InputStream is = null;

      try {
        if (fileIndex < 0) {
          is = doGetPreviewAsStream(fileVersion, previewType);
        } else {
          is = doGetPreviewAsStream(fileVersion, fileIndex, previewType);
        }

        addFileToStore(portletDataContext.getCompanyId(), PREVIEW_PATH, previewFilePath, is);
      } finally {
        StreamUtil.cleanUp(is);
      }
    }
  }
  protected void exportLayouts(
      LayoutSetPrototype layoutSetPrototype, PortletDataContext portletDataContext)
      throws Exception {

    File file = null;
    InputStream inputStream = null;

    try {
      file = SitesUtil.exportLayoutSetPrototype(layoutSetPrototype, new ServiceContext());

      inputStream = new FileInputStream(file);

      String layoutSetPrototypeLARPath =
          ExportImportPathUtil.getModelPath(
              layoutSetPrototype, getLayoutSetPrototypeLARFileName(layoutSetPrototype));

      portletDataContext.addZipEntry(layoutSetPrototypeLARPath, inputStream);

      List<Layout> layoutSetPrototypeLayouts =
          _layoutLocalService.getLayouts(layoutSetPrototype.getGroupId(), true);

      Element layoutSetPrototypeElement =
          portletDataContext.getExportDataElement(layoutSetPrototype);

      for (Layout layoutSetPrototypeLayout : layoutSetPrototypeLayouts) {
        portletDataContext.addReferenceElement(
            layoutSetPrototype,
            layoutSetPrototypeElement,
            layoutSetPrototypeLayout,
            PortletDataContext.REFERENCE_TYPE_EMBEDDED,
            false);
      }
    } finally {
      StreamUtil.cleanUp(inputStream);

      if (file != null) {
        file.delete();
      }
    }
  }
  protected void addKBArticleAttachments(
      KBArticle kbArticle, String dirName, ServiceContext serviceContext)
      throws PortalException, SystemException {

    try {
      DLStoreUtil.addDirectory(
          serviceContext.getCompanyId(),
          CompanyConstants.SYSTEM,
          kbArticle.getAttachmentsDirName());
    } catch (DuplicateDirectoryException dde) {
      _log.error("Directory already exists for " + dde.getMessage());
    }

    if (Validator.isNull(dirName)) {
      return;
    }

    String[] fileNames =
        DLStoreUtil.getFileNames(serviceContext.getCompanyId(), CompanyConstants.SYSTEM, dirName);

    for (String fileName : fileNames) {
      InputStream inputStream = null;

      try {
        inputStream =
            DLStoreUtil.getFileAsStream(
                serviceContext.getCompanyId(), CompanyConstants.SYSTEM, fileName);

        addAttachment(
            kbArticle.getAttachmentsDirName(),
            FileUtil.getShortFileName(fileName),
            inputStream,
            serviceContext);
      } catch (DuplicateFileException dfe) {
        _log.error("File already exists for " + dfe.getMessage());
      } finally {
        StreamUtil.cleanUp(inputStream);
      }
    }
  }
  protected FileEntry addTempImageFileEntry(PortletRequest portletRequest) throws Exception {

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(portletRequest);

    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);

    String contentType = uploadPortletRequest.getContentType("fileName");

    if (!MimeTypesUtil.isWebImage(contentType)) {
      throw new ImageTypeException();
    }

    String fileName = uploadPortletRequest.getFileName("fileName");

    try {
      TempFileEntryUtil.deleteTempFileEntry(
          themeDisplay.getScopeGroupId(),
          themeDisplay.getUserId(),
          getTempImageFolderName(),
          fileName);
    } catch (Exception e) {
    }

    InputStream inputStream = null;

    try {
      inputStream = uploadPortletRequest.getFileAsStream("fileName");

      return TempFileEntryUtil.addTempFileEntry(
          themeDisplay.getScopeGroupId(),
          themeDisplay.getUserId(),
          getTempImageFolderName(),
          fileName,
          inputStream,
          contentType);
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }
Exemple #24
0
  public static void transfer(
      ReadableByteChannel readableByteChannel,
      WritableByteChannel writableByteChannel,
      int bufferSize,
      boolean cleanUp)
      throws IOException {

    try {
      if (readableByteChannel == null) {
        throw new IllegalArgumentException("Readable byte channel cannot be null");
      }

      if (writableByteChannel == null) {
        throw new IllegalArgumentException("Writable byte channel cannot be null");
      }

      ByteBuffer byteBuffer = ByteBuffer.allocateDirect(bufferSize);

      while (readableByteChannel.read(byteBuffer) != -1) {
        byteBuffer.flip();

        writableByteChannel.write(byteBuffer);

        byteBuffer.compact();
      }

      byteBuffer.flip();

      while (byteBuffer.hasRemaining()) {
        writableByteChannel.write(byteBuffer);
      }
    } finally {
      if (cleanUp) {
        cleanUp(readableByteChannel, writableByteChannel);
      }
    }
  }
Exemple #25
0
  public static void transfer(
      InputStream inputStream, OutputStream outputStream, int bufferSize, boolean cleanUp)
      throws IOException {

    if (inputStream == null) {
      throw new IllegalArgumentException("Input stream cannot be null");
    }

    if (outputStream == null) {
      throw new IllegalArgumentException("Output stream cannot be null");
    }

    if (bufferSize <= 0) {
      bufferSize = BUFFER_SIZE;
    }

    if (USE_NIO) {
      ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
      WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);

      transfer(readableByteChannel, writableByteChannel, bufferSize, cleanUp);
    } else {
      try {
        byte[] bytes = new byte[bufferSize];

        int value = -1;

        while ((value = inputStream.read(bytes)) != -1) {
          outputStream.write(bytes, 0, value);
        }
      } finally {
        if (cleanUp) {
          cleanUp(inputStream, outputStream);
        }
      }
    }
  }
  protected void transferFileToRemoteLive(
      File file, long stagingRequestId, HttpPrincipal httpPrincipal) throws Exception {

    byte[] bytes = new byte[PropsValues.STAGING_REMOTE_TRANSFER_BUFFER_SIZE];

    int i = 0;
    int j = 0;

    String numberFormat =
        String.format("%%0%dd", String.valueOf((int) (file.length() / bytes.length)).length() + 1);

    FileInputStream fileInputStream = null;

    try {
      fileInputStream = new FileInputStream(file);

      while ((i = fileInputStream.read(bytes)) >= 0) {
        String fileName = file.getName() + String.format(numberFormat, j++);

        if (i < PropsValues.STAGING_REMOTE_TRANSFER_BUFFER_SIZE) {
          byte[] tempBytes = new byte[i];

          System.arraycopy(bytes, 0, tempBytes, 0, i);

          StagingServiceHttp.updateStagingRequest(
              httpPrincipal, stagingRequestId, fileName, tempBytes);
        } else {
          StagingServiceHttp.updateStagingRequest(httpPrincipal, stagingRequestId, fileName, bytes);
        }

        bytes = new byte[PropsValues.STAGING_REMOTE_TRANSFER_BUFFER_SIZE];
      }
    } finally {
      StreamUtil.cleanUp(fileInputStream);
    }
  }
  public String updateAttachments(
      long resourcePrimKey, String dirName, ServiceContext serviceContext)
      throws PortalException, SystemException {

    if (Validator.isNotNull(dirName)) {
      return dirName;
    }

    dirName = "knowledgebase/temp/attachments/" + counterLocalService.increment();

    DLStoreUtil.addDirectory(serviceContext.getCompanyId(), CompanyConstants.SYSTEM, dirName);

    if (resourcePrimKey <= 0) {
      return dirName;
    }

    KBArticle kbArticle = getLatestKBArticle(resourcePrimKey, WorkflowConstants.STATUS_ANY);

    for (String fileName : kbArticle.getAttachmentsFileNames()) {
      String shortFileName = FileUtil.getShortFileName(fileName);

      InputStream inputStream = null;

      try {
        inputStream =
            DLStoreUtil.getFileAsStream(
                kbArticle.getCompanyId(), CompanyConstants.SYSTEM, fileName);

        addAttachment(dirName, shortFileName, inputStream, serviceContext);
      } finally {
        StreamUtil.cleanUp(inputStream);
      }
    }

    return dirName;
  }
Exemple #28
0
  public static void cleanUp(InputStream inputStream, OutputStream outputStream) {

    cleanUp(outputStream);
    cleanUp(inputStream);
  }
Exemple #29
0
 public static void cleanUp(Channel inputChannel, Channel outputChannel) {
   cleanUp(inputChannel);
   cleanUp(outputChannel);
 }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, MBMessage message)
      throws Exception {

    long userId = portletDataContext.getUserId(message.getUserUuid());

    String userName = message.getUserName();

    Map<Long, Long> categoryIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(MBCategory.class);

    long parentCategoryId =
        MapUtil.getLong(categoryIds, message.getCategoryId(), message.getCategoryId());

    Map<Long, Long> threadIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(MBThread.class);

    long threadId = MapUtil.getLong(threadIds, message.getThreadId(), 0);

    Map<Long, Long> messageIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(MBMessage.class);

    long parentMessageId =
        MapUtil.getLong(messageIds, message.getParentMessageId(), message.getParentMessageId());

    Element element = portletDataContext.getImportDataStagedModelElement(message);

    List<ObjectValuePair<String, InputStream>> inputStreamOVPs =
        getAttachments(portletDataContext, element, message);

    try {
      ServiceContext serviceContext =
          portletDataContext.createServiceContext(message, MBPortletDataHandler.NAMESPACE);

      if (message.getStatus() != WorkflowConstants.STATUS_APPROVED) {
        serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
      }

      if ((parentCategoryId != MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID)
          && (parentCategoryId != MBCategoryConstants.DISCUSSION_CATEGORY_ID)
          && (parentCategoryId == message.getCategoryId())) {

        String categoryPath =
            ExportImportPathUtil.getModelPath(
                portletDataContext, MBCategory.class.getName(), parentCategoryId);

        MBCategory category = (MBCategory) portletDataContext.getZipEntryAsObject(categoryPath);

        StagedModelDataHandlerUtil.importStagedModel(portletDataContext, category);

        parentCategoryId =
            MapUtil.getLong(categoryIds, message.getCategoryId(), message.getCategoryId());
      }

      MBMessage importedMessage = null;

      if (portletDataContext.isDataStrategyMirror()) {
        MBMessage existingMessage =
            MBMessageUtil.fetchByUUID_G(message.getUuid(), portletDataContext.getScopeGroupId());

        if (existingMessage == null) {
          serviceContext.setUuid(message.getUuid());

          importedMessage =
              MBMessageLocalServiceUtil.addMessage(
                  userId,
                  userName,
                  portletDataContext.getScopeGroupId(),
                  parentCategoryId,
                  threadId,
                  parentMessageId,
                  message.getSubject(),
                  message.getBody(),
                  message.getFormat(),
                  inputStreamOVPs,
                  message.getAnonymous(),
                  message.getPriority(),
                  message.getAllowPingbacks(),
                  serviceContext);
        } else {
          importedMessage =
              MBMessageLocalServiceUtil.updateMessage(
                  userId,
                  existingMessage.getMessageId(),
                  message.getSubject(),
                  message.getBody(),
                  inputStreamOVPs,
                  new ArrayList<String>(),
                  message.getPriority(),
                  message.getAllowPingbacks(),
                  serviceContext);
        }
      } else {
        importedMessage =
            MBMessageLocalServiceUtil.addMessage(
                userId,
                userName,
                portletDataContext.getScopeGroupId(),
                parentCategoryId,
                threadId,
                parentMessageId,
                message.getSubject(),
                message.getBody(),
                message.getFormat(),
                inputStreamOVPs,
                message.getAnonymous(),
                message.getPriority(),
                message.getAllowPingbacks(),
                serviceContext);
      }

      importedMessage.setAnswer(message.getAnswer());

      if (importedMessage.isRoot()) {
        MBThreadLocalServiceUtil.updateQuestion(
            importedMessage.getThreadId(),
            GetterUtil.getBoolean(element.attributeValue("question")));
      }

      threadIds.put(message.getThreadId(), importedMessage.getThreadId());

      portletDataContext.importClassedModel(
          message, importedMessage, MBPortletDataHandler.NAMESPACE);
    } finally {
      for (ObjectValuePair<String, InputStream> inputStreamOVP : inputStreamOVPs) {

        InputStream inputStream = inputStreamOVP.getValue();

        StreamUtil.cleanUp(inputStream);
      }
    }
  }