How to associate Kentico changes from REST API or External Application to a staging task group - console-application

How to associate Kentico changes from REST API or External Application (like windows console application) to a staging task group
static void Main ( string [ ] args )
{
UserInfo userInfo = UserInfoProvider.GetUserInfo ( "User1" );
using ( new CMSActionContext ( userInfo ) )
{
TreeProvider treeProvider = new TreeProvider ( userInfo );
NodeSelectionParameters nodeSelectionParameters = new NodeSelectionParameters
{
AliasPath = "Path"
};
TreeNode parentPage = treeProvider.SelectSingleNode ( nodeSelectionParameters );
TreeNode newPage = TreeNode.New ( "Class", treeProvider );
newPage.DocumentName = "Test Title";
newPage.DocumentCulture = "en-us";
newPage.DocumentUrlPath = "Path";
newPage.Insert ( parentPage );
}
}
The above code is properly creating the document and the staging tasks with the user context. How can I associate the staging tasks for this document to a staging task group?

First I'd look to make sure that the objects that you are changing are in the list of items supported by content staging. you can see that list here: Content staging - What can be synchronized
So long as you are ultimately using Kentico's API, and Content Staging is enabled, then Kentico should be creating these tasks for you. If you're updating the Kentico database directly without the API, you're probably going to run into trouble and might need to manually create staging tasks or use the API to perform synchronisation.

We can use the SynchronizationActionContext class to associate API changes to a staging task group.
static void Main ( string [ ] args )
{
List<TaskGroupInfo> taskGroups = TaskGroupInfoProvider.GetTaskGroups ( ).WhereEquals ( "TaskGroupCodeName", "MyTaskGroup" ).ToList ( );
using ( new SynchronizationActionContext ( ) { TaskGroups = taskGroups } )
{
UserInfo userInfo = UserInfoProvider.GetUserInfo ( "User1" );
using ( new CMSActionContext ( userInfo ) )
{
TreeProvider treeProvider = new TreeProvider ( userInfo );
NodeSelectionParameters nodeSelectionParameters = new NodeSelectionParameters
{
AliasPath = "Path"
};
TreeNode parentPage = treeProvider.SelectSingleNode ( nodeSelectionParameters );
TreeNode newPage = TreeNode.New ( "Class", treeProvider );
newPage.DocumentName = "Test Title";
newPage.DocumentCulture = "en-us";
newPage.DocumentUrlPath = "Path";
newPage.Insert ( parentPage );
}
}
}

Related

test class for handler trigger is not covered

