Example usage for java.net URI isAbsolute

List of usage examples for java.net URI isAbsolute

Introduction

In this page you can find the example usage for java.net URI isAbsolute.

Prototype

public boolean isAbsolute() 

Source Link

Document

Tells whether or not this URI is absolute.

Usage

From source file:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java

protected void parseDispatchStack(DispatchLayer dispatchLayer) throws ReaderException {
    URI typeUri = mapTypeFromRaven(dispatchLayer.getRaven(), dispatchLayer.getClazz());
    ObjectNode procConfig = parserState.get().getCurrentConfiguration().getJsonAsObjectNode();

    try {/*from   ww  w.j a va2s.c o  m*/
        Configuration dispatchConfig = parseConfiguration(dispatchLayer.getConfigBean());
        URI relUri = INTERNAL_DISPATCH_PREFIX.relativize(typeUri);
        String name;
        if (!relUri.isAbsolute()) {
            /*
             * It's an internal layer. We'll put it under the name which
             * we'll cleverly fish out of the URI path, eg. "retry" or
             * "parallelize"
             */
            name = relUri.getPath().toLowerCase();
            if (dispatchConfig != null && dispatchConfig.getJson().size() > 0)
                // But only if non-empty (non-default)
                procConfig.put(name, dispatchConfig.getJson());
        } else {
            ObjectNode json;
            if (dispatchConfig != null && dispatchConfig.getJson().isObject())
                json = dispatchConfig.getJsonAsObjectNode();
            else {
                /*
                 * We'll still need to create an objectNode to keep _type
                 * and _below
                 */
                json = procConfig.objectNode();
                if (dispatchConfig != null)
                    // We'll put the non-objectnode here
                    json.put("_config", dispatchConfig.getJson());
            }

            /*
             * Not really much to go from here, we don't want to use the
             * typeUri as the name as third-party layers in theory could be
             * added several times for same type
             */
            name = randomUUID().toString();
            json.put("_type", typeUri.toString());
            // Might be null - meaning "top"
            json.put("_below", parserState.get().getPreviousDispatchLayerName());
            procConfig.put(name, json);
        }
        parserState.get().setPreviousDispatchLayerName(name);
    } catch (JAXBException ex) {
        String message = "Can't parse configuration for dispatch layer in "
                + parserState.get().getCurrentProcessor();
        if (isStrict())
            throw new ReaderException(message, ex);
        logger.log(WARNING, message, ex);
    }
}

From source file:org.robolectric.shadows.httpclient.DefaultRequestDirector.java

protected void rewriteRequestURI(final RequestWrapper request, final HttpRoute route) throws ProtocolException {
    try {/*from  w  w w  .j  a  v  a2s.  c o  m*/

        URI uri = request.getURI();
        if (route.getProxyHost() != null && !route.isTunnelled()) {
            // Make sure the request URI is absolute
            if (!uri.isAbsolute()) {
                HttpHost target = route.getTargetHost();
                uri = URIUtils.rewriteURI(uri, target);
                request.setURI(uri);
            }
        } else {
            // Make sure the request URI is relative
            if (uri.isAbsolute()) {
                uri = URIUtils.rewriteURI(uri, null);
                request.setURI(uri);
            }
        }

    } catch (URISyntaxException ex) {
        throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex);
    }
}

From source file:org.dita.dost.module.GenMapAndTopicListModule.java

/**
 * add FlagImangesSet to Properties, which needn't to change the dir level,
 * just ouput to the ouput dir.//from w  w w  . ja v  a 2  s.c o  m
 *
 * @param prop job configuration
 * @param set absolute flag image files
 */
