Example usage for org.apache.http.client.utils URIUtils resolve

List of usage examples for org.apache.http.client.utils URIUtils resolve

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIUtils resolve.

Prototype

public static URI resolve(final URI baseURI, final URI reference) 

Source Link

Document

Resolves a URI reference against a base URI.

Usage

From source file:spaceRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }/*from   w  ww.j  a v  a2s .c o m*/
    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue().replaceAll(" ", "%20");
    ;
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri = createLocationURI(location);

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }
        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            //redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:com.amos.tool.SelfRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    Args.notNull(request, "HTTP request");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    //get the location header to find out where to redirect to
    final Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }//from  w w  w  .java2 s  .c om
    final String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    final RequestConfig config = clientContext.getRequestConfig();

    URI uri = createLocationURI(location.replaceAll(" ", "%20"));

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (!config.isRelativeRedirectsAllowed()) {
                throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            final HttpHost target = clientContext.getTargetHost();
            Asserts.notNull(target, "Target host");
            final URI requestURI = new URI(request.getRequestLine().getUri());
            final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (final URISyntaxException ex) {
        throw new ProtocolException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute(HttpClientContext.REDIRECT_LOCATIONS);
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations);
    }
    if (!config.isCircularRedirectsAllowed()) {
        if (redirectLocations.contains(uri)) {
            throw new CircularRedirectException("Circular redirect to '" + uri + "'");
        }
    }
    redirectLocations.add(uri);
    return uri;
}

From source file:com.norconex.collector.http.url.impl.GenericCanonicalLinkDetector.java

private String toAbsolute(String pageReference, String link) {
    if (link == null) {
        return null;
    }//from   www .  ja  va  2s. c om
    if (link.matches("^https{0,1}://")) {
        return link;
    }
    return URIUtils.resolve(URI.create(pageReference), StringEscapeUtils.unescapeHtml4(link)).toString();
}

From source file:com.basistech.m2e.code.quality.pmd.MavenPluginConfigurationTranslator.java

private List<String> convertFileFoldersToRelativePathStrings(final Iterable<? extends File> sources) {
    final List<String> folders = new ArrayList<String>();
    //No null check as internally we *know*
    for (File f : sources) {
        String relativePath;//from w w w  .j  a  v  a 2  s . c om
        if (!f.isAbsolute()) {
            relativePath = URIUtils.resolve(this.basedirUri, f.toURI()).getPath();
            //TODO this.basedirUri.relativize(f.toURI()).getPath();
        } else {
            relativePath = f.getAbsolutePath();
        }

        if ("\\".equals(File.separator)) {
            relativePath = relativePath.replace("\\", "/");
        }
        if (relativePath.endsWith("/")) {
            relativePath = relativePath.substring(0, relativePath.length() - 1);
        }
        // we append the .* pattern regardless
        relativePath = relativePath + ".*";
        folders.add(relativePath);
    }
    return folders;
}

From source file:org.sonatype.nexus.internal.httpclient.HttpClientManagerImpl.java

/**
 * Creates absolute request URI with full path from passed in context.
 *///from w w w .  j ava2 s .co m
@Nonnull
private URI getRequestURI(final HttpContext context) {
    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final HttpRequest httpRequest = clientContext.getRequest();
    final HttpHost target = clientContext.getTargetHost();
    try {
        URI uri;
        if (httpRequest instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) httpRequest).getURI();
        } else {
            uri = URI.create(httpRequest.getRequestLine().getUri());
        }
        return uri.isAbsolute() ? uri : URIUtils.resolve(URI.create(target.toURI()), uri);
    } catch (Exception e) {
        log.warn("Could not create absolute request URI", e);
        return URI.create(target.toURI());
    }
}

From source file:czd.lib.network.AsyncHttpClient.java

/**
 * Simple interface method, to enable or disable redirects. If you set manually RedirectHandler
 * on underlying HttpClient, effects of this method will be canceled.
 *
 * @param enableRedirects boolean//  ww  w  .  j  av  a2 s.c o m
 */