I did a trigger on content version ,but my handler class is not covered ,can you please explain to me why ?
please find below the code and screenshots for non covered lines
in my test class ,i created all data needed for the handler class i call the method with content version input
Trigger:
trigger contentversiontrigger on ContentVersion (before insert, before update, before delete, after insert, after update, after delete, after undelete) {
if(trigger.isAfter && trigger.isInsert) {
Bytel_ContentVersionTriggerHandler.AlignAttachementsWithOpportunity(Trigger.New);
}
}
Trigger Handler
public with sharing class Bytel_ContentVersionTriggerHandler extends TriggerHandler {
public static void AlignAttachementsWithOpportunity(List<ContentVersion> contentVersion) {
Set<Id> contentDocumentIdSet = new Set<Id>();
String Contractid;
String Opportunityid;
for (ContentVersion cv : contentVersion) {
if(cv.ContentDocumentId != null)
{
contentDocumentIdSet.add(cv.ContentDocumentId);
}
}
list<ContentDocumentLink> cdl = [SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN:contentDocumentIdSet];
id LinkedEntityId =cdl[0].LinkedEntityId ;
// List<Contract> contractList = [SELECT Id, name FROM Contract where Id =:cdl.LinkedEntityId];
list<contract> Contracts = [SELECT Id, name FROM Contract where Id =:LinkedEntityId ];
if (!Contracts.isEmpty())
{
Contractid=Contracts[0].Id;
}
// Id Contractid = [SELECT Id, name FROM Contract where Id ='8005t0000001UQFAA2' limit 1].Id;
system.debug('test trigger' +Contractid) ;
// String Contractid= String.valueof(contractList[0].Id);
system.debug('ContractId' +Contractid) ;
list<Contract> contractssecond=[SELECT id ,vlocity_cmt__OpportunityId__c FROM Contract WHERE id =:Contractid limit 1];
if (!contractssecond.isEmpty())
{
Opportunityid=contractssecond[0].vlocity_cmt__OpportunityId__c;
}
system.debug('Opportunityid' +Opportunityid) ;
Id conDoc = cdl[0].ContentDocumentId;
//if (Opportunityid!=Null & conDoc!=Null) {
if (Opportunityid!=Null ) {
//create ContentDocumentLink record
ContentDocumentLink conDocLink = New ContentDocumentLink();
conDocLink.LinkedEntityId = Opportunityid;
conDocLink.ContentDocumentId = conDoc; //ContentDocumentId Id from ContentVersion
conDocLink.shareType = 'V';
insert conDocLink;
}
}
}
Test class of handler
#isTest
public class Bytel_ContentVersionTriggerHandlerTest {
static testMethod void createattachememtns() {
insert Bytel_TestDataFactory.createByPassSettings(false); // Custom setting bypass profile
insert Bytel_TestDataFactory.createGlobalVariableSettings(); // Custom setting globalVaribale, parameter callout end-point
insert Bytel_TestDataFactory.createOpportunityRaisonEchecSettings();
insert Bytel_TestDataFactory.createOpportunityStatusSettings();
Account acc = new Account(
Name = 'Test Account',
TypeIdentifiant__c = 'SIREN',
SIREN__c = '123765982',
Statut__c = 'Prospect'
);
insert acc;
Opportunity opp = Bytel_TestDataFactory.createOpportunity(
'FILL AUTO',
'Etape10',
acc.Id,
null
);
opp.Tech_AccountIdToDelete__c = acc.id;
opp.ScoringFinancier__c = 'Vert';
opp.siren__c = '123765981';
insert opp;
Quote quote = new Quote(Name = 'devis1', OpportunityId = opp.Id);
insert quote;
Contract contract1 = new Contract(
vlocity_cmt__QuoteId__c = quote.Id,
vlocity_cmt__OpportunityId__c=opp.id,
AccountId = acc.id
);
insert contract1;
Contract contract2 = new Contract(
vlocity_cmt__QuoteId__c = quote.Id,
AccountId = acc.id,
vlocity_cmt__OpportunityId__c=opp.id
);
insert contract2;
Blob bodyBlob=Blob.valueOf('Unit Test ContentVersion Body to be insert in test class for testing the');
ContentVersion contentVersion_1 = new ContentVersion(
Title='SampleTitle',
PathOnClient ='SampleTitle.txt',
Type_de_Fichier__c='RIB',
VersionData = bodyBlob,
origin = 'H'
);
insert contentVersion_1;
Contract contra = [SELECT Id
FROM Contract WHERE Id = :contract1.Id LIMIT 1];
List<ContentVersion> contentVersion_2 = [SELECT Id, Title, ContentDocumentId
FROM ContentVersion WHERE Id = :contentVersion_1.Id ];
// ContentDocumentLink contentlink = new ContentDocumentLink();
// contentlink.LinkedEntityId = contra.id;
// contentlink.contentdocumentid = contentVersion_2.contentdocumentid;
// contentlink.ShareType = 'V';
// insert contentlink;
Bytel_ContentVersionTriggerHandler.AlignAttachementsWithOpportunity(contentVersion_2);
}
}
After a first look, I guess you forgot to add #isTest to your test method.
#isTest
static testMethod void createattachememtns() {
//Your Code
}

How to make JSESSIONID and other cookie secure? [duplicate]

