Example usage for com.liferay.portal.kernel.util FileUtil getBytes

List of usage examples for com.liferay.portal.kernel.util FileUtil getBytes

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.util FileUtil getBytes.

Prototype

public static byte[] getBytes(InputStream is) throws IOException 

Source Link

Usage

From source file:com.liferay.wsrp.portlet.ConsumerPortlet.java

License:Open Source License

protected Object[] processMultipartForm(PortletRequest portletRequest, PortletResponse portletResponse)
        throws Exception {

    List<NamedString> formParameters = new ArrayList<NamedString>();
    List<UploadContext> uploadContexts = new ArrayList<UploadContext>();

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(portletRequest);

    Enumeration<String> enu = uploadPortletRequest.getParameterNames();

    while (enu.hasMoreElements()) {
        String name = enu.nextElement();

        if (isReservedParameter(name) || name.startsWith("p_p_")) {
            continue;
        }//from   w  ww .ja  v  a2 s .  c  o m

        if (uploadPortletRequest.isFormField(name)) {
            String[] values = uploadPortletRequest.getParameterValues(name);

            if (values == null) {
                continue;
            }

            addFormField(formParameters, name, values);
        } else {
            UploadContext uploadContext = new UploadContext();

            String contentType = uploadPortletRequest.getContentType(name);

            uploadContext.setMimeType(contentType);

            StringBuilder sb = new StringBuilder();

            sb.append("form-data; ");
            sb.append("name=");
            sb.append(name);
            sb.append("; filename=");
            sb.append(uploadPortletRequest.getFileName(name));

            NamedString mimeAttribute = new NamedString();

            mimeAttribute.setName(HttpHeaders.CONTENT_DISPOSITION);
            mimeAttribute.setValue(sb.toString());

            uploadContext.setMimeAttributes(new NamedString[] { mimeAttribute });

            File file = uploadPortletRequest.getFile(name);

            byte[] bytes = FileUtil.getBytes(file);

            if (bytes == null) {
                continue;
            }

            uploadContext.setUploadData(bytes);

            uploadContexts.add(uploadContext);
        }
    }

    return new Object[] { formParameters, uploadContexts };
}

From source file:com.rknowsys.eapp.DataImportAction.java

/**
 * This method saves uploaded file into the server folder.And stores the
 * file data into the database.//from   w  w  w .j  a v  a  2  s  .  com
 * 
 * @param actionRequest
 * @param actionResponse
 * @throws IOException
 */