private void addFlagImagesSetToProperties(final Job prop, final Set<URI> set) {
    final Set<URI> newSet = new LinkedHashSet<>(128);
    for (final URI file : set) {
        //            assert file.isAbsolute();
        if (file.isAbsolute()) {
            // no need to append relative path before absolute paths
            newSet.add(file.normalize());
        } else {
            // In ant, all the file separator should be slash, so we need to
            // replace all the back slash with slash.
            newSet.add(file.normalize());
        }
    }

    // write list attribute to file
    final String fileKey = org.dita.dost.util.Constants.REL_FLAGIMAGE_LIST.substring(0,
            org.dita.dost.util.Constants.REL_FLAGIMAGE_LIST.lastIndexOf("list")) + "file";
    prop.setProperty(fileKey, org.dita.dost.util.Constants.REL_FLAGIMAGE_LIST.substring(0,
            org.dita.dost.util.Constants.REL_FLAGIMAGE_LIST.lastIndexOf("list")) + ".list");
    final File list = new File(job.tempDir, prop.getProperty(fileKey));
    try (Writer bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(list)))) {
        final Iterator<URI> it = newSet.iterator();
        while (it.hasNext()) {
            bufferedWriter.write(it.next().getPath());
            if (it.hasNext()) {
                bufferedWriter.write("\n");
            }
        }
        bufferedWriter.flush();
    } catch (final IOException e) {
        logger.error(e.getMessage(), e);
    }

    prop.setProperty(org.dita.dost.util.Constants.REL_FLAGIMAGE_LIST, StringUtils.join(newSet, COMMA));
}

From source file:org.apache.http.impl.client.DefaultRequestDirector.java

protected void rewriteRequestURI(final RequestWrapper request, final HttpRoute route) throws ProtocolException {
    try {//from   ww  w . j a  va  2  s  . c o m

        URI uri = request.getURI();
        if (route.getProxyHost() != null && !route.isTunnelled()) {
            // Make sure the request URI is absolute
            if (!uri.isAbsolute()) {
                final HttpHost target = route.getTargetHost();
                uri = URIUtils.rewriteURI(uri, target, true);
            } else {
                uri = URIUtils.rewriteURI(uri);
            }
        } else {
            // Make sure the request URI is relative
            if (uri.isAbsolute()) {
                uri = URIUtils.rewriteURI(uri, null, true);
            } else {
                uri = URIUtils.rewriteURI(uri);
            }
        }
        request.setURI(uri);

    } catch (final URISyntaxException ex) {
        throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex);
    }
}

From source file:org.apache.http2.impl.client.DefaultRequestDirector.java

protected void rewriteRequestURI(final RequestWrapper request, final HttpRoute route) throws ProtocolException {
    try {//  w  ww .j  a  va  2 s.c  o m

        URI uri = request.getURI();
        if (route.getProxyHost() != null && !route.isTunnelled()) {
            // Make sure the request URI is absolute
            if (!uri.isAbsolute()) {
                HttpHost target = route.getTargetHost();
                uri = URIUtils.rewriteURI(uri, target, true);
            } else {
                uri = URIUtils.rewriteURI(uri);
            }
        } else {
            // Make sure the request URI is relative
            if (uri.isAbsolute()) {
                uri = URIUtils.rewriteURI(uri, null, true);
            } else {
                uri = URIUtils.rewriteURI(uri);
            }
        }
        request.setURI(uri);

    } catch (URISyntaxException ex) {
        throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex);
    }
}

From source file:gr.iti.mklab.bubing.parser.ITIHTMLParser.java