Is there a way to configure Tomcat 7 to create JSESSIONID cookie with a secure flag in all occasions?
Usual configuration results in Tomcat flagging session cookie with secure flag only if connection is made through https. However in my production scenario, Tomcat is behind a reverse proxy/load balancer which handles (and terminates) the https connection and contacts tomcat over http.
Can I somehow force secure flag on session cookie with Tomcat, even though connection is made through plain http?
In the end, contrary to my initial tests, web.xml solution worked for me on Tomcat 7.
E.g. I added this snippet to web.xml and it marks session cookie as secure even when reverse proxy contacts tomcat over plain HTTP.
<session-config>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
</session-config>
ServletContext.getSessionCookieConfig().setSecure(true)
Another approach, similar to Mark's, would be to use the SessionCookieConfig, but set it in a context listener from JNDI configuration:
The code:
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.SessionCookieConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JndiSessionCookieConfigListener implements ServletContextListener {
private static final Logger logger = LoggerFactory.getLogger( JndiSessionCookieConfigListener.class );
private volatile Context jndiSessionCookieConfig;
private volatile SessionCookieConfig sessionCookieConfig;
#Override
public void contextInitialized( ServletContextEvent sce ) {
String listenerName = getClass().getSimpleName();
try {
logger.info( "JNDI override session cookie config found for {}", listenerName );
jndiSessionCookieConfig = (Context) new InitialContext().lookup(
"java:comp/env/" + listenerName );
}
catch ( NamingException e ) {
logger.info( "No JNDI override session cookie config found for {}", listenerName );
}
sessionCookieConfig = sce.getServletContext().getSessionCookieConfig();
String comment = getString( "comment" );
if ( comment != null ) {
logger.debug( "\t[comment]: [{}]", comment );
sessionCookieConfig.setComment( comment );
}
String domain = getString( "domain" );
if ( domain != null ) {
logger.debug( "\t[domain]: [{}]", domain );
sessionCookieConfig.setDomain( domain );
}
Boolean httpOnly = getBoolean( "http-only" );
if ( httpOnly == null ) {
sessionCookieConfig.setHttpOnly( true );
}
else {
logger.debug( "\t[http-only]: [{}]", httpOnly );
sessionCookieConfig.setHttpOnly( httpOnly );
}
Integer maxAge = getInteger( "max-age" );
if ( maxAge != null ) {
sessionCookieConfig.setMaxAge( maxAge );
}
String name = getString( "name" );
if ( name != null ) {
logger.debug( "\t[name]: [{}]", name );
sessionCookieConfig.setName( name );
}
String path = getString( "path" );
if ( path != null ) {
logger.debug( "\t[path]: [{}]", path );
sessionCookieConfig.setPath( path );
}
Boolean secure = getBoolean( "secure" );
if ( secure == null ) {
sessionCookieConfig.setSecure( true );
}
else {
logger.debug( "\t[secure]: [{}]", secure );
sessionCookieConfig.setSecure( secure );
}
}
#Override
public void contextDestroyed( ServletContextEvent sce ) {
}
private Boolean getBoolean( String name ) {
Object value;
try {
value = jndiSessionCookieConfig.lookup( name );
if ( value instanceof Boolean ) {
return (Boolean)value;
}
else {
return Boolean.valueOf( value.toString() );
}
}
catch ( NamingException e ) {
return null;
}
}
private Integer getInteger( String name ) {
Object value;
try {
value = jndiSessionCookieConfig.lookup( name );
if ( value instanceof Integer ) {
return (Integer)value;
}
else {
return Integer.valueOf( value.toString() );
}
}
catch ( NamingException e ) {
return null;
}
}
private String getString( String name ) {
Object value;
try {
value = jndiSessionCookieConfig.lookup( name );
return value.toString();
}
catch ( NamingException e ) {
return null;
}
}
}
Inside web.xml:
...
<listener>
<listener-class>
org.mitre.caasd.servlet.init.JndiSessionCookieConfigListener
</listener-class>
</listener>
...
In your context.xml:
...
<Environment name="JndiSessionCookieConfigListener/secure"
type="java.lang.String"
override="false"
value="true" />
...
This allows you to set all the session cookie configurations at runtime in the deployment environment. Thus, you could use the same webapp (war file) to do development locally (where you would not have https) and in production where you would ALWAYS want https.
Note, this approach is mentioned in the OWASP documentation