public void saveDataImport(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException {
    System.out.println("saveDataImport method()..!!!!!!!!!!");
    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    Properties properties = PortalUtil.getPortalProperties();
    String uploadDirectory = properties.getProperty("liferay.home") + "/data/uploadedFiles";
    UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
    byte[] bytes = null;

    try {
        // ==========Saving the uploaded file in server folder with uploaded
        // date and time as file filename prefix.===========

        Date date = new Date();
        SimpleDateFormat sd = new SimpleDateFormat("mm-dd-yyyy");
        String d = sd.format(date);
        System.out.println("uploaded date = " + d);
        File uploadedFile = uploadRequest.getFile("fileName");

        bytes = FileUtil.getBytes(uploadedFile);

        String fileName = uploadRequest.getFileName("fileName");
        File newFile = null;
        File newDirectory = new File(uploadDirectory);
        if (!newDirectory.exists()) {
            System.out.println("directory does not exist");
            Path directoryPath = Paths.get(uploadDirectory);
            Files.createDirectory(directoryPath.getParent());
        }
        newFile = new File(uploadDirectory + "/" + d + Calendar.getInstance().getTimeInMillis() + fileName);

        // ============Creating the New file in server folder===========

        if (!newFile.exists()) {
            System.out.println("file does not exist");
            Path pathToFile = Paths
                    .get(uploadDirectory + "/" + d + Calendar.getInstance().getTimeInMillis() + fileName);
            Files.createFile(pathToFile);

        }
        // =========Reading the uploaded file content and writing the
        // content to newly created file==============
        FileInputStream fileInputStream = new FileInputStream(uploadedFile);

        fileInputStream.read(bytes);
        FileOutputStream fileOutputStream = new FileOutputStream(newFile);
        fileOutputStream.write(bytes, 0, bytes.length);
        fileOutputStream.close();
        fileInputStream.close();

        String filePath = newFile.getAbsolutePath();
        System.out.println("filePath = " + filePath);

        FileInputStream file1 = new FileInputStream(new File(filePath));

        // Reading Excel file Rows and cells content using apache poi api
        // and saving the data in to the database.

        XSSFWorkbook workbook = new XSSFWorkbook(file1); // Create Workbook
        // instance
        // holding
        // reference to
        // .xlsx file

        XSSFSheet sheet = workbook.getSheetAt(0); // Get first/desired sheet
        // from the workbook

        @SuppressWarnings("rawtypes")
        Iterator rows = sheet.rowIterator(); // Iterate through each rows
        // one by one

        while (rows.hasNext()) {

            XSSFRow row = (XSSFRow) rows.next();
            if (row.getRowNum() != 0) {
                EmpPersonalDetails empPersonalDetails = EmpPersonalDetailsLocalServiceUtil
                        .createEmpPersonalDetails(CounterLocalServiceUtil.increment());
                Employee employee = EmployeeLocalServiceUtil
                        .createEmployee(CounterLocalServiceUtil.increment());
                JobTitle jobTitle = JobTitleLocalServiceUtil
                        .createJobTitle(CounterLocalServiceUtil.increment());
                SubUnit subUnit = SubUnitLocalServiceUtil.createSubUnit(CounterLocalServiceUtil.increment());
                EmploymentStatus employmentStatus = EmploymentStatusLocalServiceUtil
                        .createEmploymentStatus(CounterLocalServiceUtil.increment());
                EmpJob empJob = EmpJobLocalServiceUtil.createEmpJob(CounterLocalServiceUtil.increment());
                EmpSupervisor empSupervisor = EmpSupervisorLocalServiceUtil
                        .createEmpSupervisor(CounterLocalServiceUtil.increment());
                @SuppressWarnings("rawtypes")
                Iterator cells = row.cellIterator();

                while (cells.hasNext()) {

                    XSSFCell cell = (XSSFCell) cells.next();
                    if (cell.getColumnIndex() == 0) {
                        empPersonalDetails.setFirstName(cell.toString());
                    }
                    if (cell.getColumnIndex() == 1) {
                        empPersonalDetails.setMiddleName(cell.toString());
                    }
                    if (cell.getColumnIndex() == 2) {
                        empPersonalDetails.setLastName(cell.toString());
                    }
                    if (cell.getColumnIndex() == 3) {
                        empPersonalDetails.setEmployeeNo(cell.getRawValue());
                    }
                    if (cell.getColumnIndex() == 4) {
                        empPersonalDetails.setLicenseNo(cell.getRawValue());
                    }
                    if (cell.getColumnIndex() == 5) {
                        jobTitle.setTitle(cell.toString());
                    }
                    if (cell.getColumnIndex() == 6) {
                        employmentStatus.setEmploymentstatus(cell.toString());
                    }
                    if (cell.getColumnIndex() == 7) {
                        subUnit.setName(cell.toString());
                    }

                }
                employee.setUserId(themeDisplay.getUserId());
                employee.setGroupId(themeDisplay.getCompanyGroupId());
                employee.setCompanyId(themeDisplay.getCompanyId());
                employee.setCreateDate(date);
                employee.setModifiedDate(date);
                employee = EmployeeLocalServiceUtil.addEmployee(employee);

                empPersonalDetails.setUserId(themeDisplay.getUserId());
                empPersonalDetails.setGroupId(themeDisplay.getCompanyGroupId());
                empPersonalDetails.setCompanyId(themeDisplay.getCompanyId());
                empPersonalDetails.setCreateDate(date);
                empPersonalDetails.setModifiedDate(date);
                empPersonalDetails.setEmployeeId(employee.getEmployeeId());
                empPersonalDetails = EmpPersonalDetailsLocalServiceUtil
                        .addEmpPersonalDetails(empPersonalDetails);

                jobTitle.setUserId(themeDisplay.getUserId());
                jobTitle.setGroupId(themeDisplay.getCompanyGroupId());
                jobTitle.setCompanyId(themeDisplay.getCompanyId());
                jobTitle.setCreateDate(date);
                jobTitle.setModifiedDate(date);
                jobTitle = JobTitleLocalServiceUtil.addJobTitle(jobTitle);

                subUnit.setUserId(themeDisplay.getUserId());
                subUnit.setGroupId(themeDisplay.getCompanyGroupId());
                subUnit.setCompanyId(themeDisplay.getCompanyId());
                subUnit.setCreateDate(date);
                subUnit.setModifiedDate(date);
                subUnit = SubUnitLocalServiceUtil.addSubUnit(subUnit);

                employmentStatus.setUserId(themeDisplay.getUserId());
                employmentStatus.setGroupId(themeDisplay.getCompanyGroupId());
                employmentStatus.setCompanyId(themeDisplay.getCompanyId());
                employmentStatus.setCreateDate(date);
                employmentStatus.setModifiedDate(date);
                employmentStatus = EmploymentStatusLocalServiceUtil.addEmploymentStatus(employmentStatus);

                empJob.setJobTitleId(employee.getEmployeeId());
                empJob.setEmploymentStatusId(employmentStatus.getEmploymentStatusId());
                empJob.setSubUnitId(subUnit.getSubUnitId());
                empJob.setUserId(themeDisplay.getUserId());
                empJob.setGroupId(themeDisplay.getCompanyGroupId());
                empJob.setCompanyId(themeDisplay.getCompanyId());
                empJob.setCreateDate(date);
                empJob.setModifiedDate(date);
                empJob.setEmployeeId(employee.getEmployeeId());
                empJob = EmpJobLocalServiceUtil.addEmpJob(empJob);

                empSupervisor.setUserId(themeDisplay.getUserId());
                empSupervisor.setGroupId(themeDisplay.getCompanyGroupId());
                empSupervisor.setCompanyId(themeDisplay.getCompanyId());
                empSupervisor.setCreateDate(date);
                empSupervisor.setModifiedDate(date);
                empSupervisor.setEmployeeId(employee.getEmployeeId());
                empSupervisor.setReporterEmployeeId(empPersonalDetails.getEmployeeId());
                empSupervisor = EmpSupervisorLocalServiceUtil.addEmpSupervisor(empSupervisor);
            }

        }
        file1.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

License:Open Source License

protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers,
        Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts,
        Map<String, String> parts, Http.Response response, boolean followRedirects, String progressId,
        PortletRequest portletRequest) throws IOException {

    byte[] bytes = null;

    HttpMethod httpMethod = null;//  w ww  .  j  a v a 2  s  .  co  m
    HttpState httpState = null;

    try {
        _cookies.set(null);

        if (location == null) {
            return null;
        } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) {

            location = Http.HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfiguration = getHostConfiguration(location);

        HttpClient httpClient = getClient(hostConfiguration);

        if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) {

            if (method.equals(Http.Method.POST)) {
                httpMethod = new PostMethod(location);
            } else {
                httpMethod = new PutMethod(location);
            }

            if (body != null) {
                RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(),
                        body.getCharset());

                EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;

                entityEnclosingMethod.setRequestEntity(requestEntity);
            } else if (method.equals(Http.Method.POST)) {
                PostMethod postMethod = (PostMethod) httpMethod;

                if (!hasRequestHeader(postMethod, HttpHeaders.CONTENT_TYPE)) {

                    HttpClientParams httpClientParams = httpClient.getParams();

                    httpClientParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, StringPool.UTF8);
                }

                processPostMethod(postMethod, fileParts, parts);
            }
        } else if (method.equals(Http.Method.DELETE)) {
            httpMethod = new DeleteMethod(location);
        } else if (method.equals(Http.Method.HEAD)) {
            httpMethod = new HeadMethod(location);
        } else {
            httpMethod = new GetMethod(location);
        }

        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }
        }

        if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null)
                || ((fileParts != null) && !fileParts.isEmpty()) || ((parts != null) && !parts.isEmpty()))) {
        } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) {
            httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE,
                    ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED_UTF8);
        }

        if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) {
            httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT);
        }

        httpState = new HttpState();

        if (ArrayUtil.isNotEmpty(cookies)) {
            org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies);

            httpState.addCookies(commonsCookies);

            HttpMethodParams httpMethodParams = httpMethod.getParams();

            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        if (auth != null) {
            httpMethod.setDoAuthentication(true);

            httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()),
                    new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
        }

        proxifyState(httpState, hostConfiguration);

        int responseCode = httpClient.executeMethod(hostConfiguration, httpMethod, httpState);

        response.setResponseCode(responseCode);

        Header locationHeader = httpMethod.getResponseHeader("location");

        if ((locationHeader != null) && !locationHeader.equals(location)) {
            String redirect = locationHeader.getValue();

            if (followRedirects) {
                return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts,
                        response, followRedirects, progressId, portletRequest);
            } else {
                response.setRedirect(redirect);
            }
        }

        InputStream inputStream = httpMethod.getResponseBodyAsStream();

        if (inputStream != null) {
            int contentLength = 0;

            Header contentLengthHeader = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH);

            if (contentLengthHeader != null) {
                contentLength = GetterUtil.getInteger(contentLengthHeader.getValue());

                response.setContentLength(contentLength);
            }

            Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE);

            if (contentType != null) {
                response.setContentType(contentType.getValue());
            }

            if (Validator.isNotNull(progressId) && (portletRequest != null)) {

                ProgressInputStream progressInputStream = new ProgressInputStream(portletRequest, inputStream,
                        contentLength, progressId);

                UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream(
                        contentLength);

                try {
                    progressInputStream.readAll(unsyncByteArrayOutputStream);
                } finally {
                    progressInputStream.clearProgress();
                }

                bytes = unsyncByteArrayOutputStream.unsafeGetByteArray();

                unsyncByteArrayOutputStream.close();
            } else {
                bytes = FileUtil.getBytes(inputStream);
            }
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            response.addHeader(header.getName(), header.getValue());
        }

        return bytes;
    } finally {
        try {
            if (httpState != null) {
                _cookies.set(toServletCookies(httpState.getCookies()));
            }
        } catch (Exception e) {
            _log.error(e, e);
        }

        try {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        } catch (Exception e) {
            _log.error(e, e);
        }
    }
}