@Override
public byte[] parse(final URI uri, final HttpResponse httpResponse, final LinkReceiver linkReceiver)
        throws IOException {
    guessedCharset = "ISO-8859-1";

    final HttpEntity entity = httpResponse.getEntity();

    // TODO: check if it will make sense to use getValue() of entity
    // Try to guess using headers
    final Header contentTypeHeader = entity.getContentType();
    if (contentTypeHeader != null) {
        final String headerCharset = getCharsetNameFromHeader(contentTypeHeader.getValue());
        if (headerCharset != null)
            guessedCharset = headerCharset;
    }//from   ww w .j  a  v  a2s .co  m

    final InputStream contentStream = entity.getContent();

    /* Note that the bubing-guessed-charset header and the header guessed by inspecting
    the entity content are complementary. The first is supposed to appear when parsing
       a store, the second while crawling. They should be aligned. This is a bit tricky,
       but we want to avoid the dependency on "rewindable" streams while parsing. */

    final Header bubingGuessedCharsetHeader = httpResponse instanceof WarcRecord
            ? ((WarcRecord) httpResponse).getWarcHeader(WarcHeader.Name.BUBING_GUESSED_CHARSET)
            : null;

    if (bubingGuessedCharsetHeader != null)
        guessedCharset = bubingGuessedCharsetHeader.getValue();
    else {
        if (contentStream instanceof InspectableFileCachedInputStream) {
            final InspectableFileCachedInputStream inspectableStream = (InspectableFileCachedInputStream) contentStream;
            final String metaCharset = getCharsetName(inspectableStream.buffer, inspectableStream.inspectable);
            if (metaCharset != null)
                guessedCharset = metaCharset;
        }
    }

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Guessing charset \"{}\" for URL {}", guessedCharset, uri);

    Charset charset = Charsets.ISO_8859_1; // Fallback
    try {
        charset = Charset.forName(guessedCharset);
    } catch (IllegalCharsetNameException e) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Response for {} contained an illegal charset name: \"{}\"", uri, guessedCharset);
    } catch (UnsupportedCharsetException e) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Response for {} contained an unsupported charset: \"{}\"", uri, guessedCharset);
    }

    linkReceiver.init(uri);
    if (textProcessor != null)
        textProcessor.init(uri);

    // Get location if present
    location = null;
    metaLocation = null;

    final Header locationHeader = httpResponse.getFirstHeader(HttpHeaders.LOCATION);
    if (locationHeader != null) {
        final URI location = BURL.parse(locationHeader.getValue());
        if (location != null) {
            // This shouldn't happen by standard, but people unfortunately does it.
            if (!location.isAbsolute() && LOGGER.isDebugEnabled())
                LOGGER.debug("Found relative header location URL: \"{}\"", location);
            linkReceiver.location(this.location = uri.resolve(location));
        }
    }

    @SuppressWarnings("resource")
    final StreamedSource streamedSource = new StreamedSource(new InputStreamReader(contentStream, charset));
    if (buffer != null)
        streamedSource.setBuffer(buffer);
    if (digestAppendable != null)
        digestAppendable.init(crossAuthorityDuplicates ? null : uri);
    URI base = uri;

    int lastSegmentEnd = 0;
    int inSpecialText = 0;
    for (Segment segment : streamedSource) {
        if (segment.getEnd() > lastSegmentEnd) {
            lastSegmentEnd = segment.getEnd();
            if (segment instanceof StartTag) {
                final StartTag startTag = (StartTag) segment;
                if (startTag.getTagType() != StartTagType.NORMAL)
                    continue;
                final String name = startTag.getName();
                if ((name == HTMLElementName.STYLE || name == HTMLElementName.SCRIPT)
                        && !startTag.isSyntacticalEmptyElementTag())
                    inSpecialText++;

                if (digestAppendable != null)
                    digestAppendable.startTag(startTag);
                // TODO: detect flow breakers
                if (linkReceiver == null)
                    continue; // No link receiver, nothing to do.

                // IFRAME or FRAME + SRC
                if (name == HTMLElementName.IFRAME || name == HTMLElementName.FRAME
                        || name == HTMLElementName.EMBED)
                    process(linkReceiver, base, startTag.getAttributeValue("src"),
                            startTag.getAttributeValue("name"), true);
                else if (name == HTMLElementName.IMG) {
                    processImageURL(uri, base, startTag.getAttributeValue("src"),
                            startTag.getAttributeValue("alt"));
                } else if (name == HTMLElementName.SCRIPT)
                    process(linkReceiver, base, startTag.getAttributeValue("src"), null, false);
                else if (name == HTMLElementName.OBJECT)
                    process(linkReceiver, base, startTag.getAttributeValue("data"),
                            startTag.getAttributeValue("name"), true);
                else if (name == HTMLElementName.A || name == HTMLElementName.AREA
                        || name == HTMLElementName.LINK)
                    process(linkReceiver, base, startTag.getAttributeValue("href"), null, true);
                else if (name == HTMLElementName.BASE) {
                    String s = startTag.getAttributeValue("href");
                    if (s != null) {
                        final URI link = BURL.parse(s);
                        if (link != null) {
                            if (link.isAbsolute())
                                base = link;
                            else if (LOGGER.isDebugEnabled())
                                LOGGER.debug("Found relative BASE URL: \"{}\"", link);
                        }
                    }
                }

                // META REFRESH/LOCATION
                else if (name == HTMLElementName.META) {
                    final String equiv = startTag.getAttributeValue("http-equiv");
                    final String content = startTag.getAttributeValue("content");
                    if (equiv != null && content != null) {
                        equiv.toLowerCase();

                        // http-equiv="refresh" content="0;URL=http://foo.bar/..."
                        if (equiv.equals("refresh")) {

                            final int pos = URLEQUAL_PATTERN.search(content);
                            if (pos != -1) {
                                final String urlPattern = content.substring(pos + URLEQUAL_PATTERN.length());
                                final URI refresh = BURL.parse(urlPattern);
                                if (refresh != null) {
                                    // This shouldn't happen by standard, but people unfortunately does it.
                                    if (!refresh.isAbsolute() && LOGGER.isDebugEnabled())
                                        LOGGER.debug("Found relative META refresh URL: \"{}\"", urlPattern);
                                    linkReceiver.metaRefresh(base.resolve(refresh));
                                }
                            }
                        }

                        // http-equiv="location" content="http://foo.bar/..."
                        if (equiv.equals("location")) {
                            final URI metaLocation = BURL.parse(content);
                            if (metaLocation != null) {
                                // This shouldn't happen by standard, but people unfortunately does it.
                                if (!metaLocation.isAbsolute() && LOGGER.isDebugEnabled())
                                    LOGGER.debug("Found relative META location URL: \"{}\"", content);
                                linkReceiver.metaLocation(this.metaLocation = base.resolve(metaLocation));
                            }
                        }
                    }
                }
            } else if (segment instanceof EndTag) {
                final EndTag endTag = (EndTag) segment;
                final String name = endTag.getName();
                if (name == HTMLElementName.STYLE || name == HTMLElementName.SCRIPT) {
                    inSpecialText = Math.max(0, inSpecialText - 1); // Ignore extra closing tags
                }

                if (digestAppendable != null) {
                    if (endTag.getTagType() != EndTagType.NORMAL)
                        continue;
                    digestAppendable.endTag(endTag);
                }
            } else if (inSpecialText == 0) {
                if (textProcessor != null) {
                    if (segment instanceof CharacterReference)
                        ((CharacterReference) segment).appendCharTo(textProcessor);
                    else
                        textProcessor.append(segment);
                }
                if (digestAppendable != null) {
                    if (segment instanceof CharacterReference)
                        ((CharacterReference) segment).appendCharTo(digestAppendable);
                    else
                        digestAppendable.append(segment);
                }
            }
        }
    }

    if (DigestAppendable.DEBUG)
        if (digestAppendable != null) {
            System.err.println("Closing " + digestAppendable.debugFile + " for " + uri);
            digestAppendable.debugStream.close();
        }

    return digestAppendable != null ? digestAppendable.digest() : null;
}

