Hi All,
I am doing upload asset through below service and written below code.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.json.JSONObject;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.AssetManager;
@Component(service = AssetUploadAPIService.class)
public class AssetUploadAPIServiceImpl implements AssetUploadAPIService {
@reference
transient ResourceResolverFactory resolverFactory;
private transient Map<String, Object> param = new HashMap<>();
private static final Logger LOGGER = LoggerFactory.getLogger(AssetUploadAPIServiceImpl.class);
public AssetUploadAPIServiceImpl() {
param.put(ResourceResolverFactory.SUBSERVICE, "datawrite");
}
private ResourceResolver getResourceResolver() throws LoginException {
return resolverFactory.getServiceResourceResolver(param);
}
@Override
public ServletResponse<String> getAssetUploadResponse(SlingHttpServletRequest request) {
try (ResourceResolver resourceResolver = getResourceResolver()) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
reader.close();
}
LOGGER.info("POST JSON data: {}", sb);
JSONObject jsonObject = new JSONObject(sb.toString());
String assetPath = jsonObject.getString("assetPath");
String mimeType = jsonObject.getString("mimeType");
String encoding = jsonObject.getString("encoding");
String asset = jsonObject.getString("asset");
String imageType = mimeType.split("/")[1];
LOGGER.info("assetPath: {}, mimeType: {}, encoding: {}, asset: {}, imageType: {}", assetPath, mimeType,encoding, asset, imageType);
InputStream targetStream = new ByteArrayInputStream(Base64.getDecoder().decode(asset.getBytes(StandardCharsets.UTF_8)));
AssetManager assetManager = resourceResolver.adaptTo(AssetManager.class);
Asset imageAsset = assetManager.createAsset((assetPath + "." + imageType), targetStream, mimeType, true);
return new ServletResponse<>(ServletResponse.ServletResponseType.RES_200, imageAsset.getPath());
}
catch (Exception e) {
LOGGER.error(String.format("There was an Error === " + e));
return new ServletResponse<>(ServletResponse.ServletResponseType.RES_400, e.getMessage());
}
}
}
Here I am passing as assetpath = "/content/dam/public/assets/test1" , mimetype = "image/png" and encoding = "base64" as part of json object and then test1.png is uploading in the path /content/dam/public/assets
Here I have written below JUNIT test case for this upload asset, but my asset path are not covering. Can anybody please help me here which one I am missing here.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import javax.jcr.Session;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.wrappers.SlingHttpServletRequestWrapper;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.json.JSONException;
import org.junit.Rule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.day.cq.wcm.foundation.forms.FormsHandlingRequest;
import io.wcm.testing.mock.aem.junit5.AemContext;
class AssetUploadAPIServiceImplTest {
@Mock
private ResourceResolverFactory resolverFactory;
@Mock
private Session session;
@Mock
private ResourceResolver resourceResolver;
@Rule
private final AemContext context = new AemContext(ResourceResolverType.JCR_MOCK);
@InjectMocks
private AssetUploadAPIServiceImpl assetUploadAPIService = new AssetUploadAPIServiceImpl();
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
HashMap<String, Object> parameterMap = new HashMap<>();
parameterMap.put("assetPath", "/content/dam/public/assets");
parameterMap.put("mimeType", "image/png");
parameterMap.put("encoding", "base64");
context.request().setParameterMap(parameterMap);
}
@test
void getAssetUploadResponse() throws LoginException, JSONException {
when(resolverFactory.getServiceResourceResolver(any())).thenReturn(resourceResolver);
when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
ServletResponse<String> actualAssetUploadResponse = assetUploadAPIService.getAssetUploadResponse(new FormsHandlingRequest(new SlingHttpServletRequestWrapper(mock(SlingHttpServletRequest.class))));
assertNull(actualAssetUploadResponse.getPayload());
assertEquals(ServletResponse.ServletResponseType.RES_400, actualAssetUploadResponse.getStatus());
}
}
Can anybody please let me know that what I am missing here for the code coverage for below jsonobject part ?
JSONObject jsonObject = new JSONObject(sb.toString()); String assetPath = jsonObject.getString("assetPath"); String mimeType = jsonObject.getString("mimeType"); String encoding = jsonObject.getString("encoding"); String asset = jsonObject.getString("asset"); String imageType = mimeType.split("/")[1]; LOGGER.info("assetPath: {}, mimeType: {}, encoding: {}, asset: {}, imageType: {}", assetPath, mimeType,encoding, asset, imageType); InputStream targetStream = new ByteArrayInputStream(Base64.getDecoder().decode(asset.getBytes(StandardCharsets.UTF_8))); AssetManager assetManager = resourceResolver.adaptTo(AssetManager.class); Asset imageAsset = assetManager.createAsset((assetPath + "." + imageType), targetStream, mimeType, true); return new ServletResponse<>(ServletResponse.ServletResponseType.RES_200, imageAsset.getPath());
Thanks in advance.
snaik
Solved! Go to Solution.
Views
Replies
Total Likes
@subnaik can you try below code
lenient().when(resolver.adaptTo(AssetManager.class)).thenReturn(assetManager);
lenient().when(fileResource.adaptTo(Asset.class)).thenReturn(asset);
JSONObject js = new JSONObject();
js.put("assetPath","/content/dam");
js.put("mimeType", "test");
InputStream in = IOUtils.toInputStream(json.toString(), CharEncoding.UTF_8);
when(conn.getInputStream()).thenReturn(in);
@Jagadeesh_Prakash @TarunKumar @Heidi05 @Mohit_KBansal @Avdhesh-Pandey @VictorToledo @sherinregi @Hafizur-Rahman @Hemant_arora Can you please review this unanswered question? Appreciate your thoughts on this.
Views
Replies
Total Likes
@subnaik can you try below code
lenient().when(resolver.adaptTo(AssetManager.class)).thenReturn(assetManager);
lenient().when(fileResource.adaptTo(Asset.class)).thenReturn(asset);
JSONObject js = new JSONObject();
js.put("assetPath","/content/dam");
js.put("mimeType", "test");
InputStream in = IOUtils.toInputStream(json.toString(), CharEncoding.UTF_8);
when(conn.getInputStream()).thenReturn(in);
Views
Likes
Replies
Views
Likes
Replies
Views
Likes
Replies