From source file:com.vportal.portlet.vcms.service.impl.VcmsArticleServiceImpl.java

License:Open Source License

public void saveImage(ActionRequest req, UploadPortletRequest uploadReq, VcmsArticle article, String image,
        String imageTitle, long companyId) throws Exception {

    /*UploadPortletRequest uploadReq = PortalUtil
    .getUploadPortletRequest(req);*/

    // Image.../*from  ww  w.  j  a  va 2 s .c om*/
    if ((article != null) && Validator.isNotNull(image)) {

        // Validate the image input
        String contentType = uploadReq.getContentType("image");
        if (ImageUtilExt.isImage(contentType)) {

            String imageKey = WebKeysExt.VCMS_ARTICLE_IMAGE_KEY + article.getArticleId();
            String smallImageKey = WebKeysExt.VCMS_ARTICLE_SMALL_IMAGE_KEY + article.getArticleId();

            int thumbnailMaxWidth = GetterUtil.getInteger(
                    PrefsPropsUtil.getString(companyId, PropsUtilExt.VCMS_ARTICLE_THUMB_IMAGE_WIDTH), 100);
            int thumbnailMaxHeight = GetterUtil.getInteger(
                    PrefsPropsUtil.getString(companyId, PropsUtilExt.VCMS_ARTICLE_THUMB_IMAGE_HEIGHT), 100);

            File fileImage = uploadReq.getFile("image");

            if (fileImage != null) {

                byte[] photoBytes = FileUtil.getBytes(fileImage);
                ImageUtilExt.saveOriginalImage(Long.parseLong(imageKey), photoBytes);

                // Also, save a scaled version of the image
                ByteArrayInputStream bais = new ByteArrayInputStream(photoBytes);
                ImageUtilExt.saveThumbnail(Long.parseLong(smallImageKey), ImageIO.read(bais), contentType,
                        thumbnailMaxWidth, thumbnailMaxHeight);

                // Update the article when the image is saved
                article.setHasImage(true);
                article.setImage(imageKey);
                article.setImageTitle(Validator.isNull(imageTitle) ? StringPool.BLANK : imageTitle);
            }
        }
    }
}