getting products and their attributes from prestashop webservice

I'm going to use Prestashop 1.5.4 web-service to get all products with their attributes such as description, name and etc. My problem is whenever I call web-service it returns to me only the products Ids. How can I get attributes too?
Edited :
code :
class ShopApi
{
public $client;
public function __construct()
{
$this->getClient();
}
public function getClient()
{
try {
// creating web service access
$this->client = new PrestaShopWebservice('http://wikibazaar.ir/', 'A38L095W0RHRXE8PM9CM01CZW7KIU4PX', false);
} catch (PrestaShopWebserviceException $ex) {
// Shows a message related to the error
echo 'error: <br />' . $ex->getMessage();
}
}
}
class ProductApi extends ShopApi
{
public function findAll()
{
$products = array();
/// The key-value array
$opt['resource'] = 'products';
$opt['display'] = '[description]';
$opt['limit'] = 1;
$xml = $this->client->get($opt);
$resources = $xml->products->children();
foreach ($resources as $resource)
$products[] = $resource->attributes();
return $products;
}
}
EDIT :
I've found that the response from webservice is ok. but there is a problem during parsing xml with simplexml_load_string() function. any idea?
it's $product var_dump :
SimpleXMLElement#1 ( [products] => SimpleXMLElement#2 ( [product] => SimpleXMLElement#3 ( [description] => SimpleXMLElement#4 ( [language] => SimpleXMLElement#5 ( [#attributes] => array ( 'id' => '1' ) ) ) ) ) )
I think that $opt['display'] = 'full'; would do the job
You can also select only some specific attribute e.g.
$opt['display'] = '[id,name]';
Take a look at the official documentation, you might find it interesting

Compiling JSF 2 facelets within a unit test for correctness