From source file:dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest.java

private String getAbsoluteURIAsString(String uriAsString) throws BackendMethodFailedException {
    URI predURI;
    try {/*from   w ww.j  av a2s  .co m*/
        predURI = new URI(uriAsString);
    } catch (URISyntaxException e) {
        //TODO This is not a backend exception
        throw new BackendMethodFailedException("Failed to parse uriAsString as an URI", e);
    }
    if (!predURI.isAbsolute()) {
        uriAsString = "info:fedora/" + uriAsString;
    }
    return uriAsString;
}

From source file:org.apache.http.impl.client.DefaultRequestDirector.java

public HttpResponse execute(final HttpHost targetHost, final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {

    context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
    context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

    HttpHost target = targetHost;/*ww w  .  ja  va2  s .com*/

    final HttpRequest orig = request;
    final RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    final HttpRoute origRoute = determineRoute(target, origWrapper, context);

    virtualHost = (HttpHost) origWrapper.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

    // HTTPCLIENT-1092 - add the port if necessary
    if (virtualHost != null && virtualHost.getPort() == -1) {
        final HttpHost host = (target != null) ? target : origRoute.getTargetHost();
        final int port = host.getPort();
        if (port != -1) {
            virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
        }
    }

    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);

    boolean reuse = false;
    boolean done = false;
    try {
        HttpResponse response = null;
        while (!done) {
            // In this loop, the RoutedRequest may be replaced by a
            // followup request and route. The request and route passed
            // in the method arguments will be replaced. The original
            // request is still available in 'orig'.

            final RequestWrapper wrapper = roureq.getRequest();
            final HttpRoute route = roureq.getRoute();
            response = null;

            // See if we have a user token bound to the execution context
            Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

            // Allocate connection if needed
            if (managedConn == null) {
                final ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
                if (orig instanceof AbortableHttpRequest) {
                    ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
                }

                final long timeout = HttpClientParams.getConnectionManagerTimeout(params);
                try {
                    managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
                } catch (final InterruptedException interrupted) {
                    Thread.currentThread().interrupt();
                    throw new InterruptedIOException();
                }

                if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                    // validate connection
                    if (managedConn.isOpen()) {
                        this.log.debug("Stale connection check");
                        if (managedConn.isStale()) {
                            this.log.debug("Stale connection detected");
                            managedConn.close();
                        }
                    }
                }
            }

            if (orig instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
            }

            try {
                tryConnect(roureq, context);
            } catch (final TunnelRefusedException ex) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage());
                }
                response = ex.getResponse();
                break;
            }

            final String userinfo = wrapper.getURI().getUserInfo();
            if (userinfo != null) {
                targetAuthState.update(new BasicScheme(), new UsernamePasswordCredentials(userinfo));
            }

            // Get target.  Even if there's virtual host, we may need the target to set the port.
            if (virtualHost != null) {
                target = virtualHost;
            } else {
                final URI requestURI = wrapper.getURI();
                if (requestURI.isAbsolute()) {
                    target = URIUtils.extractHost(requestURI);
                }
            }
            if (target == null) {
                target = route.getTargetHost();
            }

            // Reset headers on the request wrapper
            wrapper.resetHeaders();
            // Re-write request URI if needed
            rewriteRequestURI(wrapper, route);

            // Populate the execution context
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
            context.setAttribute(ClientContext.ROUTE, route);
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);

            // Run request protocol interceptors
            requestExec.preProcess(wrapper, httpProcessor, context);

            response = tryExecute(roureq, context);
            if (response == null) {
                // Need to start over
                continue;
            }

            // Run response protocol interceptors
            response.setParams(params);
            requestExec.postProcess(response, httpProcessor, context);

            // The connection is in or can be brought to a re-usable state.
            reuse = reuseStrategy.keepAlive(response, context);
            if (reuse) {
                // Set the idle duration of this connection
                final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                if (this.log.isDebugEnabled()) {
                    final String s;
                    if (duration > 0) {
                        s = "for " + duration + " " + TimeUnit.MILLISECONDS;
                    } else {
                        s = "indefinitely";
                    }
                    this.log.debug("Connection can be kept alive " + s);
                }
                managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
            }

            final RoutedRequest followup = handleResponse(roureq, response, context);
            if (followup == null) {
                done = true;
            } else {
                if (reuse) {
                    // Make sure the response body is fully consumed, if present
                    final HttpEntity entity = response.getEntity();
                    EntityUtils.consume(entity);
                    // entity consumed above is not an auto-release entity,
                    // need to mark the connection re-usable explicitly
                    managedConn.markReusable();
                } else {
                    managedConn.close();
                    if (proxyAuthState.getState().compareTo(AuthProtocolState.CHALLENGED) > 0
                            && proxyAuthState.getAuthScheme() != null
                            && proxyAuthState.getAuthScheme().isConnectionBased()) {
                        this.log.debug("Resetting proxy auth state");
                        proxyAuthState.reset();
                    }
                    if (targetAuthState.getState().compareTo(AuthProtocolState.CHALLENGED) > 0
                            && targetAuthState.getAuthScheme() != null
                            && targetAuthState.getAuthScheme().isConnectionBased()) {
                        this.log.debug("Resetting target auth state");
                        targetAuthState.reset();
                    }
                }
                // check if we can use the same connection for the followup
                if (!followup.getRoute().equals(roureq.getRoute())) {
                    releaseConnection();
                }
                roureq = followup;
            }

            if (managedConn != null) {
                if (userToken == null) {
                    userToken = userTokenHandler.getUserToken(context);
                    context.setAttribute(ClientContext.USER_TOKEN, userToken);
                }
                if (userToken != null) {
                    managedConn.setState(userToken);
                }
            }

        } // while not done

        // check for entity, release connection if possible
        if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse) {
                managedConn.markReusable();
            }
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }

        return response;

    } catch (final ConnectionShutdownException ex) {
        final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
        ioex.initCause(ex);
        throw ioex;
    } catch (final HttpException ex) {
        abortConnection();
        throw ex;
    } catch (final IOException ex) {
        abortConnection();
        throw ex;
    } catch (final RuntimeException ex) {
        abortConnection();
        throw ex;
    }
}