From source file:de.fraunhofer.fokus.movepla.service.impl.ApplicationLocalServiceImpl.java

License:Open Source License

public Application addApplication(Application application, File imageFile)
        throws SystemException, PortalException {
    try {//  w ww . j a  v a  2s. c  o m
        long applicationID = CounterLocalServiceUtil.increment(Application.class.getName());

        Application model = applicationPersistence.create(applicationID);
        model.setCompanyId(application.getCompanyId());
        model.setCreateDate(new Date());
        model.setDescription(application.getDescription());
        model.setFee(application.getFee());
        model.setLifeCycleStatus(Constants.APPLICATION_STATUS_SUBMITTED);
        //      model.setLifeCycleStatusString("neu erstellt - warten auf Freigabe");

        try {
            _log.debug("imageFile.getName(): " + imageFile.getName());
            byte[] imageBytes = null;
            imageBytes = FileUtil.getBytes(imageFile);
            if (imageBytes != null) {
                _log.debug("addApplication::imageBytes.length: " + imageBytes.length);
                if (imageBytes.length > 0) {
                    model.setLogoImageId(counterLocalService.increment());
                    saveImages(model.getLogoImageId(), imageFile, imageBytes);
                }

            } else {
                _log.debug("addApplication::imageBytes == null! ");
            }
        } catch (Exception e) {
            _log.debug("Exception: " + e.getMessage());
            e.printStackTrace();
        }
        model.setMinTargetOSVersion(application.getMinTargetOSVersion());
        model.setModifiedDate(new Date());
        model.setName(application.getName());
        model.setSize(application.getSize());
        model.setTargetOS(application.getTargetOS());
        model.setUserId(application.getUserId());
        //      model.setVerifiedDate(application.getVerifiedDate());
        model.setVersion(application.getVersion());
        model.setVersionInformation(application.getVersionInformation());

        model.setTargetCategory(application.getTargetCategory());
        model.setDeveloper(application.getDeveloper());
        model.setFirstPublishingDate(application.getFirstPublishingDate());
        model.setLastModifiedDate(application.getLastModifiedDate());
        model.setLegalDetails(application.getLegalDetails());

        // Indexer
        Indexer indexer = IndexerRegistryUtil.getIndexer(Application.class);
        indexer.reindex(model);
        Application res = applicationPersistence.update(model, true);
        _log.debug("getApplicationId: " + res.getApplicationId());
        _log.debug("getCompanyId: " + res.getCompanyId());
        return res;
    } catch (Exception e) {
        _log.debug("Exception: " + e.getMessage());
        e.printStackTrace();
    }
    return null;
}