public void setEnableRedirects(final boolean enableRedirects) {
    if (enableRedirects) {
        httpClient.setRedirectHandler(new DefaultRedirectHandler() {
            @Override
            public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
                if (response == null) {
                    throw new IllegalArgumentException("HTTP response may not be null");
                }
                int statusCode = response.getStatusLine().getStatusCode();
                switch (statusCode) {
                case HttpStatus.SC_MOVED_TEMPORARILY:
                case HttpStatus.SC_MOVED_PERMANENTLY:
                case HttpStatus.SC_SEE_OTHER:
                case HttpStatus.SC_TEMPORARY_REDIRECT:
                    return true;
                default:
                    return false;
                }
            }

            @Override
            public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
                if (response == null) {
                    throw new IllegalArgumentException("HTTP response may not be null");
                }
                //get the location header to find out where to redirect to
                Header locationHeader = response.getFirstHeader("location");
                if (locationHeader == null) {
                    // got a redirect response, but no location header
                    throw new ProtocolException("Received redirect response " + response.getStatusLine()
                            + " but no location header");
                }
                //HERE IS THE MODIFIED LINE OF CODE
                String location = locationHeader.getValue().replaceAll(" ", "%20");

                URI uri;
                try {
                    uri = new URI(location);
                } catch (URISyntaxException ex) {
                    throw new ProtocolException("Invalid redirect URI: " + location, ex);
                }

                HttpParams params = response.getParams();
                // rfc2616 demands the location value be a complete URI
                // Location       = "Location" ":" absoluteURI
                if (!uri.isAbsolute()) {
                    if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
                        throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
                    }
                    // Adjust location URI
                    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
                    if (target == null) {
                        throw new IllegalStateException("Target host not available " + "in the HTTP context");
                    }

                    HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

                    try {
                        URI requestURI = new URI(request.getRequestLine().getUri());
                        URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
                        uri = URIUtils.resolve(absoluteRequestURI, uri);
                    } catch (URISyntaxException ex) {
                        throw new ProtocolException(ex.getMessage(), ex);
                    }
                }

                if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

                    RedirectLocations redirectLocations = (RedirectLocations) context
                            .getAttribute("http.protocol.redirect-locations");

                    if (redirectLocations == null) {
                        redirectLocations = new RedirectLocations();
                        context.setAttribute("http.protocol.redirect-locations", redirectLocations);
                    }

                    URI redirectURI;
                    if (uri.getFragment() != null) {
                        try {
                            HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                            redirectURI = URIUtils.rewriteURI(uri, target, true);
                        } catch (URISyntaxException ex) {
                            throw new ProtocolException(ex.getMessage(), ex);
                        }
                    } else {
                        redirectURI = uri;
                    }

                    if (redirectLocations.contains(redirectURI)) {
                        throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
                    } else {
                        redirectLocations.add(redirectURI);
                    }
                }

                return uri;
            }
        });
    }

}

From source file:org.opencastproject.workflow.handler.PublishEngageWorkflowOperationHandler.java

/**
 * {@inheritDoc}/*from w  ww  . j  a  v a2s .com*/
 * 
 * @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance,
 *      JobContext)
 */
