How should I increase the test coverage for this apex controller class - apex

How do I make coverage more than 75% using apex test class for this controller class. I try to write test class for this but, I'm not able to make its coverage as 75 or above 75. I am tried to cover its second method but its covers only 1 line of its try block i.e. Id recordId = hostId; Other part of code is not covered. It is only cover its catch block. So could you help me to make its coverage more than 75.
public with sharing class DocumentSelectorController {
#AuraEnabled(cacheable = true)
public static List<dmpl__CreateRelatedSetting__mdt> getCreateRelatedSettings(string objectApiName)
{
try {
return CreateRelatedSettingHelper.getCreateRelatedSettings(objectApiName);
} catch (Exception error) {
ExceptionLogHelper.logException(error);
throw error;
}
}
#AuraEnabled
public static List<SObject> getChildObjects(
Id recordSettingId,
Id hostId,
String searchKey)
{
try {
Id recordId = hostId;
return Database.query(
CreateRelatedSettingHelper.getSOQLQuery(
CreateRelatedSettingHelper.getCreateRelatedSetting(recordSettingId),
searchKey,
hostId
)
) ;
} catch (Exception error) {
ExceptionLogHelper.logException(error);
throw error;
}
}
#AuraEnabled
public static CreateRelatedResult releaseDocument(
Id recordSettingId,
Id hostId)
{
try {
dmpl__CreateRelatedSetting__mdt recordSetting = CreateRelatedSettingHelper.getCreateRelatedSetting(recordSettingId);
switch on recordSetting.dmpl__HostObjectId__r.QualifiedApiName {
when 'dmpl__SaleOrder__c'{
if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__InventoryFulfillment__c'){
return FulfillmentHelper.createFulfillmentFromSaleOrder(hostId);
}else if(recordSetting.dmpl__Tag__c == 'OTC' && recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__SaleInvoice__c'){
return SaleInvoiceHelper.createSaleInvoiceFromSaleOrder(hostId);
}else if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__SaleInvoice__c'){
return SaleInvoiceHelper.createSaleInvoiceFromAllocatedLines(hostId);
}
}
when 'dmpl__InventoryFulfillment__c'{
if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__InventoryFulfillment__c'){
return InventoryFulfillmentAllocationLineHelper.createAllocationFromFulfillment(hostId);
} else if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__DeliveryOrder__c'){
return SaleDeliveryHelper.createSaleDeliveryFromFulfillment(hostId);
}
}
when 'dmpl__PurchaseReturn__c'{
if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__DeliveryOrder__c'){
return SaleDeliveryHelper.createSaleDeliveryFromPurchaseReturn(hostId);
}
}
}
return new CreateRelatedResult('No handler attached');
} catch (Exception error) {
ExceptionLogHelper.logException(error);
throw error;
}
}
#AuraEnabled
public static CreateRelatedResult releaseChildDocuments(
Id hostId,
Id recordSettingId,
List<SourceObjectInfo> childObjectsInfo)
{
try {
dmpl__CreateRelatedSetting__mdt recordSetting = CreateRelatedSettingHelper.getCreateRelatedSetting(recordSettingId);
switch on recordSetting.dmpl__HostObjectId__r.QualifiedApiName {
when 'dmpl__SaleOrder__c'{
if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__InventoryFulfillment__c'){
return FulfillmentHelper.createFulfillmentFromSaleOrder(childObjectsInfo);
}
else if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__SaleInvoice__c'){
if(recordSetting.dmpl__Tag__c == 'OTC')
return SaleInvoiceHelper.createSaleInvoiceFromSaleOrder(childObjectsInfo);
else
return SaleInvoiceHelper.createSaleInvoiceFromAllocatedLines(childObjectsInfo);
} else if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__PurchaseOrder__c'){
return SaleOrderLineHelper.createSaleOrderLinesFromPurchaseOrder(childObjectsInfo, hostId);
}
}
when 'dmpl__InventoryFulfillment__c'{
if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__SaleOrder__c'){
return FulfillmentHelper.populateFulfillmentFromSaleOrder(childObjectsInfo, hostId);
} else if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__InventoryFulfillment__c'){
return InventoryFulfillmentAllocationLineHelper.createAllocationFromFulfillment(childObjectsInfo);
} else if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__DeliveryOrder__c'){
return SaleDeliveryHelper.createSaleDeliveryFromFulfillment(childObjectsInfo);
}
}
when 'dmpl__SaleReturn__c'{
if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__SaleInvoice__c'){
return SaleReturnHelper.createSaleReturnFromSaleInvoice(childObjectsInfo, hostId);
}
}
when 'dmpl__PurchaseReturn__c'{
if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__Bill__c'){
return PurchaseReturnHelper.createPurchaseReturnFromPurchaseInvoice(childObjectsInfo, hostId);
} else if(recordSetting.dmpl__RelatedObjectId__r.QualifiedApiName == 'dmpl__DeliveryOrder__c'){
return SaleDeliveryHelper.createSaleDeliveryFromPurchaseReturn(childObjectsInfo);
}
}
}
return new CreateRelatedResult('No handler attached');
} catch (Exception error) {
}
}
}