From source file:de.fraunhofer.fokus.movepla.service.impl.ApplicationLocalServiceImpl.java

License:Open Source License

public Application addApplication(Application application, File imageFile, List<Category> categories,
        List<Language> languages, List<Region> regions) throws SystemException, PortalException {
    try {//  w  w w .  j a va  2s  .  co m
        long applicationID = CounterLocalServiceUtil.increment(Application.class.getName());

        Application model = applicationPersistence.create(applicationID);
        model.setCompanyId(application.getCompanyId());
        model.setCreateDate(new Date());
        model.setDescription(application.getDescription());
        model.setFee(application.getFee());
        model.setTargetCategory(application.getTargetCategory());
        model.setDeveloper(application.getDeveloper());
        model.setFirstPublishingDate(application.getFirstPublishingDate());
        model.setLastModifiedDate(application.getLastModifiedDate());
        model.setLifeCycleStatus(Constants.APPLICATION_STATUS_SUBMITTED);
        //      model.setLifeCycleStatusString("neu erstellt - warten auf Freigabe");
        try {
            _log.debug("imageFile.getName(): " + imageFile.getName());
            byte[] imageBytes = null;
            imageBytes = FileUtil.getBytes(imageFile);
            _log.debug("addApplication::imageBytes.length: " + imageBytes.length);
            if (imageBytes.length > 0) {
                model.setLogoImageId(counterLocalService.increment());
                saveImages(model.getLogoImageId(), imageFile, imageBytes);
            }
        } catch (Exception e) {
            _log.debug("Exception: " + e.getMessage());
        }
        _log.debug("addApplication::model.getLogoImageId(): " + model.getLogoImageId());
        model.setMinTargetOSVersion(application.getMinTargetOSVersion());
        model.setModifiedDate(new Date());
        model.setName(application.getName());
        model.setSize(application.getSize());
        model.setTargetOS(application.getTargetOS());
        model.setUserId(application.getUserId());
        //      model.setVerifiedDate(application.getVerifiedDate());
        model.setVersion(application.getVersion());
        model.setVersionInformation(application.getVersionInformation());

        Application _app = applicationPersistence.update(model, true);
        applicationPersistence.addCategories(_app.getApplicationId(), categories);
        applicationPersistence.addLanguages(_app.getApplicationId(), languages);
        applicationPersistence.addRegions(_app.getApplicationId(), regions);

        return _app;
    } catch (Exception e) {
        _log.debug("Exception: " + e.getMessage());
        e.printStackTrace();
    }
    return null;
}