@Override
public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context)
        throws WorkflowOperationException {
    logger.debug("Running engage publication workflow operation");

    MediaPackage mediaPackage = workflowInstance.getMediaPackage();
    WorkflowOperationInstance op = workflowInstance.getCurrentOperation();

    // Check which tags have been configured
    String downloadSourceTags = StringUtils.trimToEmpty(op.getConfiguration(DOWNLOAD_SOURCE_TAGS));
    String downloadTargetTags = StringUtils.trimToEmpty(op.getConfiguration(DOWNLOAD_TARGET_TAGS));
    String downloadSourceFlavors = StringUtils.trimToEmpty(op.getConfiguration(DOWNLOAD_SOURCE_FLAVORS));
    String downloadTargetSubflavor = StringUtils.trimToNull(op.getConfiguration(DOWNLOAD_TARGET_SUBFLAVOR));
    String streamingSourceTags = StringUtils.trimToEmpty(op.getConfiguration(STREAMING_SOURCE_TAGS));
    String streamingTargetTags = StringUtils.trimToEmpty(op.getConfiguration(STREAMING_TARGET_TAGS));
    String streamingSourceFlavors = StringUtils.trimToEmpty(op.getConfiguration(STREAMING_SOURCE_FLAVORS));
    String streamingTargetSubflavor = StringUtils.trimToNull(op.getConfiguration(STREAMING_TARGET_SUBFLAVOR));
    boolean checkAvailability = option(op.getConfiguration(CHECK_AVAILABILITY)).bind(trimToNone).map(toBool)
            .getOrElse(true);

    String[] sourceDownloadTags = StringUtils.split(downloadSourceTags, ",");
    String[] targetDownloadTags = StringUtils.split(downloadTargetTags, ",");
    String[] sourceDownloadFlavors = StringUtils.split(downloadSourceFlavors, ",");
    String[] sourceStreamingTags = StringUtils.split(streamingSourceTags, ",");
    String[] targetStreamingTags = StringUtils.split(streamingTargetTags, ",");
    String[] sourceStreamingFlavors = StringUtils.split(streamingSourceFlavors, ",");

    if (sourceDownloadTags.length == 0 && sourceDownloadFlavors.length == 0 && sourceStreamingTags.length == 0
            && sourceStreamingFlavors.length == 0) {
        logger.warn(
                "No tags or flavors have been specified, so nothing will be published to the engage publication channel");
        return createResult(mediaPackage, Action.CONTINUE);
    }

    // Parse the download target flavor
    MediaPackageElementFlavor downloadSubflavor = null;
    if (downloadTargetSubflavor != null) {
        try {
            downloadSubflavor = MediaPackageElementFlavor.parseFlavor(downloadTargetSubflavor);
        } catch (IllegalArgumentException e) {
            throw new WorkflowOperationException(e);
        }
    }

    // Parse the streaming target flavor
    MediaPackageElementFlavor streamingSubflavor = null;
    if (streamingTargetSubflavor != null) {
        try {
            streamingSubflavor = MediaPackageElementFlavor.parseFlavor(streamingTargetSubflavor);
        } catch (IllegalArgumentException e) {
            throw new WorkflowOperationException(e);
        }
    }

    // Configure the download element selector
    SimpleElementSelector downloadElementSelector = new SimpleElementSelector();
    for (String flavor : sourceDownloadFlavors) {
        downloadElementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
    }
    for (String tag : sourceDownloadTags) {
        downloadElementSelector.addTag(tag);
    }

    // Configure the streaming element selector
    SimpleElementSelector streamingElementSelector = new SimpleElementSelector();
    for (String flavor : sourceStreamingFlavors) {
        streamingElementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
    }
    for (String tag : sourceStreamingTags) {
        streamingElementSelector.addTag(tag);
    }

    // Select the appropriate elements for download and streaming
    Collection<MediaPackageElement> downloadElements = downloadElementSelector.select(mediaPackage, false);
    Collection<MediaPackageElement> streamingElements = streamingElementSelector.select(mediaPackage, false);

    try {
        Set<String> downloadElementIds = new HashSet<String>();
        Set<String> streamingElementIds = new HashSet<String>();

        // Look for elements matching the tag
        for (MediaPackageElement elem : downloadElements) {
            downloadElementIds.add(elem.getIdentifier());
        }
        for (MediaPackageElement elem : streamingElements) {
            streamingElementIds.add(elem.getIdentifier());
        }

        // Also distribute the security configuration
        // -----
        // This was removed in the meantime by a fix for MH-8515, but could now be used again.
        // -----
        Attachment[] securityAttachments = mediaPackage.getAttachments(MediaPackageElements.XACML_POLICY);
        if (securityAttachments != null && securityAttachments.length > 0) {
            for (Attachment a : securityAttachments) {
                downloadElementIds.add(a.getIdentifier());
                streamingElementIds.add(a.getIdentifier());
            }
        }

        List<Job> jobs = new ArrayList<Job>();
        try {
            for (String elementId : downloadElementIds) {
                Job job = downloadDistributionService.distribute(CHANNEL_ID, mediaPackage, elementId,
                        checkAvailability);
                if (job == null)
                    continue;
                jobs.add(job);
            }
            if (distributeStreaming) {
                for (String elementId : streamingElementIds) {
                    Job job = streamingDistributionService.distribute(CHANNEL_ID, mediaPackage, elementId);
                    if (job == null)
                        continue;
                    jobs.add(job);
                }
            }
        } catch (DistributionException e) {
            throw new WorkflowOperationException(e);
        }

        if (jobs.size() < 1) {
            logger.info("No mediapackage element was found for distribution to engage");
            return createResult(mediaPackage, Action.CONTINUE);
        }

        // Wait until all distribution jobs have returned
        if (!waitForStatus(jobs.toArray(new Job[jobs.size()])).isSuccess())
            throw new WorkflowOperationException("One of the distribution jobs did not complete successfully");

        logger.debug("Distribute of mediapackage {} completed", mediaPackage);

        try {
            MediaPackage mediaPackageForSearch = getMediaPackageForSearchIndex(mediaPackage, jobs,
                    downloadSubflavor, targetDownloadTags, downloadElementIds, streamingSubflavor,
                    streamingElementIds, targetStreamingTags);
            if (!isPublishable(mediaPackageForSearch))
                throw new WorkflowOperationException("Media package does not meet criteria for publication");

            logger.info("Publishing media package {} to search index", mediaPackageForSearch);

            // Create new distribution element
            URI engageUri = URIUtils.resolve(engageBaseUrl.toURI(),
                    "/engage/ui/watch.html?id=" + mediaPackage.getIdentifier().compact());
            Publication publicationElement = PublicationImpl.publication(UUID.randomUUID().toString(),
                    CHANNEL_ID, engageUri, MimeTypes.parseMimeType("text/html"));
            mediaPackage.add(publicationElement);

            // Adding media package to the search index
            Job publishJob = null;
            try {
                publishJob = searchService.add(mediaPackageForSearch);
                if (!waitForStatus(publishJob).isSuccess()) {
                    throw new WorkflowOperationException("Mediapackage " + mediaPackageForSearch.getIdentifier()
                            + " could not be published");
                }
            } catch (SearchException e) {
                throw new WorkflowOperationException("Error publishing media package", e);
            } catch (MediaPackageException e) {
                throw new WorkflowOperationException("Error parsing media package", e);
            }

            logger.debug("Publishing of mediapackage {} completed", mediaPackage);
            return createResult(mediaPackage, Action.CONTINUE);
        } catch (Throwable t) {
            if (t instanceof WorkflowOperationException)
                throw (WorkflowOperationException) t;
            else
                throw new WorkflowOperationException(t);
        }
    } catch (Exception e) {
        if (e instanceof WorkflowOperationException) {
            throw (WorkflowOperationException) e;
        } else {
            throw new WorkflowOperationException(e);
        }
    }
}