I am trying to use the Mojarra JSF 2 compiler programatically with a view to checking the correctness of the xhtml of any pages.
I have got so far but the compiler is not erroring for tags that don't exist in a particular tag library. It does the standard XML namespace checks but if say rich:spacer is present it should error (it got removed in Richfaces 4.x). At runtime this check takes does take place.
Any thoughts? Here is my code:
#RunWith( PowerMockRunner.class )
#PrepareForTest( { WebConfiguration.class, FacesContext.class } )
public class XhtmlValidatorTest
{
#Test
public void test() throws IOException
{
WebConfiguration webConfiguration = PowerMock.createMock( WebConfiguration.class );
PowerMock.mockStatic( WebConfiguration.class );
WebConfiguration.getInstance();
PowerMock.expectLastCall().andReturn( webConfiguration ).anyTimes();
FaceletsConfiguration faceletsConfiguration = PowerMock.createMock( FaceletsConfiguration.class );
webConfiguration.getFaceletsConfiguration();
PowerMock.expectLastCall().andReturn( faceletsConfiguration ).anyTimes();
faceletsConfiguration.isProcessCurrentDocumentAsFaceletsXhtml(EasyMock.isA( String.class ) );
PowerMock.expectLastCall().andReturn(true).anyTimes();
faceletsConfiguration.isConsumeComments( EasyMock.isA( String.class) );
PowerMock.expectLastCall().andReturn(false).anyTimes();
faceletsConfiguration.isConsumeCDATA( EasyMock.isA( String.class ) );
PowerMock.expectLastCall().andReturn(false).anyTimes();
webConfiguration.isOptionEnabled(BooleanWebContextInitParameter.EnableMissingResourceLibraryDetection);
PowerMock.expectLastCall().andReturn( false ).anyTimes();
webConfiguration.isOptionEnabled(BooleanWebContextInitParameter.EnableCoreTagLibraryValidator );
PowerMock.expectLastCall().andReturn( true ).anyTimes();
FacesContext facesContext = PowerMock.createMock( FacesContext.class );
PowerMock.mockStatic( FacesContext.class );
FacesContext.getCurrentInstance();
PowerMock.expectLastCall().andReturn( facesContext ).anyTimes();
facesContext.isProjectStage( ProjectStage.Development );
PowerMock.expectLastCall().andReturn( false ).anyTimes();
Application application = PowerMock.createMock( Application.class );
facesContext.getApplication();
PowerMock.expectLastCall().andReturn( application ).anyTimes();
application.getExpressionFactory();
PowerMock.expectLastCall().andReturn( new org.jboss.el.ExpressionFactoryImpl() ).anyTimes();
PowerMock.replayAll();
long refreshPeriod = -1;
com.sun.faces.facelets.compiler.Compiler compiler = new SAXCompiler();
compiler.setValidating( true );
System.out.println( "Compiler.isValidating() " + compiler.isValidating() );
FaceletCache cache = new UnittestFaceletCacheFactory().getCache( refreshPeriod );
ResourceResolver resolver = new ResourceResolver()
{
#Override
public URL resolveUrl(String path)
{
URL url = null;
try
{
url = new URL( BASE_PATH + path );
}
catch (MalformedURLException e)
{
throw new RuntimeException( e );
}
return url;
}
};
DefaultFaceletFactory defaultFaceletFactory = new DefaultFaceletFactory( compiler, resolver, refreshPeriod, cache );
File file = new File( "WebContent" );
File[] files = file.listFiles();
for( File xhtmlFile : files )
{
if( xhtmlFile.isFile() )
{
String name = xhtmlFile.getName();
if( name.endsWith(".xhtml" ) )
{
System.out.println( "compiling: " + name );
defaultFaceletFactory.getFacelet( name );
}
}
}
}
The facelet cache factory used in the code is a hack:
package com.sun.faces.facelets.impl;
import javax.faces.view.facelets.FaceletCache;
public class UnittestFaceletCacheFactory
{
public FaceletCache getCache( long refreshPeriod )
{
return new DefaultFaceletCache( refreshPeriod );
}
}

Unit testing Monorail's RenderText method

I'm doing some maintenance on an older web application written in Monorail v1.0.3. I want to unit test an action that uses RenderText(). How do I extract the content in my test? Reading from controller.Response.OutputStream doesn't work, since the response stream is either not setup properly in PrepareController(), or is closed in RenderText().
Example Action
public DeleteFoo( int id )
{
var success= false;
var foo = Service.Get<Foo>( id );
if( foo != null && CurrentUser.IsInRole( "CanDeleteFoo" ) )
{
Service.Delete<Foo>( id );
success = true;
}
CancelView();
RenderText( "{ success: " + success + " }" );
}
Example Test (using Moq)
[Test]
public void DeleteFoo()
{
var controller = new FooController ();
PrepareController ( controller );
var foo = new Foo { Id = 123 };
var mockService = new Mock < Service > ();
mockService.Setup ( s => s.Get<Foo> ( foo.Id ) ).Returns ( foo );
controller.Service = mockService.Object;
controller.DeleteTicket ( foo.Id );
mockService.Verify ( s => s.Delete<Foo> ( foo.Id ) );
Assert.AreEqual ( "{success:true}", GetResponse ( Response ) );
}
// response.OutputStream.Seek throws an "System.ObjectDisposedException: Cannot access a closed Stream." exception
private static string GetResponse( IResponse response )
{
response.OutputStream.Seek ( 0, SeekOrigin.Begin );
var buffer = new byte[response.OutputStream.Length];
response.OutputStream.Read ( buffer, 0, buffer.Length );
return Encoding.ASCII.GetString ( buffer );
}
Override BaseControllerTest.BuildResponse() and provide your mock of IMockResponse built with Moq.