From source file:de.fraunhofer.fokus.movepla.service.impl.ApplicationLocalServiceImpl.java

License:Open Source License

public Application updateApplication(Application application, File imageFile)
        throws SystemException, PortalException {

    Application model = applicationPersistence.fetchByPrimaryKey(application.getApplicationId());
    model.setCompanyId(application.getCompanyId());
    //      model.setCreateDate(new Date());
    model.setDescription(application.getDescription());
    model.setFee(application.getFee());/*from ww w .  j a  v a2  s.com*/
    model.setTargetCategory(application.getTargetCategory());
    model.setDeveloper(application.getDeveloper());
    model.setFirstPublishingDate(application.getFirstPublishingDate());
    model.setLastModifiedDate(application.getLastModifiedDate());
    model.setLifeCycleStatus(application.getLifeCycleStatus());
    //      model.setLifeCycleStatusString("gendert - warten auf Freigabe");

    try {
        _log.debug("imageFile.getName(): " + imageFile.getName());
        byte[] imageBytes = null;
        imageBytes = FileUtil.getBytes(imageFile);

        if (imageBytes != null) {
            _log.debug("updateApplication::imageBytes.length: " + imageBytes.length);
            if (imageBytes.length > 0) {
                model.setLogoImageId(counterLocalService.increment());
                saveImages(model.getLogoImageId(), imageFile, imageBytes);
            } else {
                _log.debug("updateApplication::imageBytes.length == 0");
                _log.debug("model.getLogoImageId(): " + model.getLogoImageId());
                //               model.setLogoImageId(model.getLogoImageId());
            }
        } else {
            _log.debug("updateApplication::imageBytes == null! ");
            _log.debug("model.getLogoImageId(): " + model.getLogoImageId());
            //            model.setLogoImageId(model.getLogoImageId());
        }
    } catch (Exception e) {
        _log.debug(e.getMessage());
    }
    _log.debug("model.getLogoImageId(): " + model.getLogoImageId());
    model.setMinTargetOSVersion(application.getMinTargetOSVersion());
    model.setModifiedDate(new Date());
    model.setName(application.getName());
    model.setSize(application.getSize());
    model.setTargetOS(application.getTargetOS());
    model.setUserId(application.getUserId());
    if (application.getLifeCycleStatus() >= Constants.APPLICATION_STATUS_VERIFIED) {
        model.setVerifiedDate(application.getVerifiedDate());
    }
    model.setVersion(application.getVersion());
    model.setVersionInformation(application.getVersionInformation());
    model.setLegalDetails(application.getLegalDetails());
    // Indexer
    Indexer indexer = IndexerRegistryUtil.getIndexer(Application.class);
    indexer.reindex(model);
    model = applicationPersistence.update(model, true);
    _log.debug("model.getLogoImageId(): " + model.getLogoImageId());
    return model;
}

From source file:de.fraunhofer.fokus.movepla.service.impl.MultiMediaLocalServiceImpl.java

License:Open Source License

public MultiMedia addMultiMedia(MultiMedia multiMedia, File imageFile) throws SystemException, PortalException {
    long multiMediaId = CounterLocalServiceUtil.increment(MultiMedia.class.getName());
    MultiMedia model = multiMediaPersistence.create(multiMediaId);
    model.setUserId(multiMedia.getUserId());
    model.setCompanyId(multiMedia.getCompanyId());
    model.setCreateDate(new Date());
    model.setModifiedDate(new Date());
    model.setApplicationId(multiMedia.getApplicationId());
    model.setName(multiMedia.getName());
    model.setType(multiMedia.getType());
    try {//  w w w . j  a v  a  2  s  . c  om

        //         DLAppLocalServiceUtil.addFileEntry(userId, repositoryId, folderId, sourceFileName, mimeType, title, description, changeLog, imageFile, serviceContext);
        //         DLAppLocalServiceUtil.addFileEntry(userId, repositoryId, folderId, imageFile.getName(), mimeType, title, description, changeLog, imageFile, serviceContext);
        byte[] imageBytes = null;
        imageBytes = FileUtil.getBytes(imageFile);
        model.setImageId(counterLocalService.increment());
        _log.debug("addLink::imageBytes.length: " + imageBytes.length);
        saveImages(model.getImageId(), imageFile, imageBytes);
    } catch (Exception e) {
        _log.info(e.toString());
    }
    return multiMediaPersistence.update(model, true);
}