From source file:org.apache.http2.impl.client.DefaultRequestDirector.java

public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {

    context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
    context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

    HttpRequest orig = request;/*from w ww.  j  a  v  a  2 s.c o  m*/
    RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    HttpRoute origRoute = determineRoute(target, origWrapper, context);

    virtualHost = (HttpHost) origWrapper.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

    // HTTPCLIENT-1092 - add the port if necessary
    if (virtualHost != null && virtualHost.getPort() == -1) {
        HttpHost host = (target != null) ? target : origRoute.getTargetHost();
        int port = host.getPort();
        if (port != -1) {
            virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
        }
    }

    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);

    boolean reuse = false;
    boolean done = false;
    try {
        HttpResponse response = null;
        while (!done) {
            // In this loop, the RoutedRequest may be replaced by a
            // followup request and route. The request and route passed
            // in the method arguments will be replaced. The original
            // request is still available in 'orig'.

            RequestWrapper wrapper = roureq.getRequest();
            HttpRoute route = roureq.getRoute();
            response = null;

            // See if we have a user token bound to the execution context
            Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

            // Allocate connection if needed
            if (managedConn == null) {
                ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
                if (orig instanceof AbortableHttpRequest) {
                    ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
                }

                long timeout = HttpClientParams.getConnectionManagerTimeout(params);
                try {
                    managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
                } catch (InterruptedException interrupted) {
                    InterruptedIOException iox = new InterruptedIOException();
                    iox.initCause(interrupted);
                    throw iox;
                }

                if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                    // validate connection
                    if (managedConn.isOpen()) {
                        this.log.debug("Stale connection check");
                        if (managedConn.isStale()) {
                            this.log.debug("Stale connection detected");
                            managedConn.close();
                        }
                    }
                }
            }

            if (orig instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
            }

            try {
                tryConnect(roureq, context);
            } catch (TunnelRefusedException ex) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage());
                }
                response = ex.getResponse();
                break;
            }

            String userinfo = wrapper.getURI().getUserInfo();
            if (userinfo != null) {
                targetAuthState.update(new BasicScheme(), new UsernamePasswordCredentials(userinfo));
            }

            HttpHost proxy = route.getProxyHost();
            if (virtualHost != null) {
                target = virtualHost;
            } else {
                URI requestURI = wrapper.getURI();
                if (requestURI.isAbsolute()) {
                    target = new HttpHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
                }
            }
            if (target == null) {
                target = route.getTargetHost();
            }

            // Reset headers on the request wrapper
            wrapper.resetHeaders();
            // Re-write request URI if needed
            rewriteRequestURI(wrapper, route);

            // Populate the execution context
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
            context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);

            // Run request protocol interceptors
            requestExec.preProcess(wrapper, httpProcessor, context);

            response = tryExecute(roureq, context);
            if (response == null) {
                // Need to start over
                continue;
            }

            // Run response protocol interceptors
            response.setParams(params);
            requestExec.postProcess(response, httpProcessor, context);

            // The connection is in or can be brought to a re-usable state.
            reuse = reuseStrategy.keepAlive(response, context);
            if (reuse) {
                // Set the idle duration of this connection
                long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                if (this.log.isDebugEnabled()) {
                    String s;
                    if (duration > 0) {
                        s = "for " + duration + " " + TimeUnit.MILLISECONDS;
                    } else {
                        s = "indefinitely";
                    }
                    this.log.debug("Connection can be kept alive " + s);
                }
                managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
            }

            RoutedRequest followup = handleResponse(roureq, response, context);
            if (followup == null) {
                done = true;
            } else {
                if (reuse) {
                    // Make sure the response body is fully consumed, if present
                    HttpEntity entity = response.getEntity();
                    EntityUtils.consume(entity);
                    // entity consumed above is not an auto-release entity,
                    // need to mark the connection re-usable explicitly
                    managedConn.markReusable();
                } else {
                    managedConn.close();
                    if (proxyAuthState.getState().compareTo(AuthProtocolState.CHALLENGED) > 0
                            && proxyAuthState.getAuthScheme() != null
                            && proxyAuthState.getAuthScheme().isConnectionBased()) {
                        this.log.debug("Resetting proxy auth state");
                        proxyAuthState.reset();
                    }
                    if (targetAuthState.getState().compareTo(AuthProtocolState.CHALLENGED) > 0
                            && targetAuthState.getAuthScheme() != null
                            && targetAuthState.getAuthScheme().isConnectionBased()) {
                        this.log.debug("Resetting target auth state");
                        targetAuthState.reset();
                    }
                }
                // check if we can use the same connection for the followup
                if (!followup.getRoute().equals(roureq.getRoute())) {
                    releaseConnection();
                }
                roureq = followup;
            }

            if (managedConn != null) {
                if (userToken == null) {
                    userToken = userTokenHandler.getUserToken(context);
                    context.setAttribute(ClientContext.USER_TOKEN, userToken);
                }
                if (userToken != null) {
                    managedConn.setState(userToken);
                }
            }

        } // while not done

        // check for entity, release connection if possible
        if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse)
                managedConn.markReusable();
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }

        return response;

    } catch (ConnectionShutdownException ex) {
        InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
        ioex.initCause(ex);
        throw ioex;
    } catch (HttpException ex) {
        abortConnection();
        throw ex;
    } catch (IOException ex) {
        abortConnection();
        throw ex;
    } catch (RuntimeException ex) {
        abortConnection();
        throw ex;
    }
}

