Package com.dotcms.publisher.business

Examples of com.dotcms.publisher.business.PublisherAPI


     */
    public void publish ( HttpServletRequest request, HttpServletResponse response ) throws IOException, WorkflowActionFailureException {

        try {

            PublisherAPI publisherAPI = PublisherAPI.getInstance();

            //Read the form values
            String _assetId = request.getParameter( "assetIdentifier" );
            String _contentPushPublishDate = request.getParameter( "remotePublishDate" );
            String _contentPushPublishTime = request.getParameter( "remotePublishTime" );
            String _contentPushExpireDate = request.getParameter( "remotePublishExpireDate" );
            String _contentPushExpireTime = request.getParameter( "remotePublishExpireTime" );
            String _contentFilterDate = request.getParameter( "remoteFilterDate" );
            String _iWantTo = request.getParameter( "iWantTo" );
            String whoToSendTmp = request.getParameter( "whoToSend" );
            String forcePushStr = request.getParameter( "forcePush" );
            boolean forcePush = (forcePushStr!=null && forcePushStr.equals("true"));
            List<String> whereToSend = Arrays.asList(whoToSendTmp.split(","));
            List<Environment> envsToSendTo = new ArrayList<Environment>();

            // Lists of Environments to push to
            for (String envId : whereToSend) {
              Environment e = APILocator.getEnvironmentAPI().findEnvironmentById(envId);

              if(e!=null) {
                envsToSendTo.add(e);
              }
      }

            //Put the selected environments in session in order to have the list of the last selected environments
            request.getSession().setAttribute( WebKeys.SELECTED_ENVIRONMENTS + getUser().getUserId(), envsToSendTo );

            SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd-H-m" );
            Date publishDate = dateFormat.parse( _contentPushPublishDate + "-" + _contentPushPublishTime );

            List<String> ids;
            if ( _assetId.startsWith( "query_" ) ) { //Support for lucene queries

                String luceneQuery = _assetId.replace( "query_", "" );
                List<String> queries = new ArrayList<String>();
                queries.add( luceneQuery );
                ids = PublisherUtil.getContentIds( queries );

            } else {

                String[] _assetsIds = _assetId.split( "," );//Support for multiple ids in the assetIdentifier parameter
                List<String> assetsIds = Arrays.asList( _assetsIds );

                ids = getIdsToPush( assetsIds, null, _contentFilterDate, dateFormat );
            }

            //Response map with the status of the addContents operation (error messages and counts )
            Map<String, Object> responseMap = null;

            if ( _iWantTo.equals( RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH ) || _iWantTo.equals( RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH_AND_EXPIRE ) ) {
              Bundle bundle = new Bundle(null, publishDate, null, getUser().getUserId(), forcePush);
              APILocator.getBundleAPI().saveBundle(bundle, envsToSendTo);

                responseMap = publisherAPI.addContentsToPublish( ids, bundle.getId(), publishDate, getUser() );
            }
            if ( _iWantTo.equals( RemotePublishAjaxAction.DIALOG_ACTION_EXPIRE ) || _iWantTo.equals( RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH_AND_EXPIRE ) ) {
                if ( (!"".equals( _contentPushExpireDate.trim() ) && !"".equals( _contentPushExpireTime.trim() )) ) {
                    Date expireDate = dateFormat.parse( _contentPushExpireDate + "-" + _contentPushExpireTime );

                    Bundle bundle = new Bundle(null, publishDate, expireDate, getUser().getUserId(), forcePush);
                  APILocator.getBundleAPI().saveBundle(bundle, envsToSendTo);

                    responseMap = publisherAPI.addContentsToUnpublish( ids, bundle.getId(), expireDate, getUser() );
                }
            }

            //If we have errors lets return them in order to feedback the user
            if ( responseMap != null && !responseMap.isEmpty() ) {
View Full Code Here


     * @throws DotPublisherException If fails retrieving the Bundle related information like elements on it and statuses
     * @throws LanguageException If fails using i18 messages
     */
    public void retry ( HttpServletRequest request, HttpServletResponse response ) throws IOException, DotPublisherException, LanguageException {

        PublisherAPI publisherAPI = PublisherAPI.getInstance();
        PublishAuditAPI publishAuditAPI = PublishAuditAPI.getInstance();

        //Read the parameters
        String bundlesIds = request.getParameter( "bundlesIds" );
        String[] ids = bundlesIds.split( "," );

        StringBuilder responseMessage = new StringBuilder();

        for ( String bundleId : ids ) {

            if ( bundleId.trim().isEmpty() ) {
                continue;
            }

            PublisherConfig basicConfig = new PublisherConfig();
            basicConfig.setId( bundleId );
            File bundleRoot = BundlerUtil.getBundleRoot( basicConfig );

            //Get the audit records related to this bundle
            PublishAuditStatus status = PublishAuditAPI.getInstance().getPublishAuditStatus( bundleId );
            String pojo_string = status.getStatusPojo().getSerialized();
            PublishAuditHistory auditHistory = PublishAuditHistory.getObjectFromString( pojo_string );

            //First we need to verify is this bundle is already in the queue job
            List<PublishQueueElement> foundBundles = publisherAPI.getQueueElementsByBundleId( bundleId );
            if ( foundBundles != null && !foundBundles.isEmpty() ) {
                appendMessage( responseMessage, "publisher_retry.error.already.in.queue", bundleId, true );
                continue;
            }

            //We will be able to retry failed and successfully bundles
            if ( !(status.getStatus().equals( Status.FAILED_TO_PUBLISH ) || status.getStatus().equals( Status.SUCCESS )) ) {
                appendMessage( responseMessage, "publisher_retry.error.only.failed.publish", bundleId, true );
                continue;
            }

            /*
            Verify if the bundle exist and was created correctly..., meaning, if there is not a .tar.gz file is because
            something happened on the creation of the bundle.
             */
            File bundleFile = new File( bundleRoot + File.separator + ".." + File.separator + basicConfig.getId() + ".tar.gz" );
            if ( !bundleFile.exists() ) {
                Logger.error( this.getClass(), "No Bundle with id: " + bundleId + " found." );
                appendMessage( responseMessage, "publisher_retry.error.not.found", bundleId, true );
                continue;
            }

            if ( !BundlerUtil.bundleExists( basicConfig ) ) {
                Logger.error( this.getClass(), "No Bundle Descriptor for bundle id: " + bundleId + " found." );
                appendMessage( responseMessage, "publisher_retry.error.not.descriptor.found", bundleId, true );
                continue;
            }

            try {

                //Read the bundle to see what kind of configuration we need to apply
                String bundlePath = ConfigUtils.getBundlePath() + File.separator + basicConfig.getId();
                File xml = new File( bundlePath + File.separator + "bundle.xml" );
                PushPublisherConfig config = (PushPublisherConfig) BundlerUtil.xmlToObject( xml );

                //We can not retry Received Bundles, just bundles that we are trying to send
                Boolean sending = sendingBundle( request, config, bundleId );
                if ( !sending ) {
                    appendMessage( responseMessage, "publisher_retry.error.cannot.retry.received", bundleId, true );
                    continue;
                }

                if ( status.getStatus().equals( Status.SUCCESS ) ) {

                    //Get the bundle
                    Bundle bundle = APILocator.getBundleAPI().getBundleById( bundleId );
                    if ( bundle == null ) {
                        Logger.error( this.getClass(), "No Bundle with id: " + bundleId + " found." );
                        appendMessage( responseMessage, "publisher_retry.error.not.found", bundleId, true );
                        continue;
                    }
                    bundle.setForcePush( true );
                    APILocator.getBundleAPI().updateBundle( bundle );
                }

                //Clean the number of tries, we want to try it again
                auditHistory.setNumTries( 0 );
                publishAuditAPI.updatePublishAuditStatus( config.getId(), status.getStatus(), auditHistory, true );

                //Get the identifiers on this bundle
                HashSet<String> identifiers = new HashSet<String>();
                List<PublishQueueElement> assets = config.getAssets();
                if ( config.getLuceneQueries() != null && !config.getLuceneQueries().isEmpty() ) {
                    identifiers.addAll( PublisherUtil.getContentIds( config.getLuceneQueries() ) );
                }
                if ( assets != null && !assets.isEmpty() ) {
                    for ( PublishQueueElement asset : assets ) {
                        identifiers.add( asset.getAsset() );
                    }
                }

                //Cleaning previous bundle folder and tar file to avoid sending modified data
                FileUtils.cleanDirectory(new File(bundlePath));
                bundleFile.delete();
               
                //Now depending of the operation lets add it to the queue job
                if ( config.getOperation().equals( PushPublisherConfig.Operation.PUBLISH ) ) {
                    publisherAPI.addContentsToPublish( new ArrayList<String>( identifiers ), bundleId, new Date(), getUser() );
                } else {
                    publisherAPI.addContentsToUnpublish( new ArrayList<String>( identifiers ), bundleId, new Date(), getUser() );
                }

                //Success...
                appendMessage( responseMessage, "publisher_retry.success", bundleId, false );
            } catch ( Exception e ) {
View Full Code Here

     */
    @SuppressWarnings ("unchecked")
    private Map<String, Object> generateBundle ( String bundleId, PushPublisherConfig.Operation operation ) throws DotPublisherException, DotDataException, DotPublishingException, IllegalAccessException, InstantiationException, DotBundleException, IOException {

        PushPublisherConfig pconf = new PushPublisherConfig();
        PublisherAPI pubAPI = PublisherAPI.getInstance();

        List<PublishQueueElement> tempBundleContents = pubAPI.getQueueElementsByBundleId( bundleId );
        List<PublishQueueElement> assetsToPublish = new ArrayList<PublishQueueElement>(); // all assets but contentlets

        for ( PublishQueueElement c : tempBundleContents ) {
            if ( !c.getType().equals( "contentlet" ) ) {
                assetsToPublish.add( c );
View Full Code Here

     * @param request  HttpRequest
     * @param response HttpResponse
     */
    public void addToBundle ( HttpServletRequest request, HttpServletResponse response ) throws IOException {

        PublisherAPI publisherAPI = PublisherAPI.getInstance();
        String _assetId = request.getParameter( "assetIdentifier" );
        String _contentFilterDate = request.getParameter( "remoteFilterDate" );
        String bundleName = request.getParameter( "bundleName" );
        String bundleId = request.getParameter( "bundleSelect" );

        try {
            Bundle bundle;

            if ( bundleId == null || bundleName.equals( bundleId ) ) {
                // if the user has a unsent bundle with that name just add to it
                bundle=null;
                for(Bundle b : APILocator.getBundleAPI().getUnsendBundlesByName(getUser().getUserId(), bundleName, 1000, 0)) {
                    if(b.getName().equalsIgnoreCase(bundleName)) {
                        bundle=b;
                    }
                }

                if(bundle==null) {
                    bundle = new Bundle( bundleName, null, null, getUser().getUserId() );
                    APILocator.getBundleAPI().saveBundle( bundle );
                }
            } else {
                bundle = APILocator.getBundleAPI().getBundleById( bundleId );
            }

            //Put the selected bundle in session in order to have last one selected
            request.getSession().setAttribute( WebKeys.SELECTED_BUNDLE + getUser().getUserId(), bundle );

            List<String> ids;
            if ( _assetId.startsWith( "query_" ) ) { //Support for lucene queries

                String luceneQuery = _assetId.replace( "query_", "" );
                List<String> queries = new ArrayList<String>();
                queries.add( luceneQuery );
                ids = PublisherUtil.getContentIds( queries );

            } else {

                String[] _assetsIds = _assetId.split( "," );//Support for multiple ids in the assetIdentifier parameter
                List<String> assetsIds = Arrays.asList( _assetsIds );

                ids = getIdsToPush( assetsIds,bundle.getId(), _contentFilterDate, new SimpleDateFormat( "yyyy-MM-dd-H-m" ) );
            }

            Map<String, Object> responseMap = publisherAPI.saveBundleAssets( ids, bundle.getId(), getUser() );

            //If we have errors lets return them in order to feedback the user
            if ( responseMap != null && !responseMap.isEmpty() ) {

                //Error messages
View Full Code Here

     */
    public void pushBundle ( HttpServletRequest request, HttpServletResponse response ) throws WorkflowActionFailureException, IOException {
        response.setContentType("text/plain");
        try {

            PublisherAPI publisherAPI = PublisherAPI.getInstance();

            //Read the form values
            String bundleId = request.getParameter( "assetIdentifier" );
            String _contentPushPublishDate = request.getParameter( "remotePublishDate" );
            String _contentPushPublishTime = request.getParameter( "remotePublishTime" );
            String _contentPushExpireDate = request.getParameter( "remotePublishExpireDate" );
            String _contentPushExpireTime = request.getParameter( "remotePublishExpireTime" );
            String _iWantTo = request.getParameter( "iWantTo" );
            String whoToSendTmp = request.getParameter( "whoToSend" );
            List<String> whereToSend = Arrays.asList(whoToSendTmp.split(","));
            List<Environment> envsToSendTo = new ArrayList<Environment>();

            // Lists of Environments to push to
            for (String envId : whereToSend) {
              Environment e = APILocator.getEnvironmentAPI().findEnvironmentById(envId);

              if(e!=null && APILocator.getPermissionAPI().doesUserHavePermission(e, PermissionAPI.PERMISSION_USE, getUser())) {
                envsToSendTo.add(e);
              }
      }

            if(envsToSendTo.isEmpty()) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            //Put the selected environments in session in order to have the list of the last selected environments
            request.getSession().setAttribute( WebKeys.SELECTED_ENVIRONMENTS + getUser().getUserId(), envsToSendTo );
            //Clean up the selected bundle
            request.getSession().removeAttribute( WebKeys.SELECTED_BUNDLE + getUser().getUserId() );

            SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd-H-m" );
            Date publishDate = dateFormat.parse( _contentPushPublishDate + "-" + _contentPushPublishTime );
            Bundle bundle = APILocator.getBundleAPI().getBundleById(bundleId);
            APILocator.getBundleAPI().saveBundleEnvironments(bundle, envsToSendTo);

            if ( _iWantTo.equals( RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH )) {
              bundle.setPublishDate(publishDate);
               APILocator.getBundleAPI().updateBundle(bundle);

               publisherAPI.publishBundleAssets(bundle.getId(), publishDate);

            } else if ( _iWantTo.equals( RemotePublishAjaxAction.DIALOG_ACTION_EXPIRE )) {
              if ( (!"".equals( _contentPushExpireDate.trim() ) && !"".equals( _contentPushExpireTime.trim() )) ) {
                    Date expireDate = dateFormat.parse( _contentPushExpireDate + "-" + _contentPushExpireTime );
                    bundle.setExpireDate(expireDate);
                  APILocator.getBundleAPI().updateBundle(bundle);

                  publisherAPI.unpublishBundleAssets(bundle.getId(), expireDate);
                }

            } else if(_iWantTo.equals( RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH_AND_EXPIRE ) ) {
                if ( (!"".equals( _contentPushExpireDate.trim() ) && !"".equals( _contentPushExpireTime.trim() )) ) {
                    Date expireDate = dateFormat.parse( _contentPushExpireDate + "-" + _contentPushExpireTime );
                    bundle.setPublishDate(publishDate);
                    bundle.setExpireDate(expireDate);
                  APILocator.getBundleAPI().updateBundle(bundle);

                  publisherAPI.publishAndExpireBundleAssets(bundle.getId(), publishDate, expireDate, getUser());
                }
            }

        } catch ( Exception e ) {
            Logger.error( RemotePublishAjaxAction.class, e.getMessage(), e );
View Full Code Here

     * @param assetId Asset identifier
     * @param bundleId Bundle Id
     * @return true if the asset is already included.
     */
    private boolean isAssetInBundle(String assetId, String bundleId){
      PublisherAPI publisherAPI = PublisherAPI.getInstance();
    try {
      List<PublishQueueElement> assets = publisherAPI.getQueueElementsByAsset(assetId);
      for(PublishQueueElement element :  assets){
        if(element.getBundleId().equals(bundleId)){
          return true;
        }
      }
View Full Code Here

  public void retry_issue5097 () throws DotSecurityException, DotDataException, IOException, JSONException, DotPublisherException, InterruptedException {

    EnvironmentAPI environmentAPI = APILocator.getEnvironmentAPI();
    ContentletAPI contentletAPI = APILocator.getContentletAPI();
    PublishingEndPointAPI publisherEndPointAPI = APILocator.getPublisherEndPointAPI();
    PublisherAPI publisherAPI = PublisherAPI.getInstance();

    HttpServletRequest req = ServletTestRunner.localRequest.get();

    Environment environment = new Environment();
    environment.setName( "TestEnvironment_" + String.valueOf( new Date().getTime() ) );
    environment.setPushToAll( false );

    //Find the roles of the admin user
    Role role = APILocator.getRoleAPI().loadRoleByKey( adminUser.getUserId() );

    //Create the permissions for the environment
    List<Permission> permissions = new ArrayList<Permission>();
    Permission p = new Permission( environment.getId(), role.getId(), PermissionAPI.PERMISSION_USE );
    permissions.add( p );

    //Create a environment
    environmentAPI.saveEnvironment( environment, permissions );

    //Now we need to create the end point
    PublishingEndPoint endpoint = new PublishingEndPoint();
    endpoint.setServerName( new StringBuilder( "TestEndPoint" + String.valueOf( new Date().getTime() ) ) );
    endpoint.setAddress( "127.0.0.1" );
    endpoint.setPort( "999" );
    endpoint.setProtocol( "http" );
    endpoint.setAuthKey( new StringBuilder( PublicEncryptionFactory.encryptString( "1111" ) ) );
    endpoint.setEnabled( true );
    endpoint.setSending( false );//TODO: Shouldn't this be true as we are creating this end point to send bundles to another server..?
    endpoint.setGroupId( environment.getId() );
    //Save the endpoint.
    publisherEndPointAPI.saveEndPoint( endpoint );

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //++++++++++++++++++++++++++++++PUBLISH++++++++++++++++++++++++++++

    //Getting test data
    List<Contentlet> contentlets = contentletAPI.findAllContent( 0, 1 );
    //Validations
    assertNotNull( contentlets );
    assertEquals( contentlets.size(), 1 );

    //Preparing the url in order to push content
    SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
    SimpleDateFormat timeFormat = new SimpleDateFormat( "H-m" );
    String publishDate = dateFormat.format( new Date() );
    String publishTime = timeFormat.format( new Date() );

    String baseURL = "http://" + req.getServerName() + ":" + req.getServerPort() + "/DotAjaxDirector/com.dotcms.publisher.ajax.RemotePublishAjaxAction/cmd/publish/u/admin@dotcms.com/p/admin";
    String completeURL = baseURL +
        "?remotePublishDate=" + UtilMethods.encodeURIComponent( publishDate ) +
        "&remotePublishTime=" + UtilMethods.encodeURIComponent( publishTime ) +
        "&remotePublishExpireDate=" +
        "&remotePublishExpireTime=" +
        "&iWantTo=" + RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH +
        "&whoToSend=" + UtilMethods.encodeURIComponent( environment.getId() ) +
        "&forcePush=false" +
        "&assetIdentifier=" + UtilMethods.encodeURIComponent( contentlets.get( 0 ).getIdentifier() );

    //Execute the call
    URL publishUrl = new URL( completeURL );
    String response = IOUtils.toString( publishUrl.openStream(), "UTF-8" );
    //Validations
    JSONObject jsonResponse = new JSONObject( response );
    assertNotNull( contentlets );
    assertEquals( jsonResponse.getInt( "errors" ), 0 );
    assertEquals( jsonResponse.getInt( "total" ), 1 );
    assertNotNull( jsonResponse.get( "bundleId" ) );

    //Now that we have a bundle id
    String bundleId = jsonResponse.getString( "bundleId" );
    //First we need to verify if this bundle is in the queue job
    List<PublishQueueElement> foundBundles = publisherAPI.getQueueElementsByBundleId( bundleId );
    assertNotNull( foundBundles );
    assertTrue( !foundBundles.isEmpty() );

    /*
         Now lets wait until it finished, by the way, we are expecting it to fail to publish as the end point does not exist.
         Keep in mind the queue will try 3 times before to marked as failed to publish, so we have to wait a bit here....
     */
    int x = 0;
    do {
      Thread.sleep( 3000 );
      //Verify if it continues in the queue job
      foundBundles = publisherAPI.getQueueElementsByBundleId( bundleId );
      x++;
    } while ( (foundBundles != null && !foundBundles.isEmpty()) && x < 200 );
    //At this points should not be here anymore
    foundBundles = publisherAPI.getQueueElementsByBundleId( bundleId );
    assertTrue( foundBundles == null || foundBundles.isEmpty() );

    //Get the audit records related to this bundle
    PublishAuditStatus status = PublishAuditAPI.getInstance().getPublishAuditStatus( bundleId );
    //We will be able to retry failed and successfully bundles
    assertEquals( status.getStatus(), PublishAuditStatus.Status.FAILED_TO_PUBLISH ); //Remember, we are expecting this to fail

    //Get current status dates
    Date initialCreationDate = status.getCreateDate();
    Date initialUpdateDate = status.getStatusUpdated();

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //++++++++++++++++++++++++++++++RETRY++++++++++++++++++++++++++++++
    //Now we can try the retry
    req = ServletTestRunner.localRequest.get();
    baseURL = "http://" + req.getServerName() + ":" + req.getServerPort() + "/DotAjaxDirector/com.dotcms.publisher.ajax.RemotePublishAjaxAction/cmd/retry/u/admin@dotcms.com/p/admin";
    completeURL = baseURL + "?bundlesIds=" + UtilMethods.encodeURIComponent( bundleId );

    //Execute the call
    URL retryUrl = new URL( completeURL );
    response = IOUtils.toString( retryUrl.openStream(), "UTF-8" );//We can expect something like "Bundle id: <strong>1193e3eb-3ccd-496e-8995-29a9fcc48cbd</strong> added successfully to Publishing Queue."
    //Validations
    assertNotNull( response );
    assertTrue( response.contains( bundleId ) );
    assertTrue( response.contains( "added successfully to" ) );

    //And should be back to the queue job
    foundBundles = publisherAPI.getQueueElementsByBundleId( bundleId );
    assertNotNull( foundBundles );
    assertTrue( !foundBundles.isEmpty() );

    //Get current status dates
    status = PublishAuditAPI.getInstance().getPublishAuditStatus( bundleId );//Get the audit records related to this bundle
View Full Code Here

     * Generate test environment
     */
    //Preparing the url in order to push content
    EnvironmentAPI environmentAPI = APILocator.getEnvironmentAPI();
    PublishingEndPointAPI publisherEndPointAPI = APILocator.getPublisherEndPointAPI();
    PublisherAPI publisherAPI = PublisherAPI.getInstance();

    HttpServletRequest req = ServletTestRunner.localRequest.get();

    Environment environment = new Environment();
    environment.setName( "TestEnvironment_" + String.valueOf( new Date().getTime() ) );
    environment.setPushToAll( false );

    /*
     * Find the roles of the admin user
     */
    Role role = APILocator.getRoleAPI().loadRoleByKey( adminUser.getUserId() );

    //Create the permissions for the environment
    List<Permission> permissions = new ArrayList<Permission>();
    Permission p = new Permission( environment.getId(), role.getId(), PermissionAPI.PERMISSION_USE );
    permissions.add( p );

    /*
     * Create a environment
     */
    environmentAPI.saveEnvironment( environment, permissions );

    /*
     * Now we need to create the end point
     */
    PublishingEndPoint endpoint = new PublishingEndPoint();
    endpoint.setServerName( new StringBuilder( "TestEndPoint" + String.valueOf( new Date().getTime() ) ) );
    endpoint.setAddress( "127.0.0.1" );
    endpoint.setPort( "999" );
    endpoint.setProtocol( "http" );
    endpoint.setAuthKey( new StringBuilder( PublicEncryptionFactory.encryptString( "1111" ) ) );
    endpoint.setEnabled( true );
    endpoint.setSending( false );//TODO: Shouldn't this be true as we are creating this end point to send bundles to another server..?
    endpoint.setGroupId( environment.getId() );
    /*
     * Save the endpoint.
     */
    publisherEndPointAPI.saveEndPoint( endpoint );
    SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
    SimpleDateFormat timeFormat = new SimpleDateFormat( "H-m" );
    String publishDate = dateFormat.format( new Date() );
    String publishTime = timeFormat.format( new Date() );

    String baseURL = "http://" + req.getServerName() + ":" + req.getServerPort() + "/DotAjaxDirector/com.dotcms.publisher.ajax.RemotePublishAjaxAction/cmd/publish/u/admin@dotcms.com/p/admin";
    String completeURL = baseURL +
        "?remotePublishDate=" + UtilMethods.encodeURIComponent( publishDate ) +
        "&remotePublishTime=" + UtilMethods.encodeURIComponent( publishTime ) +
        "&remotePublishExpireDate=" +
        "&remotePublishExpireTime=" +
        "&iWantTo=" + RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH +
        "&whoToSend=" + UtilMethods.encodeURIComponent( environment.getId() ) +
        "&forcePush=false" +
        "&assetIdentifier=" + UtilMethods.encodeURIComponent( folder.getInode() );

    /*
     * Execute the call
     */
    URL publishUrl = new URL( completeURL );
    String response = IOUtils.toString( publishUrl.openStream(), "UTF-8" );
    /*
     * Validations
     */
    JSONObject jsonResponse = new JSONObject( response );
    assertEquals( jsonResponse.getInt( "errors" ), 0 );
    assertEquals( jsonResponse.getInt( "total" ), 1 );
    assertNotNull( jsonResponse.get( "bundleId" ) );

    /*
     * Now that we have a bundle id
     */
    String bundleId = jsonResponse.getString( "bundleId" );
    /*
     * First we need to verify if this bundle is in the queue job
     */
    List<PublishQueueElement> foundBundles = publisherAPI.getQueueElementsByBundleId( bundleId );
    assertNotNull( foundBundles );
    assertTrue( !foundBundles.isEmpty() );

    /*
     *        Now lets wait until it finished, by the way, we are expecting it to fail to publish as the end point does not exist.
     *        Keep in mind the queue will try 3 times before to marked as failed to publish, so we have to wait a bit here....
     */
    int x = 0;
    do {
      Thread.sleep( 3000 );
      /*
       * Verify if it continues in the queue job
       */
      foundBundles = publisherAPI.getQueueElementsByBundleId( bundleId );
      x++;
    } while ( (foundBundles != null && !foundBundles.isEmpty()) && x < 200 );
    /*
     * At this points should not be here anymore
     */
 
View Full Code Here

     * Generate test environment
     */
    //Preparing the url in order to push content
    EnvironmentAPI environmentAPI = APILocator.getEnvironmentAPI();
    PublishingEndPointAPI publisherEndPointAPI = APILocator.getPublisherEndPointAPI();
    PublisherAPI publisherAPI = PublisherAPI.getInstance();

    HttpServletRequest req = ServletTestRunner.localRequest.get();

    Environment environment = new Environment();
    environment.setName( "TestEnvironment_" + String.valueOf( new Date().getTime() ) );
    environment.setPushToAll( false );

    /*
     * Find the roles of the admin user
     */
    Role role = APILocator.getRoleAPI().loadRoleByKey( adminUser.getUserId() );

    //Create the permissions for the environment
    List<Permission> permissions = new ArrayList<Permission>();
    Permission p = new Permission( environment.getId(), role.getId(), PermissionAPI.PERMISSION_USE );
    permissions.add( p );

    /*
     * Create a environment
     */
    environmentAPI.saveEnvironment( environment, permissions );

    /*
     * Now we need to create the end point
     */
    PublishingEndPoint endpoint = new PublishingEndPoint();
    endpoint.setServerName( new StringBuilder( "TestEndPoint" + String.valueOf( new Date().getTime() ) ) );
    endpoint.setAddress( "127.0.0.1" );
    endpoint.setPort( "9999" );
    endpoint.setProtocol( "http" );
    endpoint.setAuthKey( new StringBuilder( PublicEncryptionFactory.encryptString( "1111" ) ) );
    endpoint.setEnabled( true );
    endpoint.setSending( false );//TODO: Shouldn't this be true as we are creating this end point to send bundles to another server..?
    endpoint.setGroupId( environment.getId() );
    /*
     * Save the endpoint.
     */
    publisherEndPointAPI.saveEndPoint( endpoint );
    SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
    SimpleDateFormat timeFormat = new SimpleDateFormat( "H-m" );
    String publishDate = dateFormat.format( new Date() );
    String publishTime = timeFormat.format( new Date() );

    String baseURL = "http://" + req.getServerName() + ":" + req.getServerPort() + "/DotAjaxDirector/com.dotcms.publisher.ajax.RemotePublishAjaxAction/cmd/publish/u/admin@dotcms.com/p/admin";
    String completeURL = baseURL +
        "?remotePublishDate=" + UtilMethods.encodeURIComponent( publishDate ) +
        "&remotePublishTime=" + UtilMethods.encodeURIComponent( publishTime ) +
        "&remotePublishExpireDate=" +
        "&remotePublishExpireTime=" +
        "&iWantTo=" + RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH +
        "&whoToSend=" + UtilMethods.encodeURIComponent( environment.getId() ) +
        "&forcePush=false" +
        "&assetIdentifier=" + UtilMethods.encodeURIComponent( folder.getInode() );

    /*
     * Execute the call
     */
    URL publishUrl = new URL( completeURL );
    String response = IOUtils.toString( publishUrl.openStream(), "UTF-8" );
    /*
     * Validations
     */
    JSONObject jsonResponse = new JSONObject( response );
    assertEquals( jsonResponse.getInt( "errors" ), 0 );
    assertEquals( jsonResponse.getInt( "total" ), 1 );
    assertNotNull( jsonResponse.get( "bundleId" ) );

    /*
     * Now that we have a bundle id
     */
    String bundleId = jsonResponse.getString( "bundleId" );
    /*
     * First we need to verify if this bundle is in the queue job
     */
    List<PublishQueueElement> foundBundles = publisherAPI.getQueueElementsByBundleId( bundleId );
    assertNotNull( foundBundles );
    assertTrue( !foundBundles.isEmpty() );

    /*
     *        Now lets wait until it finished, by the way, we are expecting it to fail to publish as the end point does not exist.
     *        Keep in mind the queue will try 3 times before to marked as failed to publish, so we have to wait a bit here....
     */
    int x = 0;
    do {
      Thread.sleep( 3000 );
      /*
       * Verify if it continues in the queue job
       */
      foundBundles = publisherAPI.getQueueElementsByBundleId( bundleId );
      x++;
    } while ( (foundBundles != null && !foundBundles.isEmpty()) && x < 200 );
    /*
     * At this points should not be here anymore
     */
 
View Full Code Here

TOP

Related Classes of com.dotcms.publisher.business.PublisherAPI

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.