From source file:org.opencastproject.workflow.handler.distribution.PublishEngageWorkflowOperationHandler.java

/**
 * {@inheritDoc}//from  w  w  w .j av  a2s  .c o  m
 *
 * @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance,
 *      JobContext)
 */
@Override
public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context)
        throws WorkflowOperationException {
    logger.debug("Running engage publication workflow operation");

    MediaPackage mediaPackage = workflowInstance.getMediaPackage();
    WorkflowOperationInstance op = workflowInstance.getCurrentOperation();

    // Check which tags have been configured
    String downloadSourceTags = StringUtils.trimToEmpty(op.getConfiguration(DOWNLOAD_SOURCE_TAGS));
    String downloadTargetTags = StringUtils.trimToEmpty(op.getConfiguration(DOWNLOAD_TARGET_TAGS));
    String downloadSourceFlavors = StringUtils.trimToEmpty(op.getConfiguration(DOWNLOAD_SOURCE_FLAVORS));
    String downloadTargetSubflavor = StringUtils.trimToNull(op.getConfiguration(DOWNLOAD_TARGET_SUBFLAVOR));
    String streamingSourceTags = StringUtils.trimToEmpty(op.getConfiguration(STREAMING_SOURCE_TAGS));
    String streamingTargetTags = StringUtils.trimToEmpty(op.getConfiguration(STREAMING_TARGET_TAGS));
    String streamingSourceFlavors = StringUtils.trimToEmpty(op.getConfiguration(STREAMING_SOURCE_FLAVORS));
    String streamingTargetSubflavor = StringUtils.trimToNull(op.getConfiguration(STREAMING_TARGET_SUBFLAVOR));
    boolean checkAvailability = option(op.getConfiguration(CHECK_AVAILABILITY)).bind(trimToNone).map(toBool)
            .getOrElse(true);

    String[] sourceDownloadTags = StringUtils.split(downloadSourceTags, ",");
    String[] targetDownloadTags = StringUtils.split(downloadTargetTags, ",");
    String[] sourceDownloadFlavors = StringUtils.split(downloadSourceFlavors, ",");
    String[] sourceStreamingTags = StringUtils.split(streamingSourceTags, ",");
    String[] targetStreamingTags = StringUtils.split(streamingTargetTags, ",");
    String[] sourceStreamingFlavors = StringUtils.split(streamingSourceFlavors, ",");

    if (sourceDownloadTags.length == 0 && sourceDownloadFlavors.length == 0 && sourceStreamingTags.length == 0
            && sourceStreamingFlavors.length == 0) {
        logger.warn(
                "No tags or flavors have been specified, so nothing will be published to the engage publication channel");
        return createResult(mediaPackage, Action.CONTINUE);
    }

    // Parse the download target flavor
    MediaPackageElementFlavor downloadSubflavor = null;
    if (downloadTargetSubflavor != null) {
        try {
            downloadSubflavor = MediaPackageElementFlavor.parseFlavor(downloadTargetSubflavor);
        } catch (IllegalArgumentException e) {
            throw new WorkflowOperationException(e);
        }
    }

    // Parse the streaming target flavor
    MediaPackageElementFlavor streamingSubflavor = null;
    if (streamingTargetSubflavor != null) {
        try {
            streamingSubflavor = MediaPackageElementFlavor.parseFlavor(streamingTargetSubflavor);
        } catch (IllegalArgumentException e) {
            throw new WorkflowOperationException(e);
        }
    }

    // Configure the download element selector
    SimpleElementSelector downloadElementSelector = new SimpleElementSelector();
    for (String flavor : sourceDownloadFlavors) {
        downloadElementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
    }
    for (String tag : sourceDownloadTags) {
        downloadElementSelector.addTag(tag);
    }

    // Configure the streaming element selector
    SimpleElementSelector streamingElementSelector = new SimpleElementSelector();
    for (String flavor : sourceStreamingFlavors) {
        streamingElementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
    }
    for (String tag : sourceStreamingTags) {
        streamingElementSelector.addTag(tag);
    }

    // Select the appropriate elements for download and streaming
    Collection<MediaPackageElement> downloadElements = downloadElementSelector.select(mediaPackage, false);
    Collection<MediaPackageElement> streamingElements = streamingElementSelector.select(mediaPackage, false);

    try {
        Set<String> downloadElementIds = new HashSet<String>();
        Set<String> streamingElementIds = new HashSet<String>();

        // Look for elements matching the tag
        for (MediaPackageElement elem : downloadElements) {
            downloadElementIds.add(elem.getIdentifier());
        }
        for (MediaPackageElement elem : streamingElements) {
            streamingElementIds.add(elem.getIdentifier());
        }

        // Also distribute the security configuration
        // -----
        // This was removed in the meantime by a fix for MH-8515, but could now be used again.
        // -----
        Attachment[] securityAttachments = mediaPackage.getAttachments(MediaPackageElements.XACML_POLICY);
        if (securityAttachments != null && securityAttachments.length > 0) {
            for (Attachment a : securityAttachments) {
                downloadElementIds.add(a.getIdentifier());
                streamingElementIds.add(a.getIdentifier());
            }
        }

        List<Job> jobs = new ArrayList<Job>();
        try {
            for (String elementId : downloadElementIds) {
                logger.info("Element distribution delay, sleeping for " + Integer.toString(distributionDelay));
                Thread.sleep(distributionDelay);
                Job job = downloadDistributionService.distribute(CHANNEL_ID, mediaPackage, elementId,
                        checkAvailability);
                if (job != null)
                    jobs.add(job);
            }
            if (distributeStreaming) {
                for (String elementId : streamingElementIds) {
                    Job job = streamingDistributionService.distribute(CHANNEL_ID, mediaPackage, elementId);
                    if (job != null)
                        jobs.add(job);
                }
            }
        } catch (DistributionException e) {
            throw new WorkflowOperationException(e);
        }

        if (jobs.size() < 1) {
            logger.info("No mediapackage element was found for distribution to engage");
            return createResult(mediaPackage, Action.CONTINUE);
        }

        // Wait until all distribution jobs have returned
        if (!waitForStatus(jobs.toArray(new Job[jobs.size()])).isSuccess())
            throw new WorkflowOperationException("One of the distribution jobs did not complete successfully");

        logger.debug("Distribute of mediapackage {} completed", mediaPackage);

        String engageUrlString = null;
        try {
            MediaPackage mediaPackageForSearch = getMediaPackageForSearchIndex(mediaPackage, jobs,
                    downloadSubflavor, targetDownloadTags, downloadElementIds, streamingSubflavor,
                    streamingElementIds, targetStreamingTags);

            // MH-10216, check if only merging into existing mediapackage
            boolean merge = Boolean
                    .parseBoolean(workflowInstance.getCurrentOperation().getConfiguration(OPT_MERGE_ONLY));
            if (merge) {
                // merge() returns merged mediapackage or null mediaPackage is not published
                mediaPackageForSearch = merge(mediaPackageForSearch);
                if (mediaPackageForSearch == null) {
                    logger.info("Skipping republish for {} since it is not currently published",
                            mediaPackage.getIdentifier().toString());
                    return createResult(mediaPackage, Action.SKIP);
                }
            }

            if (!isPublishable(mediaPackageForSearch))
                throw new WorkflowOperationException("Media package does not meet criteria for publication");

            logger.info("Publishing media package {} to search index", mediaPackageForSearch);

            URL engageBaseUrl = null;
            engageUrlString = StringUtils
                    .trimToNull(workflowInstance.getOrganization().getProperties().get(ENGAGE_URL_PROPERTY));
            if (engageUrlString != null) {
                engageBaseUrl = new URL(engageUrlString);
            } else {
                engageBaseUrl = serverUrl;
                logger.info(
                        "Using 'server.url' as a fallback for the non-existing organization level key '{}' for the publication url",
                        ENGAGE_URL_PROPERTY);
            }

            // Create new distribution element
            URI engageUri = URIUtils.resolve(engageBaseUrl.toURI(),
                    "/engage/ui/watch.html?id=" + mediaPackage.getIdentifier().compact());
            Publication publicationElement = PublicationImpl.publication(UUID.randomUUID().toString(),
                    CHANNEL_ID, engageUri, MimeTypes.parseMimeType("text/html"));
            mediaPackage.add(publicationElement);

            // Adding media package to the search index
            Job publishJob = null;
            try {
                publishJob = searchService.add(mediaPackageForSearch);
                if (!waitForStatus(publishJob).isSuccess()) {
                    throw new WorkflowOperationException("Mediapackage " + mediaPackageForSearch.getIdentifier()
                            + " could not be published");
                }
            } catch (SearchException e) {
                throw new WorkflowOperationException("Error publishing media package", e);
            } catch (MediaPackageException e) {
                throw new WorkflowOperationException("Error parsing media package", e);
            }

            logger.debug("Publishing of mediapackage {} completed", mediaPackage);
            return createResult(mediaPackage, Action.CONTINUE);
        } catch (MalformedURLException e) {
            logger.error("{} is malformed: {}", ENGAGE_URL_PROPERTY, engageUrlString);
            throw new WorkflowOperationException(e);
        } catch (Throwable t) {
            if (t instanceof WorkflowOperationException)
                throw (WorkflowOperationException) t;
            else
                throw new WorkflowOperationException(t);
        }
    } catch (Exception e) {
        if (e instanceof WorkflowOperationException) {
            throw (WorkflowOperationException) e;
        } else {
            throw new WorkflowOperationException(e);
        }
    }
}