From source file:org.dita.dost.module.GenMapAndTopicListModule.java

private void parseInputParameters(final AbstractPipelineInput input) {
    ditaDir = toFile(input.getAttribute(ANT_INVOKER_EXT_PARAM_DITADIR));
    if (!ditaDir.isAbsolute()) {
        throw new IllegalArgumentException("DITA-OT installation directory " + ditaDir + " must be absolute");
    }//from w  ww. ja  v a  2 s .c o  m
    ditavalFile = toFile(input.getAttribute(ANT_INVOKER_PARAM_DITAVAL));
    xmlValidate = Boolean.valueOf(input.getAttribute(ANT_INVOKER_EXT_PARAM_VALIDATE));
    transtype = input.getAttribute(ANT_INVOKER_EXT_PARAM_TRANSTYPE);
    gramcache = "yes".equalsIgnoreCase(input.getAttribute(ANT_INVOKER_EXT_PARAM_GRAMCACHE));
    setSystemid = "yes".equalsIgnoreCase(input.getAttribute(ANT_INVOKER_EXT_PARAN_SETSYSTEMID));
    final String mode = input.getAttribute(ANT_INVOKER_EXT_PARAM_PROCESSING_MODE);
    processingMode = mode != null ? Mode.valueOf(mode.toUpperCase()) : Mode.LAX;
    genDebugInfo = Boolean.valueOf(input.getAttribute(ANT_INVOKER_EXT_PARAM_GENERATE_DEBUG_ATTR));

    // For the output control
    job.setGeneratecopyouter(input.getAttribute(ANT_INVOKER_EXT_PARAM_GENERATECOPYOUTTER));
    job.setOutterControl(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTTERCONTROL));
    job.setOnlyTopicInMap(Boolean.valueOf(input.getAttribute(ANT_INVOKER_EXT_PARAM_ONLYTOPICINMAP)));

    // Set the OutputDir
    final File path = toFile(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTPUTDIR));
    if (path.isAbsolute()) {
        job.setOutputDir(path);
    } else {
        throw new IllegalArgumentException("Output directory " + path + " must be absolute");
    }

    final File basedir = toFile(input.getAttribute(ANT_INVOKER_PARAM_BASEDIR));

    final URI ditaInputDir = toURI(input.getAttribute(ANT_INVOKER_EXT_PARAM_INPUTDIR));
    if (ditaInputDir != null) {
        if (ditaInputDir.isAbsolute()) {
            baseInputDir = ditaInputDir;
        } else if (ditaInputDir.getPath() != null && ditaInputDir.getPath().startsWith(URI_SEPARATOR)) {
            baseInputDir = setScheme(ditaInputDir, "file");
        } else {
            // XXX Shouldn't this be resolved to current directory, not Ant script base directory?
            baseInputDir = basedir.toURI().resolve(ditaInputDir);
        }
        assert baseInputDir.isAbsolute();
    }

    final URI ditaInput = toURI(input.getAttribute(ANT_INVOKER_PARAM_INPUTMAP));
    if (ditaInput.isAbsolute()) {
        rootFile = ditaInput;
    } else if (ditaInput.getPath() != null && ditaInput.getPath().startsWith(URI_SEPARATOR)) {
        rootFile = setScheme(ditaInput, "file");
    } else if (baseInputDir != null) {
        rootFile = baseInputDir.resolve(ditaInput);
    } else {
        rootFile = basedir.toURI().resolve(ditaInput);
    }
    assert rootFile.isAbsolute();

    if (baseInputDir == null) {
        baseInputDir = rootFile.resolve(".");
    }
    assert baseInputDir.isAbsolute();

    profilingEnabled = true;
    if (input.getAttribute(ANT_INVOKER_PARAM_PROFILING_ENABLED) != null) {
        profilingEnabled = Boolean.parseBoolean(input.getAttribute(ANT_INVOKER_PARAM_PROFILING_ENABLED));
    }
    if (profilingEnabled) {
        if (ditavalFile != null && !ditavalFile.isAbsolute()) {
            // XXX Shouldn't this be resolved to current directory, not Ant script base directory?
            ditavalFile = new File(basedir, ditavalFile.getPath()).getAbsoluteFile();
        }
    }

    // create the keydef file for scheme files
    schemekeydefMap = new HashMap<>();

    // Set the mapDir
    job.setInputFile(rootFile);
}