com.ezsource_mobile.fileservice.FileService.java Source code

Java tutorial

Introduction

Here is the source code for com.ezsource_mobile.fileservice.FileService.java

Source

/*Copyright (c) 2015-2016 gmail.com All Rights Reserved.
 This software is the confidential and proprietary information of gmail.com You shall not disclose such Confidential Information and shall use it only in accordance
 with the terms of the source code license agreement you entered into with gmail.com*/
package com.ezsource_mobile.fileservice;

import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.ezsource_mobile.appcontext.AppContext;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonCreator.Mode;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.wavemaker.runtime.data.dao.query.WMQueryExecutor;
import com.wavemaker.runtime.data.model.queries.RuntimeQuery;
import com.wavemaker.runtime.security.SecurityService;
import com.wavemaker.runtime.service.annotations.ExposeToClient;

@ExposeToClient
public class FileService {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileService.class);

    @Autowired
    private AppContext appContext;

    @Autowired
    private SecurityService securityService;

    @Autowired
    @Qualifier("rfxdbWMQueryExecutor")
    private WMQueryExecutor wmQueryExecutor;

    public static class FileUploadResponse {

        private String path;
        private String fileName;
        private long length;

        private boolean success;
        private String errorMessage;

        @JsonCreator(mode = Mode.PROPERTIES)
        public FileUploadResponse(@JsonProperty("path") String path, @JsonProperty("name") String name,
                @JsonProperty("length") long length, @JsonProperty("success") boolean success,
                @JsonProperty("errorMessage") String errorMessage) {
            this.path = path;
            this.fileName = name;
            this.length = length;
            this.success = success;
            this.errorMessage = errorMessage;
        }

        public boolean isSuccess() {
            return success;
        }

        public void setSuccess(boolean success) {
            this.success = success;
        }

        public long getLength() {
            return length;
        }

        public void setLength(int length) {
            this.length = length;
        }

        public String getErrorMessage() {
            return errorMessage;
        }

        public void setErrorMessage(String errorMessage) {
            this.errorMessage = errorMessage;
        }

        public String getPath() {
            return this.path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public String getFileName() {
            return fileName;
        }
    }

    public FileUploadResponse[] uploadFile(final MultipartFile[] files, final String relativePath,
            final HttpServletRequest httpServletRequest) {
        LOGGER.debug("start of uploadFile method");

        final RestTemplate restTemplate = new RestTemplate();
        FileUploadResponse[] result;
        try {
            final String url = getFileUploadUrl(httpServletRequest);
            final String fileName = files[0].getOriginalFilename();

            final LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
            final ByteArrayResource contentsAsResource = new ByteArrayResource(files[0].getBytes()) {
                @Override
                public String getFilename() {
                    return fileName;
                }
            };
            body.add("files", contentsAsResource);

            final HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            headers.add("Authorization",
                    "Basic " + Base64.encodeBase64String(new StringBuilder(securityService.getUserName())
                            .append(":").append(getHash()).toString().getBytes()));

            final HttpEntity<LinkedMultiValueMap<String, Object>> request = new HttpEntity<LinkedMultiValueMap<String, Object>>(
                    body, headers);
            result = restTemplate.postForObject(url, request, FileUploadResponse[].class);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        LOGGER.debug("end of uploadFile method" + result);
        return result;

    }

    private String getFileUploadUrl(final HttpServletRequest httpServletRequest) {
        String url = appContext.getAppContextPath(httpServletRequest);
        if (url.contains("www.sourcerfx.com")) {
            url = "http://www.sourcerfx.com/ezsource";
        } else {
            url = "http://e1d52cddba11.cloud.wavemakeronline.com/ezsource";
        }
        return url + "/services/file/uploadFile";
    }

    @SuppressWarnings("unchecked")
    private String getHash() {
        final RuntimeQuery query = new RuntimeQuery();
        query.setQueryString("SELECT password FROM User WHERE user_id=" + securityService.getUserId());
        final List<Object> result = wmQueryExecutor.executeRuntimeQuery(query, new PageRequest(0, 1)).getContent();
        if (result == null || result.isEmpty()) {
            LOGGER.error("User not found");
            throw new RuntimeException("User not found");
        }
        return ((LinkedHashMap<String, String>) result.get(0)).get("0");
    }

}