From source file:de.fraunhofer.fokus.movepla.service.impl.MultiMediaLocalServiceImpl.java

License:Open Source License

public MultiMedia updateMultiMedia(MultiMedia multiMedia, File imageFile) throws SystemException {
    MultiMedia model = multiMediaPersistence.fetchByPrimaryKey(multiMedia.getMultiMediaId());
    model.setUserId(multiMedia.getUserId());
    model.setCompanyId(multiMedia.getCompanyId());
    model.setApplicationId(multiMedia.getApplicationId());
    model.setType(multiMedia.getType());
    model.setModifiedDate(new Date());
    try {//from   w w  w.j av a2s . c o  m
        byte[] imageBytes = null;
        imageBytes = FileUtil.getBytes(imageFile);
        model.setImageId(counterLocalService.increment());
        _log.debug("addLink::imageBytes.length: " + imageBytes.length);
        _log.debug("imageFile.getName(): " + imageFile.getName());
        model.setName(imageFile.getName());

        saveImages(model.getImageId(), imageFile, imageBytes);
    } catch (Exception e) {
        _log.info(e.toString());
    }
    return multiMediaPersistence.update(model, true);
}

From source file:fr.smile.socialnetworking.meetups.portlet.MeetupsPortlet.java

License:Open Source License

public void updateMeetupsEntry(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);

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

    Group group = GroupLocalServiceUtil.getGroup(themeDisplay.getScopeGroupId());

    PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();

    if (!permissionChecker.isCompanyAdmin()) {
        return;/*  w w w .  j  av a  2  s .  co m*/
    }

    long meetupsEntryId = ParamUtil.getLong(uploadRequest, "meetupsEntryId");

    String title = ParamUtil.getString(uploadRequest, "title");
    String description = ParamUtil.getString(uploadRequest, "description");

    int startDateMonth = ParamUtil.getInteger(uploadRequest, "startDateMonth");
    int startDateDay = ParamUtil.getInteger(uploadRequest, "startDateDay");
    int startDateYear = ParamUtil.getInteger(uploadRequest, "startDateYear");
    int startDateHour = ParamUtil.getInteger(uploadRequest, "startDateHour");
    int startDateMinute = ParamUtil.getInteger(uploadRequest, "startDateMinute");
    int startDateAmPm = ParamUtil.getInteger(uploadRequest, "startDateAmPm");

    if (startDateAmPm == Calendar.PM) {
        startDateHour += 12;
    }

    int endDateMonth = ParamUtil.getInteger(uploadRequest, "endDateMonth");
    int endDateDay = ParamUtil.getInteger(uploadRequest, "endDateDay");
    int endDateYear = ParamUtil.getInteger(uploadRequest, "endDateYear");
    int endDateHour = ParamUtil.getInteger(uploadRequest, "endDateHour");
    int endDateMinute = ParamUtil.getInteger(uploadRequest, "endDateMinute");
    int endDateAmPm = ParamUtil.getInteger(uploadRequest, "endDateAmPm");

    if (endDateAmPm == Calendar.PM) {
        endDateHour += 12;
    }

    int totalAttendees = ParamUtil.getInteger(uploadRequest, "totalAttendees");
    int maxAttendees = ParamUtil.getInteger(uploadRequest, "maxAttendees");
    double price = ParamUtil.getDouble(uploadRequest, "price");

    File file = uploadRequest.getFile("fileName");
    byte[] bytes = FileUtil.getBytes(file);

    if (meetupsEntryId <= 0) {
        MeetupsEntryLocalServiceUtil.addMeetupsEntry(themeDisplay.getUserId(), title, description,
                startDateMonth, startDateDay, startDateYear, startDateHour, startDateMinute, endDateMonth,
                endDateDay, endDateYear, endDateHour, endDateMinute, totalAttendees, maxAttendees, price, bytes,
                group.getGroupId());
    } else {
        MeetupsEntryLocalServiceUtil.updateMeetupsEntry(themeDisplay.getUserId(), meetupsEntryId, title,
                description, startDateMonth, startDateDay, startDateYear, startDateHour, startDateMinute,
                endDateMonth, endDateDay, endDateYear, endDateHour, endDateMinute, totalAttendees, maxAttendees,
                price, bytes, group.getGroupId());
    }
}