Related

Magento 2 - new inscription newsletter error (no such entity with customerId = 0)

I always have this error when I try to register to newsletter in Magento 2. The error is:
No such entity with customerId = 0
If I try to add it directly from database, it works perfectly.
The function is :
vendor/magento/module-newsletter/Model/Subscriber.php
public function subscribe($email)
{
$this->loadByEmail($email);
if (!$this->getId()) {
$this->setSubscriberConfirmCode($this->randomSequence());
}
$isConfirmNeed = $this->_scopeConfig->getValue(
self::XML_PATH_CONFIRMATION_FLAG,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
) == 1 ? true : false;
$isOwnSubscribes = false;
$isSubscribeOwnEmail = $this->_customerSession->isLoggedIn()
&& $this->_customerSession->getCustomerDataObject()->getEmail() == $email;
if (!$this->getId() || $this->getStatus() == self::STATUS_UNSUBSCRIBED
|| $this->getStatus() == self::STATUS_NOT_ACTIVE
) {
if ($isConfirmNeed === true) {
// if user subscribes own login email - confirmation is not needed
$isOwnSubscribes = $isSubscribeOwnEmail;
if ($isOwnSubscribes == true) {
$this->setStatus(self::STATUS_SUBSCRIBED);
} else {
$this->setStatus(self::STATUS_NOT_ACTIVE);
}
} else {
$this->setStatus(self::STATUS_SUBSCRIBED);
}
$this->setSubscriberEmail($email);
}
if ($isSubscribeOwnEmail) {
try {
$customer = $this->customerRepository->getById($this->_customerSession->getCustomerId());
$this->setStoreId($customer->getStoreId());
$this->setCustomerId($customer->getId());
} catch (NoSuchEntityException $e) {
$this->setStoreId($this->_storeManager->getStore()->getId());
$this->setCustomerId(0);
}
} else {
$this->setStoreId($this->_storeManager->getStore()->getId());
$this->setCustomerId(0);
}
$this->setStatusChanged(true);
try {
$this->save();
if ($isConfirmNeed === true
&& $isOwnSubscribes === false
) {
$this->sendConfirmationRequestEmail();
} else {
$this->sendConfirmationSuccessEmail();
}
return $this->getStatus();
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
}

About mybatis3.3 databaseId,the code is useless

I study the mybatis3.3 sources code and now I have a question:in the XMLMapperBuilder.databaseIdMatchesCurrent()
private boolean databaseIdMatchesCurrent(String id, String databaseId, String requiredDatabaseId) {
if (requiredDatabaseId != null) {
if (!requiredDatabaseId.equals(databaseId)) {
return false;
}
} else {
if (databaseId != null) {
return false;
}
// skip this fragment if there is a previous one with a not null databaseId
if (this.sqlFragments.containsKey(id)) {
XNode context = this.sqlFragments.get(id);
if (context.getStringAttribute("databaseId") != null) {
return false;
}
}
}
return true;
}
if the (requiredDatabaseId == null && databaseId != null) ,then the function will return false.
So the code
if (this.sqlFragments.containsKey(id)) {
XNode context = this.sqlFragments.get(id);
if (context.getStringAttribute("databaseId") != null) {
return false;
}
}
certainly no way to return false and this code is useless.
I just want to questioning: I understand this, right?

video overwriting using ffmpeg - I want to Add video rotation code and rewrite the existing file..How can i do that?

I want to rotate the .mov file which is in portrait mode by 90 degrees, for that i used the following code..
It works but, it results in loss of video frames...
My code is,
public void encode(File source, File target, EncodingAttributes attributes,
EncoderProgressListener listener, Integer i) throws IllegalArgumentException,
InputFormatException, EncoderException {
String formatAttribute = attributes.getFormat();
Float offsetAttribute = attributes.getOffset();
Float durationAttribute = attributes.getDuration();
QualityScale qualityScale = attributes.getQualityScale();
AudioAttributes audioAttributes = attributes.getAudioAttributes();
VideoAttributes videoAttributes = attributes.getVideoAttributes();
if (audioAttributes == null && videoAttributes == null) {
throw new IllegalArgumentException(
"Both audio and video attributes are null");
}
target = target.getAbsoluteFile();
target.getParentFile().mkdirs();
FFMPEGExecutor ffmpeg = locator.createExecutor();
if (offsetAttribute != null) {
ffmpeg.addArgument("-ss");
ffmpeg.addArgument(String.valueOf(offsetAttribute.floatValue()));
}
ffmpeg.addArgument("-i");
ffmpeg.addArgument(source.getAbsolutePath());
if (durationAttribute != null) {
ffmpeg.addArgument("-t");
ffmpeg.addArgument(String.valueOf(durationAttribute.floatValue()));
}
if (qualityScale != null) {
ffmpeg.addArgument("-qscale:"+qualityScale.getQualityStreamSpecifier());
ffmpeg.addArgument(String.valueOf(qualityScale.getQualityValue()));
}
if (videoAttributes == null) {
ffmpeg.addArgument("-vn");
} else {
String codec = videoAttributes.getCodec();
if (codec != null) {
ffmpeg.addArgument("-vcodec");
ffmpeg.addArgument(codec);
}
String tag = videoAttributes.getTag();
if (tag != null) {
ffmpeg.addArgument("-vtag");
ffmpeg.addArgument(tag);
}
Integer bitRate = videoAttributes.getBitRate();
if (bitRate != null) {
ffmpeg.addArgument("-b");
ffmpeg.addArgument(String.valueOf(bitRate.intValue()));
}
Integer frameRate = videoAttributes.getFrameRate();
if (frameRate != null) {
ffmpeg.addArgument("-r");
ffmpeg.addArgument(String.valueOf(frameRate.intValue()));
}
VideoSize size = videoAttributes.getSize();
if (size != null) {
ffmpeg.addArgument("-s");
ffmpeg.addArgument(String.valueOf(size.getWidth()) + "x"
+ String.valueOf(size.getHeight()));
}
FilterGraph filterGraph = videoAttributes.getFilterGraph();
if (filterGraph != null) {
ffmpeg.addArgument("-vf");
if(videoAttributes.getRotate() != null && videoAttributes.getRotate() == 90){
ffmpeg.addArgument("transpose=1");
}else if(videoAttributes.getRotate() != null && videoAttributes.getRotate() == 180){
ffmpeg.addArgument("vflip,hflip");
}
else {
if (filterGraph.isUseExpression()) {
ffmpeg.addArgument(filterGraph.getFilterGraphExpression());
}
}
}
}
if (audioAttributes == null) {
ffmpeg.addArgument("-an");
} else {
String codec = audioAttributes.getCodec();
if (codec != null) {
ffmpeg.addArgument("-acodec");
ffmpeg.addArgument(codec);
}
Integer bitRate = audioAttributes.getBitRate();
if (bitRate != null) {
ffmpeg.addArgument("-ab");
ffmpeg.addArgument(String.valueOf(bitRate.intValue()));
}
Integer channels = audioAttributes.getChannels();
if (channels != null) {
ffmpeg.addArgument("-ac");
ffmpeg.addArgument(String.valueOf(channels.intValue()));
}
Integer samplingRate = audioAttributes.getSamplingRate();
if (samplingRate != null) {
ffmpeg.addArgument("-ar");
ffmpeg.addArgument(String.valueOf(samplingRate.intValue()));
}
Integer volume = audioAttributes.getVolume();
if (volume != null) {
ffmpeg.addArgument("-vol");
ffmpeg.addArgument(String.valueOf(volume.intValue()));
}
}
ffmpeg.addArgument("-f");
ffmpeg.addArgument(formatAttribute);
ffmpeg.addArgument("-y");
ffmpeg.addArgument(target.getAbsolutePath());
try {
ffmpeg.execute();
} catch (IOException e) {
throw new EncoderException(e);
}
try {
String lastWarning = null;
long duration;
long progress = 0;
RBufferedReader reader = null;
reader = new RBufferedReader(new InputStreamReader(ffmpeg
.getErrorStream()));
MultimediaInfo info = parseMultimediaInfo(source, reader);
if (durationAttribute != null) {
duration = (long) Math
.round((durationAttribute.floatValue() * 1000L));
} else {
duration = info.getDuration();
if (offsetAttribute != null) {
duration -= (long) Math
.round((offsetAttribute.floatValue() * 1000L));
}
}
if (listener != null) {
listener.sourceInfo(info);
}
int step = 0;
String line;
while ((line = reader.readLine()) != null) {
System.out.println("line::::"+line);
if (step == 0) {
if (line.startsWith("WARNING: ")) {
if (listener != null) {
listener.message(line);
}
} else if (!line.startsWith("Output #0")) {
//throw new EncoderException(line);
} else {
step++;
}
} else if (step == 1) {
if (!line.startsWith(" ")) {
step++;
} else {
System.out.println("line>>>>>>"+line);
Hashtable table1 = new Hashtable();
Matcher m = ROTATE_INFO_PATTERN.matcher(line);
while (m.find()) {
if (table1 == null) {
table1 = new Hashtable();
}
String key = m.group(1);
String value = m.group(2);
table1.put(key, value);
}
System.out.println("Table values"+table1.get("rotate"));
if(table1.get("rotate") != null){
Object videoRotateValue = table1.get("rotate");
int rotate = Integer.valueOf(videoRotateValue.toString());
switch(rotate){
case 90:
videoAttributes.setRotate(rotate);
if(i == 0){
i++;
encode(source, target, attributes, null, i);
}
break;
case 180:
videoAttributes.setRotate(rotate);
if(i == 0){
i++;
encode(source, target, attributes, null, i);
}
break;
case 270: System.out.println("case 3 :: "+videoRotateValue);
break;
}
}
}
}
if (step == 2) {
if (!line.startsWith("Stream mapping:")) {
throw new EncoderException(line);
} else {
step++;
}
} else if (step == 3) {
if (!line.startsWith(" ")) {
step++;
}
}
if (step == 4) {
line = line.trim();
if (line.length() > 0) {
Hashtable table = parseProgressInfoLine(line);
if (table == null) {
if (listener != null) {
listener.message(line);
}
lastWarning = line;
} else {
if (listener != null) {
String time = (String) table.get("time");
if (time != null) {
int dot = time.indexOf('.');
if (dot > 0 && dot == time.length() - 2
&& duration > 0) {
String p1 = time.substring(0, dot);
String p2 = time.substring(dot + 1);
try {
long i1 = Long.parseLong(p1);
long i2 = Long.parseLong(p2);
progress = (i1 * 1000L)
+ (i2 * 100L);
int perm = (int) Math
.round((double) (progress * 1000L)
/ (double) duration);
if (perm > 1000) {
perm = 1000;
}
listener.progress(perm);
} catch (NumberFormatException e) {
;
}
}
}
}
lastWarning = null;
}
}
}
}
if (lastWarning != null) {
if (!SUCCESS_PATTERN.matcher(lastWarning).matches()) {
throw new EncoderException(lastWarning);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
ffmpeg.destroy();
}
}
Please advise, how to achieve video rotation without any video Frame loss
Thanks In Advance
Lakshmi Priya . K
Worked for couple of days and finally tried to write the rotated video in different target file then i got the video output without any loss and video is also rotated....
Thanks
Lakshmi Priya. K

Selecting a value from a database an check if it is true or false

This code always returns true can some please help me out
public boolean plselct(String sqd)
{
try{
String player ;
pm = conn.prepareStatement("SELECT playertype FROM playerdetails where idplayeratrr = ?");
pm.setString(1,sqd );
h= pm.executeQuery();
player = h.getString("playertype");
if ("Goal keeper".equals(player))
{ return true; }
else
return false;
}catch (Exception e)
{}
return false;
}
SelectQu p = new SelectQu();
p.plselct("77");
if(true)
{ System.out.println("Yes"); }
else
{ System.out.println("No"); }
You are checking for if(true)? Did you mean this instead:
SelectQu p = new SelectQu();
if(p.plselct("77"))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}

Any other option to deploy in jboss server ither than hot deployment?

I want to know what are the methods to deploy in jboss server other than hot deployment.
Get the client and the builder to build plans:
ModelControllerClient client = ModelControllerClient.Factory.create(host, port);
ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(client);
DeploymentPlanBuilder builder = manager.newDeploymentPlan();
And the method to execute any kind of operation (here some ones are implemented):
public DeployementActionStatus execute(Type deploy) throws IOException
{
List<Throwable> errors = new LinkedList<Throwable>();
DeployementActionStatus status = DeployementActionStatus.SUCCESS;
switch (deploy)
{
case DEPLOY:
if (archive != null)
{
plan = builder.add(archive).deploy(archive.getName()).build();
}
else
{
return DeployementActionStatus.FAILURE;
}
break;
case REDEPLOY:
{
if (archive != null)
{
plan = builder.redeploy(archive.getName()).build();
}
else
{
return DeployementActionStatus.FAILURE;
}
break;
}
case UNDEPLOY:
{
plan = builder.undeploy(getApplicationName()).build();
break;
}
case REMOVE:
{
plan = builder.remove(getApplicationName()).build();
break;
}
default:
plan = null;
break;
}
if (plan == null)
{
throw new IllegalStateException("Invalid type: " + deploy);
}
if (plan.getDeploymentActions().size() > 0)
{
try
{
final ServerDeploymentPlanResult planResult = manager.execute(plan).get();
// Check the results
for (DeploymentAction action : plan.getDeploymentActions())
{
final ServerDeploymentActionResult actionResult = planResult.getDeploymentActionResult(action
.getId());
final ServerUpdateActionResult.Result result = actionResult.getResult();
switch (result)
{
case FAILED:
case NOT_EXECUTED:
case ROLLED_BACK:
{
log.error(actionResult.getDeploymentException());
if (actionResult.getDeploymentException().getMessage() != null
&& actionResult.getDeploymentException().getMessage().contains("Duplicate"))
{
status = DeployementActionStatus.FAILURE_ALREADY_DEPLOYED;
}
else
{
status = DeployementActionStatus.FAILURE;
}
break;
}
case CONFIGURATION_MODIFIED_REQUIRES_RESTART:
// Should show warning
break;
default:
break;
}
}
}
catch (InterruptedException e)
{
errors.add(e);
status = DeployementActionStatus.FAILURE;
}
catch (ExecutionException e)
{
errors.add(e);
status = DeployementActionStatus.FAILURE;
}
catch (Exception e)
{
if (e instanceof RuntimeException)
{
status = DeployementActionStatus.CONNECTION_TO_SERVER_FAILED;
}
}
}
return status;
}
Deploying is considered hot only when JBoss is running. If you don't want hot deployment you can turn off deployment scanner [1] or stop JBoss and deploy the artifact.
[1] https://community.jboss.org/wiki/ConfiguringTheDeploymentScannerInConfjbossSystemxml