From source file:com.googlecode.jdeltasync.DeltaSyncClient.java

/**
 * Slightly modified version of {@link DefaultRedirectStrategy#getLocationURI(HttpRequest, HttpResponse, HttpContext)}
 * which also adds the query string from the original request URI to the new URI.
 *///from w  w w .j av a 2 s  .co  m
private URI getRedirectLocationURI(IDeltaSyncSession session, HttpUriRequest request, HttpResponse response,
        HttpContext context) throws DeltaSyncException {

    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new DeltaSyncException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue();
    if (session.getLogger().isDebugEnabled()) {
        session.getLogger().debug("Redirect requested to location '" + location + "'");
    }

    URI uri = null;
    try {
        uri = new URI(location);
        if (request.getURI().getRawQuery() != null) {
            String query = request.getURI().getRawQuery();
            uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                    query, uri.getFragment());
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException("Invalid redirect URI: " + location, ex);
    }

    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final RequestConfig config = clientContext.getRequestConfig();

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (config.isRelativeRedirectsAllowed()) {
                throw new DeltaSyncException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            HttpHost target = clientContext.getTargetHost();
            if (target == null) {
                throw new IllegalStateException("Target host not available " + "in the HTTP context");
            }

            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute("http.protocol.redirect-locations");
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute("http.protocol.redirect-locations", redirectLocations);
    }

    if (config.isCircularRedirectsAllowed()) {
        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new DeltaSyncException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new DeltaSyncException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}